Compare commits
251 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1087591ff6 | |||
| 21c570c64c | |||
| 83432cf1c4 | |||
| 017c58d5bf | |||
| 1ce2f5d273 | |||
| 727fa7ed58 | |||
| 4057b3f611 | |||
| 7c8761a049 | |||
| a3f74b8567 | |||
| 82ecf31867 | |||
| e114312c0c | |||
| e7894480f3 | |||
| 6cc7cfde10 | |||
| a7bfe660fc | |||
| 09f6e5346d | |||
| bea0c0e6f0 | |||
| cc6375104c | |||
| 4b58b7cd46 | |||
| 8ab8ae5205 | |||
| 0769022878 | |||
| 06a122dd34 | |||
| fb6b469e9f | |||
| 504d0bbe36 | |||
| ac1d6d64f2 | |||
| 5470b4dab6 | |||
| 22a6544373 | |||
| 04b7505094 | |||
| 2056417749 | |||
| 748c871af4 | |||
| 53f1381c3b | |||
| 4a3ebb674e | |||
| 2b570a432a | |||
| 5412a0eb49 | |||
| 7b4e702da9 | |||
| e32697e7ee | |||
| d8a75fc8dd | |||
| 6cb48bb6cc | |||
| e78785de7c | |||
| 915d4570df | |||
| 48d6e82f43 | |||
| 46c32df421 | |||
| 686d14b6e5 | |||
| 561ebf0ce3 | |||
| b8e10f340c | |||
| 9c70dc762f | |||
| 8f0a49493c | |||
| e7af4d4821 | |||
| 83bc209489 | |||
| 9b6cc63158 | |||
| 96d224a5a3 | |||
| 97249db546 | |||
| 46e10ebdd8 | |||
| 4ebfacfc21 | |||
| f86749e85d | |||
| 3cc37dac55 | |||
| 5483a1aa77 | |||
| e5acad5091 | |||
| 1688fa9633 | |||
| 1967d97c31 | |||
| 79b154515d | |||
| 9b4d8fc001 | |||
| cb1f43871a | |||
| a2be5b7f52 | |||
| 708d6ddb41 | |||
| 0fb015f6d3 | |||
| c5d59dfdf9 | |||
| 4b277eaeab | |||
| f35bad78d4 | |||
| 0740abcf16 | |||
| 377da4fff6 | |||
| 84c79d8812 | |||
| a0c2d7995b | |||
| d3196a783f | |||
| 4c989a48c4 | |||
| 7c1f8df590 | |||
| 5bb46ebb97 | |||
| cbcebf6e28 | |||
| 2013a2eb70 | |||
| de89175c8e | |||
| 4e1bb0bbcf | |||
| 24a4487d0b | |||
| 24bb7bed40 | |||
| 6b56f62532 | |||
| c38529546f | |||
| 08e1219f77 | |||
| 62842f5aa8 | |||
| 13662dd0d5 | |||
| 07c3548401 | |||
| 0f50939625 | |||
| a64d1edbf4 | |||
| a62f1bd6e8 | |||
| 63ce4107c6 | |||
| a136d68e8c | |||
| 61a5077d4d | |||
| bd529d9041 | |||
| 5cdcc487d4 | |||
| ca2b1acbb9 | |||
| 77b681a40e | |||
| c6f9e5db61 | |||
| 2ec4ae3f98 | |||
| 5074bb4f28 | |||
| 9fef4bea59 | |||
| b50e43c239 | |||
| 7ec9311df2 | |||
| 1f6cf1ecaf | |||
| 9413507997 | |||
| bf0e52fc01 | |||
| c520eb7777 | |||
| d6d4b1200e | |||
| a1f3cfd3ff | |||
| 261dbdc23c | |||
| 4c0d0afceb | |||
| b79caceae6 | |||
| ed749fb606 | |||
| f200ba7f7c | |||
| 0efd4a5fc3 | |||
| 2238370088 | |||
| 364db124d1 | |||
| f1ec0a330b | |||
| 72de65d670 | |||
| 3405a1cda3 | |||
| fc6fa8b419 | |||
| cf2c8a611c | |||
| bd323fca35 | |||
| a067a20a02 | |||
| 99c4328830 | |||
| 1df438d18d | |||
| 366d3d1b25 | |||
| 17a6a4f314 | |||
| 8600449f69 | |||
| 3d47bd50d9 | |||
| 20df471683 | |||
| 5487c7c862 | |||
| c1829fe21b | |||
| b1ad6f02d2 | |||
| 01a1836659 | |||
| b616e10ceb | |||
| d07c4c2c5e | |||
| 7485e2ce24 | |||
| 8f52b5016a | |||
| 5c0808c2cb | |||
| 9d01c120e5 | |||
| ec8cfeac77 | |||
| 7c833f1e9b | |||
| 08cc30a90f | |||
| 8288cd7579 | |||
| 55da551971 | |||
| ff3b24b50e | |||
| 88cae4018a | |||
| 96fbc3f720 | |||
| fd25821e39 | |||
| cdd02e9f3d | |||
| fabbd81f22 | |||
| ace32b37cf | |||
| f1eae8a40b | |||
| ca655f351d | |||
| 40081c2464 | |||
| f1f809f54b | |||
| e8fd1b503b | |||
| 390b3ee876 | |||
| 80976609c7 | |||
| 17eea0183f | |||
| 6980781f89 | |||
| 3350039f05 | |||
| 0bdc0c74d1 | |||
| cccc829cef | |||
| fa1a915e9c | |||
| e5992b5145 | |||
| 42472f6b03 | |||
| c56e08e681 | |||
| 7e87965418 | |||
| e115d459f7 | |||
| dd39e59304 | |||
| 2efc04a3c3 | |||
| 2b20f4b2e2 | |||
| 419c68c024 | |||
| 8889803dd7 | |||
| 9c5517768f | |||
| 4aa85a9c2d | |||
| a77b3b10ee | |||
| 532f4c3e25 | |||
| 04629e73b6 | |||
| 696193c571 | |||
| 38e256c4fb | |||
| 64a78406ed | |||
| 59297ec52f | |||
| 0ff6832dc1 | |||
| 56a8928631 | |||
| 266c6d595d | |||
| b2e0816968 | |||
| dc47583565 | |||
| 26dd3bb387 | |||
| fabfe601c6 | |||
| 662aa47de6 | |||
| c3d9d10d5d | |||
| 9926533049 | |||
| 4d72017b97 | |||
| 45734c051e | |||
| db8471bb16 | |||
| 0dc6f5894f | |||
| c9769aa17a | |||
| 07b4d654b4 | |||
| b65827038f | |||
| d768da72c6 | |||
| 7385efff1a | |||
| 3e2e97e572 | |||
| ae68a33c1e | |||
| deea59fdbf | |||
| b90f86b081 | |||
| f6f5866118 | |||
| b1e69135b8 | |||
| 0c7f34a28a | |||
| c53fcde5d7 | |||
| 81a620af12 | |||
| 5f44a0ca20 | |||
| 5d2cf945f3 | |||
| 227a38fa89 | |||
| abcc004606 | |||
| 64391503c2 | |||
| 92b75d1926 | |||
| e072d0c894 | |||
| cc40493ec6 | |||
| 3a78a84610 | |||
| 692cbd9a80 | |||
| 8f01588221 | |||
| f6fc836e79 | |||
| 9c303e0a82 | |||
| cb8e46919f | |||
| 279806da2b | |||
| 90fa487d1b | |||
| b58bb267a1 | |||
| 6af76c4d80 | |||
| 43de0104e2 | |||
| d624eaeb57 | |||
| 6ad40242b3 | |||
| 2ccab42894 | |||
| 424153cfc7 | |||
| 19508dcd19 | |||
| a16b6fce54 | |||
| 0327eaffe3 | |||
| b13aef944c | |||
| 9ed5190bfe | |||
| 3d5a923caf | |||
| 2af2c0e86a | |||
| d376a82ccc | |||
| 3008cbcb50 | |||
| e75c93ddf4 | |||
| 42a318b501 | |||
| ecb737ec67 | |||
| 0f3baec6cb | |||
| 764d684846 |
@@ -0,0 +1,156 @@
|
||||
---
|
||||
name: openspec-apply-change
|
||||
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.3.1"
|
||||
---
|
||||
|
||||
Implement tasks from an OpenSpec change.
|
||||
|
||||
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
|
||||
|
||||
2. **Check status to understand the schema**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used (e.g., "spec-driven")
|
||||
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
|
||||
|
||||
3. **Get apply instructions**
|
||||
|
||||
```bash
|
||||
openspec instructions apply --change "<name>" --json
|
||||
```
|
||||
|
||||
This returns:
|
||||
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
|
||||
- Progress (total, complete, remaining)
|
||||
- Task list with status
|
||||
- Dynamic instruction based on current state
|
||||
|
||||
**Handle states:**
|
||||
- If `state: "blocked"` (missing artifacts): show message, suggest using openspec-continue-change
|
||||
- If `state: "all_done"`: congratulate, suggest archive
|
||||
- Otherwise: proceed to implementation
|
||||
|
||||
4. **Read context files**
|
||||
|
||||
Read every file path listed under `contextFiles` from the apply instructions output.
|
||||
The files depend on the schema being used:
|
||||
- **spec-driven**: proposal, specs, design, tasks
|
||||
- Other schemas: follow the contextFiles from CLI output
|
||||
|
||||
5. **Show current progress**
|
||||
|
||||
Display:
|
||||
- Schema being used
|
||||
- Progress: "N/M tasks complete"
|
||||
- Remaining tasks overview
|
||||
- Dynamic instruction from CLI
|
||||
|
||||
6. **Implement tasks (loop until done or blocked)**
|
||||
|
||||
For each pending task:
|
||||
- Show which task is being worked on
|
||||
- Make the code changes required
|
||||
- Keep changes minimal and focused
|
||||
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
|
||||
- Continue to next task
|
||||
|
||||
**Pause if:**
|
||||
- Task is unclear → ask for clarification
|
||||
- Implementation reveals a design issue → suggest updating artifacts
|
||||
- Error or blocker encountered → report and wait for guidance
|
||||
- User interrupts
|
||||
|
||||
7. **On completion or pause, show status**
|
||||
|
||||
Display:
|
||||
- Tasks completed this session
|
||||
- Overall progress: "N/M tasks complete"
|
||||
- If all done: suggest archive
|
||||
- If paused: explain why and wait for guidance
|
||||
|
||||
**Output During Implementation**
|
||||
|
||||
```
|
||||
## Implementing: <change-name> (schema: <schema-name>)
|
||||
|
||||
Working on task 3/7: <task description>
|
||||
[...implementation happening...]
|
||||
✓ Task complete
|
||||
|
||||
Working on task 4/7: <task description>
|
||||
[...implementation happening...]
|
||||
✓ Task complete
|
||||
```
|
||||
|
||||
**Output On Completion**
|
||||
|
||||
```
|
||||
## Implementation Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Progress:** 7/7 tasks complete ✓
|
||||
|
||||
### Completed This Session
|
||||
- [x] Task 1
|
||||
- [x] Task 2
|
||||
...
|
||||
|
||||
All tasks complete! Ready to archive this change.
|
||||
```
|
||||
|
||||
**Output On Pause (Issue Encountered)**
|
||||
|
||||
```
|
||||
## Implementation Paused
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Progress:** 4/7 tasks complete
|
||||
|
||||
### Issue Encountered
|
||||
<description of the issue>
|
||||
|
||||
**Options:**
|
||||
1. <option 1>
|
||||
2. <option 2>
|
||||
3. Other approach
|
||||
|
||||
What would you like to do?
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Keep going through tasks until done or blocked
|
||||
- Always read context files before starting (from the apply instructions output)
|
||||
- If task is ambiguous, pause and ask before implementing
|
||||
- If implementation reveals issues, pause and suggest artifact updates
|
||||
- Keep code changes minimal and scoped to each task
|
||||
- Update task checkbox immediately after completing each task
|
||||
- Pause on errors, blockers, or unclear requirements - don't guess
|
||||
- Use contextFiles from CLI output, don't assume specific file names
|
||||
|
||||
**Fluid Workflow Integration**
|
||||
|
||||
This skill supports the "actions on a change" model:
|
||||
|
||||
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
|
||||
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
|
||||
@@ -0,0 +1,114 @@
|
||||
---
|
||||
name: openspec-archive-change
|
||||
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.3.1"
|
||||
---
|
||||
|
||||
Archive a completed change in the experimental workflow.
|
||||
|
||||
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **If no change name provided, prompt for selection**
|
||||
|
||||
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
|
||||
|
||||
Show only active changes (not already archived).
|
||||
Include the schema used for each change if available.
|
||||
|
||||
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||
|
||||
2. **Check artifact completion status**
|
||||
|
||||
Run `openspec status --change "<name>" --json` to check artifact completion.
|
||||
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used
|
||||
- `artifacts`: List of artifacts with their status (`done` or other)
|
||||
|
||||
**If any artifacts are not `done`:**
|
||||
- Display warning listing incomplete artifacts
|
||||
- Use **AskUserQuestion tool** to confirm user wants to proceed
|
||||
- Proceed if user confirms
|
||||
|
||||
3. **Check task completion status**
|
||||
|
||||
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
|
||||
|
||||
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
|
||||
|
||||
**If incomplete tasks found:**
|
||||
- Display warning showing count of incomplete tasks
|
||||
- Use **AskUserQuestion tool** to confirm user wants to proceed
|
||||
- Proceed if user confirms
|
||||
|
||||
**If no tasks file exists:** Proceed without task-related warning.
|
||||
|
||||
4. **Assess delta spec sync state**
|
||||
|
||||
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
|
||||
|
||||
**If delta specs exist:**
|
||||
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
|
||||
- Determine what changes would be applied (adds, modifications, removals, renames)
|
||||
- Show a combined summary before prompting
|
||||
|
||||
**Prompt options:**
|
||||
- If changes needed: "Sync now (recommended)", "Archive without syncing"
|
||||
- If already synced: "Archive now", "Sync anyway", "Cancel"
|
||||
|
||||
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
|
||||
|
||||
5. **Perform the archive**
|
||||
|
||||
Create the archive directory if it doesn't exist:
|
||||
```bash
|
||||
mkdir -p openspec/changes/archive
|
||||
```
|
||||
|
||||
Generate target name using current date: `YYYY-MM-DD-<change-name>`
|
||||
|
||||
**Check if target already exists:**
|
||||
- If yes: Fail with error, suggest renaming existing archive or using different date
|
||||
- If no: Move the change directory to archive
|
||||
|
||||
```bash
|
||||
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
|
||||
```
|
||||
|
||||
6. **Display summary**
|
||||
|
||||
Show archive completion summary including:
|
||||
- Change name
|
||||
- Schema that was used
|
||||
- Archive location
|
||||
- Whether specs were synced (if applicable)
|
||||
- Note about any warnings (incomplete artifacts/tasks)
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```
|
||||
## Archive Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
|
||||
**Specs:** ✓ Synced to main specs (or "No delta specs" or "Sync skipped")
|
||||
|
||||
All artifacts complete. All tasks complete.
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Always prompt for change selection if not provided
|
||||
- Use artifact graph (openspec status --json) for completion checking
|
||||
- Don't block archive on warnings - just inform and confirm
|
||||
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
|
||||
- Show clear summary of what happened
|
||||
- If sync is requested, use openspec-sync-specs approach (agent-driven)
|
||||
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
|
||||
@@ -0,0 +1,246 @@
|
||||
---
|
||||
name: openspec-bulk-archive-change
|
||||
description: Archive multiple completed changes at once. Use when archiving several parallel changes.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.3.1"
|
||||
---
|
||||
|
||||
Archive multiple completed changes in a single operation.
|
||||
|
||||
This skill allows you to batch-archive changes, handling spec conflicts intelligently by checking the codebase to determine what's actually implemented.
|
||||
|
||||
**Input**: None required (prompts for selection)
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Get active changes**
|
||||
|
||||
Run `openspec list --json` to get all active changes.
|
||||
|
||||
If no active changes exist, inform user and stop.
|
||||
|
||||
2. **Prompt for change selection**
|
||||
|
||||
Use **AskUserQuestion tool** with multi-select to let user choose changes:
|
||||
- Show each change with its schema
|
||||
- Include an option for "All changes"
|
||||
- Allow any number of selections (1+ works, 2+ is the typical use case)
|
||||
|
||||
**IMPORTANT**: Do NOT auto-select. Always let the user choose.
|
||||
|
||||
3. **Batch validation - gather status for all selected changes**
|
||||
|
||||
For each selected change, collect:
|
||||
|
||||
a. **Artifact status** - Run `openspec status --change "<name>" --json`
|
||||
- Parse `schemaName` and `artifacts` list
|
||||
- Note which artifacts are `done` vs other states
|
||||
|
||||
b. **Task completion** - Read `openspec/changes/<name>/tasks.md`
|
||||
- Count `- [ ]` (incomplete) vs `- [x]` (complete)
|
||||
- If no tasks file exists, note as "No tasks"
|
||||
|
||||
c. **Delta specs** - Check `openspec/changes/<name>/specs/` directory
|
||||
- List which capability specs exist
|
||||
- For each, extract requirement names (lines matching `### Requirement: <name>`)
|
||||
|
||||
4. **Detect spec conflicts**
|
||||
|
||||
Build a map of `capability -> [changes that touch it]`:
|
||||
|
||||
```
|
||||
auth -> [change-a, change-b] <- CONFLICT (2+ changes)
|
||||
api -> [change-c] <- OK (only 1 change)
|
||||
```
|
||||
|
||||
A conflict exists when 2+ selected changes have delta specs for the same capability.
|
||||
|
||||
5. **Resolve conflicts agentically**
|
||||
|
||||
**For each conflict**, investigate the codebase:
|
||||
|
||||
a. **Read the delta specs** from each conflicting change to understand what each claims to add/modify
|
||||
|
||||
b. **Search the codebase** for implementation evidence:
|
||||
- Look for code implementing requirements from each delta spec
|
||||
- Check for related files, functions, or tests
|
||||
|
||||
c. **Determine resolution**:
|
||||
- If only one change is actually implemented -> sync that one's specs
|
||||
- If both implemented -> apply in chronological order (older first, newer overwrites)
|
||||
- If neither implemented -> skip spec sync, warn user
|
||||
|
||||
d. **Record resolution** for each conflict:
|
||||
- Which change's specs to apply
|
||||
- In what order (if both)
|
||||
- Rationale (what was found in codebase)
|
||||
|
||||
6. **Show consolidated status table**
|
||||
|
||||
Display a table summarizing all changes:
|
||||
|
||||
```
|
||||
| Change | Artifacts | Tasks | Specs | Conflicts | Status |
|
||||
|---------------------|-----------|-------|---------|-----------|--------|
|
||||
| schema-management | Done | 5/5 | 2 delta | None | Ready |
|
||||
| project-config | Done | 3/3 | 1 delta | None | Ready |
|
||||
| add-oauth | Done | 4/4 | 1 delta | auth (!) | Ready* |
|
||||
| add-verify-skill | 1 left | 2/5 | None | None | Warn |
|
||||
```
|
||||
|
||||
For conflicts, show the resolution:
|
||||
```
|
||||
* Conflict resolution:
|
||||
- auth spec: Will apply add-oauth then add-jwt (both implemented, chronological order)
|
||||
```
|
||||
|
||||
For incomplete changes, show warnings:
|
||||
```
|
||||
Warnings:
|
||||
- add-verify-skill: 1 incomplete artifact, 3 incomplete tasks
|
||||
```
|
||||
|
||||
7. **Confirm batch operation**
|
||||
|
||||
Use **AskUserQuestion tool** with a single confirmation:
|
||||
|
||||
- "Archive N changes?" with options based on status
|
||||
- Options might include:
|
||||
- "Archive all N changes"
|
||||
- "Archive only N ready changes (skip incomplete)"
|
||||
- "Cancel"
|
||||
|
||||
If there are incomplete changes, make clear they'll be archived with warnings.
|
||||
|
||||
8. **Execute archive for each confirmed change**
|
||||
|
||||
Process changes in the determined order (respecting conflict resolution):
|
||||
|
||||
a. **Sync specs** if delta specs exist:
|
||||
- Use the openspec-sync-specs approach (agent-driven intelligent merge)
|
||||
- For conflicts, apply in resolved order
|
||||
- Track if sync was done
|
||||
|
||||
b. **Perform the archive**:
|
||||
```bash
|
||||
mkdir -p openspec/changes/archive
|
||||
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
|
||||
```
|
||||
|
||||
c. **Track outcome** for each change:
|
||||
- Success: archived successfully
|
||||
- Failed: error during archive (record error)
|
||||
- Skipped: user chose not to archive (if applicable)
|
||||
|
||||
9. **Display summary**
|
||||
|
||||
Show final results:
|
||||
|
||||
```
|
||||
## Bulk Archive Complete
|
||||
|
||||
Archived 3 changes:
|
||||
- schema-management-cli -> archive/2026-01-19-schema-management-cli/
|
||||
- project-config -> archive/2026-01-19-project-config/
|
||||
- add-oauth -> archive/2026-01-19-add-oauth/
|
||||
|
||||
Skipped 1 change:
|
||||
- add-verify-skill (user chose not to archive incomplete)
|
||||
|
||||
Spec sync summary:
|
||||
- 4 delta specs synced to main specs
|
||||
- 1 conflict resolved (auth: applied both in chronological order)
|
||||
```
|
||||
|
||||
If any failures:
|
||||
```
|
||||
Failed 1 change:
|
||||
- some-change: Archive directory already exists
|
||||
```
|
||||
|
||||
**Conflict Resolution Examples**
|
||||
|
||||
Example 1: Only one implemented
|
||||
```
|
||||
Conflict: specs/auth/spec.md touched by [add-oauth, add-jwt]
|
||||
|
||||
Checking add-oauth:
|
||||
- Delta adds "OAuth Provider Integration" requirement
|
||||
- Searching codebase... found src/auth/oauth.ts implementing OAuth flow
|
||||
|
||||
Checking add-jwt:
|
||||
- Delta adds "JWT Token Handling" requirement
|
||||
- Searching codebase... no JWT implementation found
|
||||
|
||||
Resolution: Only add-oauth is implemented. Will sync add-oauth specs only.
|
||||
```
|
||||
|
||||
Example 2: Both implemented
|
||||
```
|
||||
Conflict: specs/api/spec.md touched by [add-rest-api, add-graphql]
|
||||
|
||||
Checking add-rest-api (created 2026-01-10):
|
||||
- Delta adds "REST Endpoints" requirement
|
||||
- Searching codebase... found src/api/rest.ts
|
||||
|
||||
Checking add-graphql (created 2026-01-15):
|
||||
- Delta adds "GraphQL Schema" requirement
|
||||
- Searching codebase... found src/api/graphql.ts
|
||||
|
||||
Resolution: Both implemented. Will apply add-rest-api specs first,
|
||||
then add-graphql specs (chronological order, newer takes precedence).
|
||||
```
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```
|
||||
## Bulk Archive Complete
|
||||
|
||||
Archived N changes:
|
||||
- <change-1> -> archive/YYYY-MM-DD-<change-1>/
|
||||
- <change-2> -> archive/YYYY-MM-DD-<change-2>/
|
||||
|
||||
Spec sync summary:
|
||||
- N delta specs synced to main specs
|
||||
- No conflicts (or: M conflicts resolved)
|
||||
```
|
||||
|
||||
**Output On Partial Success**
|
||||
|
||||
```
|
||||
## Bulk Archive Complete (partial)
|
||||
|
||||
Archived N changes:
|
||||
- <change-1> -> archive/YYYY-MM-DD-<change-1>/
|
||||
|
||||
Skipped M changes:
|
||||
- <change-2> (user chose not to archive incomplete)
|
||||
|
||||
Failed K changes:
|
||||
- <change-3>: Archive directory already exists
|
||||
```
|
||||
|
||||
**Output When No Changes**
|
||||
|
||||
```
|
||||
## No Changes to Archive
|
||||
|
||||
No active changes found. Create a new change to get started.
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Allow any number of changes (1+ is fine, 2+ is the typical use case)
|
||||
- Always prompt for selection, never auto-select
|
||||
- Detect spec conflicts early and resolve by checking codebase
|
||||
- When both changes are implemented, apply specs in chronological order
|
||||
- Skip spec sync only when implementation is missing (warn user)
|
||||
- Show clear per-change status before confirming
|
||||
- Use single confirmation for entire batch
|
||||
- Track and report all outcomes (success/skip/fail)
|
||||
- Preserve .openspec.yaml when moving to archive
|
||||
- Archive directory target uses current date: YYYY-MM-DD-<name>
|
||||
- If archive target exists, fail that change but continue with others
|
||||
@@ -0,0 +1,118 @@
|
||||
---
|
||||
name: openspec-continue-change
|
||||
description: Continue working on an OpenSpec change by creating the next artifact. Use when the user wants to progress their change, create the next artifact, or continue their workflow.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.3.1"
|
||||
---
|
||||
|
||||
Continue working on a change by creating the next artifact.
|
||||
|
||||
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **If no change name provided, prompt for selection**
|
||||
|
||||
Run `openspec list --json` to get available changes sorted by most recently modified. Then use the **AskUserQuestion tool** to let the user select which change to work on.
|
||||
|
||||
Present the top 3-4 most recently modified changes as options, showing:
|
||||
- Change name
|
||||
- Schema (from `schema` field if present, otherwise "spec-driven")
|
||||
- Status (e.g., "0/5 tasks", "complete", "no tasks")
|
||||
- How recently it was modified (from `lastModified` field)
|
||||
|
||||
Mark the most recently modified change as "(Recommended)" since it's likely what the user wants to continue.
|
||||
|
||||
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||
|
||||
2. **Check current status**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to understand current state. The response includes:
|
||||
- `schemaName`: The workflow schema being used (e.g., "spec-driven")
|
||||
- `artifacts`: Array of artifacts with their status ("done", "ready", "blocked")
|
||||
- `isComplete`: Boolean indicating if all artifacts are complete
|
||||
|
||||
3. **Act based on status**:
|
||||
|
||||
---
|
||||
|
||||
**If all artifacts are complete (`isComplete: true`)**:
|
||||
- Congratulate the user
|
||||
- Show final status including the schema used
|
||||
- Suggest: "All artifacts created! You can now implement this change or archive it."
|
||||
- STOP
|
||||
|
||||
---
|
||||
|
||||
**If artifacts are ready to create** (status shows artifacts with `status: "ready"`):
|
||||
- Pick the FIRST artifact with `status: "ready"` from the status output
|
||||
- Get its instructions:
|
||||
```bash
|
||||
openspec instructions <artifact-id> --change "<name>" --json
|
||||
```
|
||||
- Parse the JSON. The key fields are:
|
||||
- `context`: Project background (constraints for you - do NOT include in output)
|
||||
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
|
||||
- `template`: The structure to use for your output file
|
||||
- `instruction`: Schema-specific guidance
|
||||
- `outputPath`: Where to write the artifact
|
||||
- `dependencies`: Completed artifacts to read for context
|
||||
- **Create the artifact file**:
|
||||
- Read any completed dependency files for context
|
||||
- Use `template` as the structure - fill in its sections
|
||||
- Apply `context` and `rules` as constraints when writing - but do NOT copy them into the file
|
||||
- Write to the output path specified in instructions
|
||||
- Show what was created and what's now unlocked
|
||||
- STOP after creating ONE artifact
|
||||
|
||||
---
|
||||
|
||||
**If no artifacts are ready (all blocked)**:
|
||||
- This shouldn't happen with a valid schema
|
||||
- Show status and suggest checking for issues
|
||||
|
||||
4. **After creating an artifact, show progress**
|
||||
```bash
|
||||
openspec status --change "<name>"
|
||||
```
|
||||
|
||||
**Output**
|
||||
|
||||
After each invocation, show:
|
||||
- Which artifact was created
|
||||
- Schema workflow being used
|
||||
- Current progress (N/M complete)
|
||||
- What artifacts are now unlocked
|
||||
- Prompt: "Want to continue? Just ask me to continue or tell me what to do next."
|
||||
|
||||
**Artifact Creation Guidelines**
|
||||
|
||||
The artifact types and their purpose depend on the schema. Use the `instruction` field from the instructions output to understand what to create.
|
||||
|
||||
Common artifact patterns:
|
||||
|
||||
**spec-driven schema** (proposal → specs → design → tasks):
|
||||
- **proposal.md**: Ask user about the change if not clear. Fill in Why, What Changes, Capabilities, Impact.
|
||||
- The Capabilities section is critical - each capability listed will need a spec file.
|
||||
- **specs/<capability>/spec.md**: Create one spec per capability listed in the proposal's Capabilities section (use the capability name, not the change name).
|
||||
- **design.md**: Document technical decisions, architecture, and implementation approach.
|
||||
- **tasks.md**: Break down implementation into checkboxed tasks.
|
||||
|
||||
For other schemas, follow the `instruction` field from the CLI output.
|
||||
|
||||
**Guardrails**
|
||||
- Create ONE artifact per invocation
|
||||
- Always read dependency artifacts before creating a new one
|
||||
- Never skip artifacts or create out of order
|
||||
- If context is unclear, ask the user before creating
|
||||
- Verify the artifact file exists after writing before marking progress
|
||||
- Use the schema's artifact sequence, don't assume specific artifact names
|
||||
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
|
||||
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
|
||||
- These guide what you write, but should never appear in the output
|
||||
@@ -0,0 +1,288 @@
|
||||
---
|
||||
name: openspec-explore
|
||||
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.3.1"
|
||||
---
|
||||
|
||||
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
|
||||
|
||||
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
|
||||
|
||||
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
|
||||
|
||||
---
|
||||
|
||||
## The Stance
|
||||
|
||||
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
|
||||
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
|
||||
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
|
||||
- **Adaptive** - Follow interesting threads, pivot when new information emerges
|
||||
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
|
||||
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
|
||||
|
||||
---
|
||||
|
||||
## What You Might Do
|
||||
|
||||
Depending on what the user brings, you might:
|
||||
|
||||
**Explore the problem space**
|
||||
- Ask clarifying questions that emerge from what they said
|
||||
- Challenge assumptions
|
||||
- Reframe the problem
|
||||
- Find analogies
|
||||
|
||||
**Investigate the codebase**
|
||||
- Map existing architecture relevant to the discussion
|
||||
- Find integration points
|
||||
- Identify patterns already in use
|
||||
- Surface hidden complexity
|
||||
|
||||
**Compare options**
|
||||
- Brainstorm multiple approaches
|
||||
- Build comparison tables
|
||||
- Sketch tradeoffs
|
||||
- Recommend a path (if asked)
|
||||
|
||||
**Visualize**
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ Use ASCII diagrams liberally │
|
||||
├─────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌────────┐ ┌────────┐ │
|
||||
│ │ State │────────▶│ State │ │
|
||||
│ │ A │ │ B │ │
|
||||
│ └────────┘ └────────┘ │
|
||||
│ │
|
||||
│ System diagrams, state machines, │
|
||||
│ data flows, architecture sketches, │
|
||||
│ dependency graphs, comparison tables │
|
||||
│ │
|
||||
└─────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Surface risks and unknowns**
|
||||
- Identify what could go wrong
|
||||
- Find gaps in understanding
|
||||
- Suggest spikes or investigations
|
||||
|
||||
---
|
||||
|
||||
## OpenSpec Awareness
|
||||
|
||||
You have full context of the OpenSpec system. Use it naturally, don't force it.
|
||||
|
||||
### Check for context
|
||||
|
||||
At the start, quickly check what exists:
|
||||
```bash
|
||||
openspec list --json
|
||||
```
|
||||
|
||||
This tells you:
|
||||
- If there are active changes
|
||||
- Their names, schemas, and status
|
||||
- What the user might be working on
|
||||
|
||||
### When no change exists
|
||||
|
||||
Think freely. When insights crystallize, you might offer:
|
||||
|
||||
- "This feels solid enough to start a change. Want me to create a proposal?"
|
||||
- Or keep exploring - no pressure to formalize
|
||||
|
||||
### When a change exists
|
||||
|
||||
If the user mentions a change or you detect one is relevant:
|
||||
|
||||
1. **Read existing artifacts for context**
|
||||
- `openspec/changes/<name>/proposal.md`
|
||||
- `openspec/changes/<name>/design.md`
|
||||
- `openspec/changes/<name>/tasks.md`
|
||||
- etc.
|
||||
|
||||
2. **Reference them naturally in conversation**
|
||||
- "Your design mentions using Redis, but we just realized SQLite fits better..."
|
||||
- "The proposal scopes this to premium users, but we're now thinking everyone..."
|
||||
|
||||
3. **Offer to capture when decisions are made**
|
||||
|
||||
| Insight Type | Where to Capture |
|
||||
|----------------------------|--------------------------------|
|
||||
| New requirement discovered | `specs/<capability>/spec.md` |
|
||||
| Requirement changed | `specs/<capability>/spec.md` |
|
||||
| Design decision made | `design.md` |
|
||||
| Scope changed | `proposal.md` |
|
||||
| New work identified | `tasks.md` |
|
||||
| Assumption invalidated | Relevant artifact |
|
||||
|
||||
Example offers:
|
||||
- "That's a design decision. Capture it in design.md?"
|
||||
- "This is a new requirement. Add it to specs?"
|
||||
- "This changes scope. Update the proposal?"
|
||||
|
||||
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
|
||||
|
||||
---
|
||||
|
||||
## What You Don't Have To Do
|
||||
|
||||
- Follow a script
|
||||
- Ask the same questions every time
|
||||
- Produce a specific artifact
|
||||
- Reach a conclusion
|
||||
- Stay on topic if a tangent is valuable
|
||||
- Be brief (this is thinking time)
|
||||
|
||||
---
|
||||
|
||||
## Handling Different Entry Points
|
||||
|
||||
**User brings a vague idea:**
|
||||
```
|
||||
User: I'm thinking about adding real-time collaboration
|
||||
|
||||
You: Real-time collab is a big space. Let me think about this...
|
||||
|
||||
COLLABORATION SPECTRUM
|
||||
════════════════════════════════════════════
|
||||
|
||||
Awareness Coordination Sync
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
┌────────┐ ┌────────┐ ┌────────┐
|
||||
│Presence│ │Cursors │ │ CRDT │
|
||||
│ "3 │ │ Multi │ │Conflict│
|
||||
│online" │ │ select │ │ free │
|
||||
└────────┘ └────────┘ └────────┘
|
||||
│ │ │
|
||||
trivial moderate complex
|
||||
|
||||
Where's your head at?
|
||||
```
|
||||
|
||||
**User brings a specific problem:**
|
||||
```
|
||||
User: The auth system is a mess
|
||||
|
||||
You: [reads codebase]
|
||||
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ CURRENT AUTH FLOW │
|
||||
└─────────────────────────────────────────────┘
|
||||
│
|
||||
┌─────────────┼─────────────┐
|
||||
▼ ▼ ▼
|
||||
┌─────────┐ ┌─────────┐ ┌─────────┐
|
||||
│ Google │ │ GitHub │ │ Email │
|
||||
│ OAuth │ │ OAuth │ │ Magic │
|
||||
└────┬────┘ └────┬────┘ └────┬────┘
|
||||
│ │ │
|
||||
└─────────────┼─────────────┘
|
||||
▼
|
||||
┌───────────┐
|
||||
│ Session │
|
||||
└─────┬─────┘
|
||||
│
|
||||
▼
|
||||
┌───────────┐
|
||||
│ Perms │
|
||||
└───────────┘
|
||||
|
||||
I see three tangles. Which one's burning?
|
||||
```
|
||||
|
||||
**User is stuck mid-implementation:**
|
||||
```
|
||||
User: /opsx:explore add-auth-system
|
||||
The OAuth integration is more complex than expected
|
||||
|
||||
You: [reads change artifacts]
|
||||
|
||||
You're on task 4: "Implement OAuth flow"
|
||||
|
||||
Let me trace what's involved...
|
||||
|
||||
[draws diagram, explores options, suggests paths]
|
||||
|
||||
Want to update the design to reflect this?
|
||||
Or add a spike task to investigate?
|
||||
```
|
||||
|
||||
**User wants to compare options:**
|
||||
```
|
||||
User: Should we use Postgres or SQLite?
|
||||
|
||||
You: Generic answer is boring. What's the context?
|
||||
|
||||
User: A CLI tool that tracks local dev environments
|
||||
|
||||
You: That changes everything.
|
||||
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ CLI TOOL DATA STORAGE │
|
||||
└─────────────────────────────────────────────────┘
|
||||
|
||||
Key constraints:
|
||||
• No daemon running
|
||||
• Must work offline
|
||||
• Single user
|
||||
|
||||
SQLite Postgres
|
||||
Deployment embedded ✓ needs server ✗
|
||||
Offline yes ✓ no ✗
|
||||
Single file yes ✓ no ✗
|
||||
|
||||
SQLite. Not even close.
|
||||
|
||||
Unless... is there a sync component?
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Ending Discovery
|
||||
|
||||
There's no required ending. Discovery might:
|
||||
|
||||
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
|
||||
- **Result in artifact updates**: "Updated design.md with these decisions"
|
||||
- **Just provide clarity**: User has what they need, moves on
|
||||
- **Continue later**: "We can pick this up anytime"
|
||||
|
||||
When it feels like things are crystallizing, you might summarize:
|
||||
|
||||
```
|
||||
## What We Figured Out
|
||||
|
||||
**The problem**: [crystallized understanding]
|
||||
|
||||
**The approach**: [if one emerged]
|
||||
|
||||
**Open questions**: [if any remain]
|
||||
|
||||
**Next steps** (if ready):
|
||||
- Create a change proposal
|
||||
- Keep exploring: just keep talking
|
||||
```
|
||||
|
||||
But this summary is optional. Sometimes the thinking IS the value.
|
||||
|
||||
---
|
||||
|
||||
## Guardrails
|
||||
|
||||
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
|
||||
- **Don't fake understanding** - If something is unclear, dig deeper
|
||||
- **Don't rush** - Discovery is thinking time, not task time
|
||||
- **Don't force structure** - Let patterns emerge naturally
|
||||
- **Don't auto-capture** - Offer to save insights, don't just do it
|
||||
- **Do visualize** - A good diagram is worth many paragraphs
|
||||
- **Do explore the codebase** - Ground discussions in reality
|
||||
- **Do question assumptions** - Including the user's and your own
|
||||
@@ -0,0 +1,101 @@
|
||||
---
|
||||
name: openspec-ff-change
|
||||
description: Fast-forward through OpenSpec artifact creation. Use when the user wants to quickly create all artifacts needed for implementation without stepping through each one individually.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.3.1"
|
||||
---
|
||||
|
||||
Fast-forward through artifact creation - generate everything needed to start implementation in one go.
|
||||
|
||||
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **If no clear input provided, ask what they want to build**
|
||||
|
||||
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
|
||||
> "What change do you want to work on? Describe what you want to build or fix."
|
||||
|
||||
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
|
||||
|
||||
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
|
||||
|
||||
2. **Create the change directory**
|
||||
```bash
|
||||
openspec new change "<name>"
|
||||
```
|
||||
This creates a scaffolded change at `openspec/changes/<name>/`.
|
||||
|
||||
3. **Get the artifact build order**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to get:
|
||||
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
|
||||
- `artifacts`: list of all artifacts with their status and dependencies
|
||||
|
||||
4. **Create artifacts in sequence until apply-ready**
|
||||
|
||||
Use the **TodoWrite tool** to track progress through the artifacts.
|
||||
|
||||
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
|
||||
|
||||
a. **For each artifact that is `ready` (dependencies satisfied)**:
|
||||
- Get instructions:
|
||||
```bash
|
||||
openspec instructions <artifact-id> --change "<name>" --json
|
||||
```
|
||||
- The instructions JSON includes:
|
||||
- `context`: Project background (constraints for you - do NOT include in output)
|
||||
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
|
||||
- `template`: The structure to use for your output file
|
||||
- `instruction`: Schema-specific guidance for this artifact type
|
||||
- `outputPath`: Where to write the artifact
|
||||
- `dependencies`: Completed artifacts to read for context
|
||||
- Read any completed dependency files for context
|
||||
- Create the artifact file using `template` as the structure
|
||||
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
|
||||
- Show brief progress: "✓ Created <artifact-id>"
|
||||
|
||||
b. **Continue until all `applyRequires` artifacts are complete**
|
||||
- After creating each artifact, re-run `openspec status --change "<name>" --json`
|
||||
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
|
||||
- Stop when all `applyRequires` artifacts are done
|
||||
|
||||
c. **If an artifact requires user input** (unclear context):
|
||||
- Use **AskUserQuestion tool** to clarify
|
||||
- Then continue with creation
|
||||
|
||||
5. **Show final status**
|
||||
```bash
|
||||
openspec status --change "<name>"
|
||||
```
|
||||
|
||||
**Output**
|
||||
|
||||
After completing all artifacts, summarize:
|
||||
- Change name and location
|
||||
- List of artifacts created with brief descriptions
|
||||
- What's ready: "All artifacts created! Ready for implementation."
|
||||
- Prompt: "Run `/opsx:apply` or ask me to implement to start working on the tasks."
|
||||
|
||||
**Artifact Creation Guidelines**
|
||||
|
||||
- Follow the `instruction` field from `openspec instructions` for each artifact type
|
||||
- The schema defines what each artifact should contain - follow it
|
||||
- Read dependency artifacts for context before creating new ones
|
||||
- Use `template` as the structure for your output file - fill in its sections
|
||||
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
|
||||
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
|
||||
- These guide what you write, but should never appear in the output
|
||||
|
||||
**Guardrails**
|
||||
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
|
||||
- Always read dependency artifacts before creating a new one
|
||||
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
|
||||
- If a change with that name already exists, suggest continuing that change instead
|
||||
- Verify each artifact file exists after writing before proceeding to next
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
name: openspec-new-change
|
||||
description: Start a new OpenSpec change using the experimental artifact workflow. Use when the user wants to create a new feature, fix, or modification with a structured step-by-step approach.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.3.1"
|
||||
---
|
||||
|
||||
Start a new change using the experimental artifact-driven approach.
|
||||
|
||||
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **If no clear input provided, ask what they want to build**
|
||||
|
||||
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
|
||||
> "What change do you want to work on? Describe what you want to build or fix."
|
||||
|
||||
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
|
||||
|
||||
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
|
||||
|
||||
2. **Determine the workflow schema**
|
||||
|
||||
Use the default schema (omit `--schema`) unless the user explicitly requests a different workflow.
|
||||
|
||||
**Use a different schema only if the user mentions:**
|
||||
- A specific schema name → use `--schema <name>`
|
||||
- "show workflows" or "what workflows" → run `openspec schemas --json` and let them choose
|
||||
|
||||
**Otherwise**: Omit `--schema` to use the default.
|
||||
|
||||
3. **Create the change directory**
|
||||
```bash
|
||||
openspec new change "<name>"
|
||||
```
|
||||
Add `--schema <name>` only if the user requested a specific workflow.
|
||||
This creates a scaffolded change at `openspec/changes/<name>/` with the selected schema.
|
||||
|
||||
4. **Show the artifact status**
|
||||
```bash
|
||||
openspec status --change "<name>"
|
||||
```
|
||||
This shows which artifacts need to be created and which are ready (dependencies satisfied).
|
||||
|
||||
5. **Get instructions for the first artifact**
|
||||
The first artifact depends on the schema (e.g., `proposal` for spec-driven).
|
||||
Check the status output to find the first artifact with status "ready".
|
||||
```bash
|
||||
openspec instructions <first-artifact-id> --change "<name>"
|
||||
```
|
||||
This outputs the template and context for creating the first artifact.
|
||||
|
||||
6. **STOP and wait for user direction**
|
||||
|
||||
**Output**
|
||||
|
||||
After completing the steps, summarize:
|
||||
- Change name and location
|
||||
- Schema/workflow being used and its artifact sequence
|
||||
- Current status (0/N artifacts complete)
|
||||
- The template for the first artifact
|
||||
- Prompt: "Ready to create the first artifact? Just describe what this change is about and I'll draft it, or ask me to continue."
|
||||
|
||||
**Guardrails**
|
||||
- Do NOT create any artifacts yet - just show the instructions
|
||||
- Do NOT advance beyond showing the first artifact template
|
||||
- If the name is invalid (not kebab-case), ask for a valid name
|
||||
- If a change with that name already exists, suggest continuing that change instead
|
||||
- Pass --schema if using a non-default workflow
|
||||
@@ -0,0 +1,554 @@
|
||||
---
|
||||
name: openspec-onboard
|
||||
description: Guided onboarding for OpenSpec - walk through a complete workflow cycle with narration and real codebase work.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.3.1"
|
||||
---
|
||||
|
||||
Guide the user through their first complete OpenSpec workflow cycle. This is a teaching experience—you'll do real work in their codebase while explaining each step.
|
||||
|
||||
---
|
||||
|
||||
## Preflight
|
||||
|
||||
Before starting, check if the OpenSpec CLI is installed:
|
||||
|
||||
```bash
|
||||
# Unix/macOS
|
||||
openspec --version 2>&1 || echo "CLI_NOT_INSTALLED"
|
||||
# Windows (PowerShell)
|
||||
# if (Get-Command openspec -ErrorAction SilentlyContinue) { openspec --version } else { echo "CLI_NOT_INSTALLED" }
|
||||
```
|
||||
|
||||
**If CLI not installed:**
|
||||
> OpenSpec CLI is not installed. Install it first, then come back to `/opsx:onboard`.
|
||||
|
||||
Stop here if not installed.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Welcome
|
||||
|
||||
Display:
|
||||
|
||||
```
|
||||
## Welcome to OpenSpec!
|
||||
|
||||
I'll walk you through a complete change cycle—from idea to implementation—using a real task in your codebase. Along the way, you'll learn the workflow by doing it.
|
||||
|
||||
**What we'll do:**
|
||||
1. Pick a small, real task in your codebase
|
||||
2. Explore the problem briefly
|
||||
3. Create a change (the container for our work)
|
||||
4. Build the artifacts: proposal → specs → design → tasks
|
||||
5. Implement the tasks
|
||||
6. Archive the completed change
|
||||
|
||||
**Time:** ~15-20 minutes
|
||||
|
||||
Let's start by finding something to work on.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Task Selection
|
||||
|
||||
### Codebase Analysis
|
||||
|
||||
Scan the codebase for small improvement opportunities. Look for:
|
||||
|
||||
1. **TODO/FIXME comments** - Search for `TODO`, `FIXME`, `HACK`, `XXX` in code files
|
||||
2. **Missing error handling** - `catch` blocks that swallow errors, risky operations without try-catch
|
||||
3. **Functions without tests** - Cross-reference `src/` with test directories
|
||||
4. **Type issues** - `any` types in TypeScript files (`: any`, `as any`)
|
||||
5. **Debug artifacts** - `console.log`, `console.debug`, `debugger` statements in non-debug code
|
||||
6. **Missing validation** - User input handlers without validation
|
||||
|
||||
Also check recent git activity:
|
||||
```bash
|
||||
# Unix/macOS
|
||||
git log --oneline -10 2>/dev/null || echo "No git history"
|
||||
# Windows (PowerShell)
|
||||
# git log --oneline -10 2>$null; if ($LASTEXITCODE -ne 0) { echo "No git history" }
|
||||
```
|
||||
|
||||
### Present Suggestions
|
||||
|
||||
From your analysis, present 3-4 specific suggestions:
|
||||
|
||||
```
|
||||
## Task Suggestions
|
||||
|
||||
Based on scanning your codebase, here are some good starter tasks:
|
||||
|
||||
**1. [Most promising task]**
|
||||
Location: `src/path/to/file.ts:42`
|
||||
Scope: ~1-2 files, ~20-30 lines
|
||||
Why it's good: [brief reason]
|
||||
|
||||
**2. [Second task]**
|
||||
Location: `src/another/file.ts`
|
||||
Scope: ~1 file, ~15 lines
|
||||
Why it's good: [brief reason]
|
||||
|
||||
**3. [Third task]**
|
||||
Location: [location]
|
||||
Scope: [estimate]
|
||||
Why it's good: [brief reason]
|
||||
|
||||
**4. Something else?**
|
||||
Tell me what you'd like to work on.
|
||||
|
||||
Which task interests you? (Pick a number or describe your own)
|
||||
```
|
||||
|
||||
**If nothing found:** Fall back to asking what the user wants to build:
|
||||
> I didn't find obvious quick wins in your codebase. What's something small you've been meaning to add or fix?
|
||||
|
||||
### Scope Guardrail
|
||||
|
||||
If the user picks or describes something too large (major feature, multi-day work):
|
||||
|
||||
```
|
||||
That's a valuable task, but it's probably larger than ideal for your first OpenSpec run-through.
|
||||
|
||||
For learning the workflow, smaller is better—it lets you see the full cycle without getting stuck in implementation details.
|
||||
|
||||
**Options:**
|
||||
1. **Slice it smaller** - What's the smallest useful piece of [their task]? Maybe just [specific slice]?
|
||||
2. **Pick something else** - One of the other suggestions, or a different small task?
|
||||
3. **Do it anyway** - If you really want to tackle this, we can. Just know it'll take longer.
|
||||
|
||||
What would you prefer?
|
||||
```
|
||||
|
||||
Let the user override if they insist—this is a soft guardrail.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Explore Demo
|
||||
|
||||
Once a task is selected, briefly demonstrate explore mode:
|
||||
|
||||
```
|
||||
Before we create a change, let me quickly show you **explore mode**—it's how you think through problems before committing to a direction.
|
||||
```
|
||||
|
||||
Spend 1-2 minutes investigating the relevant code:
|
||||
- Read the file(s) involved
|
||||
- Draw a quick ASCII diagram if it helps
|
||||
- Note any considerations
|
||||
|
||||
```
|
||||
## Quick Exploration
|
||||
|
||||
[Your brief analysis—what you found, any considerations]
|
||||
|
||||
┌─────────────────────────────────────────┐
|
||||
│ [Optional: ASCII diagram if helpful] │
|
||||
└─────────────────────────────────────────┘
|
||||
|
||||
Explore mode (`/opsx:explore`) is for this kind of thinking—investigating before implementing. You can use it anytime you need to think through a problem.
|
||||
|
||||
Now let's create a change to hold our work.
|
||||
```
|
||||
|
||||
**PAUSE** - Wait for user acknowledgment before proceeding.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Create the Change
|
||||
|
||||
**EXPLAIN:**
|
||||
```
|
||||
## Creating a Change
|
||||
|
||||
A "change" in OpenSpec is a container for all the thinking and planning around a piece of work. It lives in `openspec/changes/<name>/` and holds your artifacts—proposal, specs, design, tasks.
|
||||
|
||||
Let me create one for our task.
|
||||
```
|
||||
|
||||
**DO:** Create the change with a derived kebab-case name:
|
||||
```bash
|
||||
openspec new change "<derived-name>"
|
||||
```
|
||||
|
||||
**SHOW:**
|
||||
```
|
||||
Created: `openspec/changes/<name>/`
|
||||
|
||||
The folder structure:
|
||||
```
|
||||
openspec/changes/<name>/
|
||||
├── proposal.md ← Why we're doing this (empty, we'll fill it)
|
||||
├── design.md ← How we'll build it (empty)
|
||||
├── specs/ ← Detailed requirements (empty)
|
||||
└── tasks.md ← Implementation checklist (empty)
|
||||
```
|
||||
|
||||
Now let's fill in the first artifact—the proposal.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: Proposal
|
||||
|
||||
**EXPLAIN:**
|
||||
```
|
||||
## The Proposal
|
||||
|
||||
The proposal captures **why** we're making this change and **what** it involves at a high level. It's the "elevator pitch" for the work.
|
||||
|
||||
I'll draft one based on our task.
|
||||
```
|
||||
|
||||
**DO:** Draft the proposal content (don't save yet):
|
||||
|
||||
```
|
||||
Here's a draft proposal:
|
||||
|
||||
---
|
||||
|
||||
## Why
|
||||
|
||||
[1-2 sentences explaining the problem/opportunity]
|
||||
|
||||
## What Changes
|
||||
|
||||
[Bullet points of what will be different]
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
- `<capability-name>`: [brief description]
|
||||
|
||||
### Modified Capabilities
|
||||
<!-- If modifying existing behavior -->
|
||||
|
||||
## Impact
|
||||
|
||||
- `src/path/to/file.ts`: [what changes]
|
||||
- [other files if applicable]
|
||||
|
||||
---
|
||||
|
||||
Does this capture the intent? I can adjust before we save it.
|
||||
```
|
||||
|
||||
**PAUSE** - Wait for user approval/feedback.
|
||||
|
||||
After approval, save the proposal:
|
||||
```bash
|
||||
openspec instructions proposal --change "<name>" --json
|
||||
```
|
||||
Then write the content to `openspec/changes/<name>/proposal.md`.
|
||||
|
||||
```
|
||||
Proposal saved. This is your "why" document—you can always come back and refine it as understanding evolves.
|
||||
|
||||
Next up: specs.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase 6: Specs
|
||||
|
||||
**EXPLAIN:**
|
||||
```
|
||||
## Specs
|
||||
|
||||
Specs define **what** we're building in precise, testable terms. They use a requirement/scenario format that makes expected behavior crystal clear.
|
||||
|
||||
For a small task like this, we might only need one spec file.
|
||||
```
|
||||
|
||||
**DO:** Create the spec file:
|
||||
```bash
|
||||
# Unix/macOS
|
||||
mkdir -p openspec/changes/<name>/specs/<capability-name>
|
||||
# Windows (PowerShell)
|
||||
# New-Item -ItemType Directory -Force -Path "openspec/changes/<name>/specs/<capability-name>"
|
||||
```
|
||||
|
||||
Draft the spec content:
|
||||
|
||||
```
|
||||
Here's the spec:
|
||||
|
||||
---
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: <Name>
|
||||
|
||||
<Description of what the system should do>
|
||||
|
||||
#### Scenario: <Scenario name>
|
||||
|
||||
- **WHEN** <trigger condition>
|
||||
- **THEN** <expected outcome>
|
||||
- **AND** <additional outcome if needed>
|
||||
|
||||
---
|
||||
|
||||
This format—WHEN/THEN/AND—makes requirements testable. You can literally read them as test cases.
|
||||
```
|
||||
|
||||
Save to `openspec/changes/<name>/specs/<capability>/spec.md`.
|
||||
|
||||
---
|
||||
|
||||
## Phase 7: Design
|
||||
|
||||
**EXPLAIN:**
|
||||
```
|
||||
## Design
|
||||
|
||||
The design captures **how** we'll build it—technical decisions, tradeoffs, approach.
|
||||
|
||||
For small changes, this might be brief. That's fine—not every change needs deep design discussion.
|
||||
```
|
||||
|
||||
**DO:** Draft design.md:
|
||||
|
||||
```
|
||||
Here's the design:
|
||||
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
[Brief context about the current state]
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- [What we're trying to achieve]
|
||||
|
||||
**Non-Goals:**
|
||||
- [What's explicitly out of scope]
|
||||
|
||||
## Decisions
|
||||
|
||||
### Decision 1: [Key decision]
|
||||
|
||||
[Explanation of approach and rationale]
|
||||
|
||||
---
|
||||
|
||||
For a small task, this captures the key decisions without over-engineering.
|
||||
```
|
||||
|
||||
Save to `openspec/changes/<name>/design.md`.
|
||||
|
||||
---
|
||||
|
||||
## Phase 8: Tasks
|
||||
|
||||
**EXPLAIN:**
|
||||
```
|
||||
## Tasks
|
||||
|
||||
Finally, we break the work into implementation tasks—checkboxes that drive the apply phase.
|
||||
|
||||
These should be small, clear, and in logical order.
|
||||
```
|
||||
|
||||
**DO:** Generate tasks based on specs and design:
|
||||
|
||||
```
|
||||
Here are the implementation tasks:
|
||||
|
||||
---
|
||||
|
||||
## 1. [Category or file]
|
||||
|
||||
- [ ] 1.1 [Specific task]
|
||||
- [ ] 1.2 [Specific task]
|
||||
|
||||
## 2. Verify
|
||||
|
||||
- [ ] 2.1 [Verification step]
|
||||
|
||||
---
|
||||
|
||||
Each checkbox becomes a unit of work in the apply phase. Ready to implement?
|
||||
```
|
||||
|
||||
**PAUSE** - Wait for user to confirm they're ready to implement.
|
||||
|
||||
Save to `openspec/changes/<name>/tasks.md`.
|
||||
|
||||
---
|
||||
|
||||
## Phase 9: Apply (Implementation)
|
||||
|
||||
**EXPLAIN:**
|
||||
```
|
||||
## Implementation
|
||||
|
||||
Now we implement each task, checking them off as we go. I'll announce each one and occasionally note how the specs/design informed the approach.
|
||||
```
|
||||
|
||||
**DO:** For each task:
|
||||
|
||||
1. Announce: "Working on task N: [description]"
|
||||
2. Implement the change in the codebase
|
||||
3. Reference specs/design naturally: "The spec says X, so I'm doing Y"
|
||||
4. Mark complete in tasks.md: `- [ ]` → `- [x]`
|
||||
5. Brief status: "✓ Task N complete"
|
||||
|
||||
Keep narration light—don't over-explain every line of code.
|
||||
|
||||
After all tasks:
|
||||
|
||||
```
|
||||
## Implementation Complete
|
||||
|
||||
All tasks done:
|
||||
- [x] Task 1
|
||||
- [x] Task 2
|
||||
- [x] ...
|
||||
|
||||
The change is implemented! One more step—let's archive it.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase 10: Archive
|
||||
|
||||
**EXPLAIN:**
|
||||
```
|
||||
## Archiving
|
||||
|
||||
When a change is complete, we archive it. This moves it from `openspec/changes/` to `openspec/changes/archive/YYYY-MM-DD-<name>/`.
|
||||
|
||||
Archived changes become your project's decision history—you can always find them later to understand why something was built a certain way.
|
||||
```
|
||||
|
||||
**DO:**
|
||||
```bash
|
||||
openspec archive "<name>"
|
||||
```
|
||||
|
||||
**SHOW:**
|
||||
```
|
||||
Archived to: `openspec/changes/archive/YYYY-MM-DD-<name>/`
|
||||
|
||||
The change is now part of your project's history. The code is in your codebase, the decision record is preserved.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase 11: Recap & Next Steps
|
||||
|
||||
```
|
||||
## Congratulations!
|
||||
|
||||
You just completed a full OpenSpec cycle:
|
||||
|
||||
1. **Explore** - Thought through the problem
|
||||
2. **New** - Created a change container
|
||||
3. **Proposal** - Captured WHY
|
||||
4. **Specs** - Defined WHAT in detail
|
||||
5. **Design** - Decided HOW
|
||||
6. **Tasks** - Broke it into steps
|
||||
7. **Apply** - Implemented the work
|
||||
8. **Archive** - Preserved the record
|
||||
|
||||
This same rhythm works for any size change—a small fix or a major feature.
|
||||
|
||||
---
|
||||
|
||||
## Command Reference
|
||||
|
||||
**Core workflow:**
|
||||
|
||||
| Command | What it does |
|
||||
|-------------------|--------------------------------------------|
|
||||
| `/opsx:propose` | Create a change and generate all artifacts |
|
||||
| `/opsx:explore` | Think through problems before/during work |
|
||||
| `/opsx:apply` | Implement tasks from a change |
|
||||
| `/opsx:archive` | Archive a completed change |
|
||||
|
||||
**Additional commands:**
|
||||
|
||||
| Command | What it does |
|
||||
|--------------------|----------------------------------------------------------|
|
||||
| `/opsx:new` | Start a new change, step through artifacts one at a time |
|
||||
| `/opsx:continue` | Continue working on an existing change |
|
||||
| `/opsx:ff` | Fast-forward: create all artifacts at once |
|
||||
| `/opsx:verify` | Verify implementation matches artifacts |
|
||||
|
||||
---
|
||||
|
||||
## What's Next?
|
||||
|
||||
Try `/opsx:propose` on something you actually want to build. You've got the rhythm now!
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Graceful Exit Handling
|
||||
|
||||
### User wants to stop mid-way
|
||||
|
||||
If the user says they need to stop, want to pause, or seem disengaged:
|
||||
|
||||
```
|
||||
No problem! Your change is saved at `openspec/changes/<name>/`.
|
||||
|
||||
To pick up where we left off later:
|
||||
- `/opsx:continue <name>` - Resume artifact creation
|
||||
- `/opsx:apply <name>` - Jump to implementation (if tasks exist)
|
||||
|
||||
The work won't be lost. Come back whenever you're ready.
|
||||
```
|
||||
|
||||
Exit gracefully without pressure.
|
||||
|
||||
### User just wants command reference
|
||||
|
||||
If the user says they just want to see the commands or skip the tutorial:
|
||||
|
||||
```
|
||||
## OpenSpec Quick Reference
|
||||
|
||||
**Core workflow:**
|
||||
|
||||
| Command | What it does |
|
||||
|--------------------------|--------------------------------------------|
|
||||
| `/opsx:propose <name>` | Create a change and generate all artifacts |
|
||||
| `/opsx:explore` | Think through problems (no code changes) |
|
||||
| `/opsx:apply <name>` | Implement tasks |
|
||||
| `/opsx:archive <name>` | Archive when done |
|
||||
|
||||
**Additional commands:**
|
||||
|
||||
| Command | What it does |
|
||||
|---------------------------|-------------------------------------|
|
||||
| `/opsx:new <name>` | Start a new change, step by step |
|
||||
| `/opsx:continue <name>` | Continue an existing change |
|
||||
| `/opsx:ff <name>` | Fast-forward: all artifacts at once |
|
||||
| `/opsx:verify <name>` | Verify implementation |
|
||||
|
||||
Try `/opsx:propose` to start your first change.
|
||||
```
|
||||
|
||||
Exit gracefully.
|
||||
|
||||
---
|
||||
|
||||
## Guardrails
|
||||
|
||||
- **Follow the EXPLAIN → DO → SHOW → PAUSE pattern** at key transitions (after explore, after proposal draft, after tasks, after archive)
|
||||
- **Keep narration light** during implementation—teach without lecturing
|
||||
- **Don't skip phases** even if the change is small—the goal is teaching the workflow
|
||||
- **Pause for acknowledgment** at marked points, but don't over-pause
|
||||
- **Handle exits gracefully**—never pressure the user to continue
|
||||
- **Use real codebase tasks**—don't simulate or use fake examples
|
||||
- **Adjust scope gently**—guide toward smaller tasks but respect user choice
|
||||
@@ -0,0 +1,110 @@
|
||||
---
|
||||
name: openspec-propose
|
||||
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.3.1"
|
||||
---
|
||||
|
||||
Propose a new change - create the change and generate all artifacts in one step.
|
||||
|
||||
I'll create a change with artifacts:
|
||||
- proposal.md (what & why)
|
||||
- design.md (how)
|
||||
- tasks.md (implementation steps)
|
||||
|
||||
When ready to implement, run /opsx:apply
|
||||
|
||||
---
|
||||
|
||||
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **If no clear input provided, ask what they want to build**
|
||||
|
||||
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
|
||||
> "What change do you want to work on? Describe what you want to build or fix."
|
||||
|
||||
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
|
||||
|
||||
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
|
||||
|
||||
2. **Create the change directory**
|
||||
```bash
|
||||
openspec new change "<name>"
|
||||
```
|
||||
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
|
||||
|
||||
3. **Get the artifact build order**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to get:
|
||||
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
|
||||
- `artifacts`: list of all artifacts with their status and dependencies
|
||||
|
||||
4. **Create artifacts in sequence until apply-ready**
|
||||
|
||||
Use the **TodoWrite tool** to track progress through the artifacts.
|
||||
|
||||
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
|
||||
|
||||
a. **For each artifact that is `ready` (dependencies satisfied)**:
|
||||
- Get instructions:
|
||||
```bash
|
||||
openspec instructions <artifact-id> --change "<name>" --json
|
||||
```
|
||||
- The instructions JSON includes:
|
||||
- `context`: Project background (constraints for you - do NOT include in output)
|
||||
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
|
||||
- `template`: The structure to use for your output file
|
||||
- `instruction`: Schema-specific guidance for this artifact type
|
||||
- `outputPath`: Where to write the artifact
|
||||
- `dependencies`: Completed artifacts to read for context
|
||||
- Read any completed dependency files for context
|
||||
- Create the artifact file using `template` as the structure
|
||||
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
|
||||
- Show brief progress: "Created <artifact-id>"
|
||||
|
||||
b. **Continue until all `applyRequires` artifacts are complete**
|
||||
- After creating each artifact, re-run `openspec status --change "<name>" --json`
|
||||
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
|
||||
- Stop when all `applyRequires` artifacts are done
|
||||
|
||||
c. **If an artifact requires user input** (unclear context):
|
||||
- Use **AskUserQuestion tool** to clarify
|
||||
- Then continue with creation
|
||||
|
||||
5. **Show final status**
|
||||
```bash
|
||||
openspec status --change "<name>"
|
||||
```
|
||||
|
||||
**Output**
|
||||
|
||||
After completing all artifacts, summarize:
|
||||
- Change name and location
|
||||
- List of artifacts created with brief descriptions
|
||||
- What's ready: "All artifacts created! Ready for implementation."
|
||||
- Prompt: "Run `/opsx:apply` or ask me to implement to start working on the tasks."
|
||||
|
||||
**Artifact Creation Guidelines**
|
||||
|
||||
- Follow the `instruction` field from `openspec instructions` for each artifact type
|
||||
- The schema defines what each artifact should contain - follow it
|
||||
- Read dependency artifacts for context before creating new ones
|
||||
- Use `template` as the structure for your output file - fill in its sections
|
||||
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
|
||||
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
|
||||
- These guide what you write, but should never appear in the output
|
||||
|
||||
**Guardrails**
|
||||
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
|
||||
- Always read dependency artifacts before creating a new one
|
||||
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
|
||||
- If a change with that name already exists, ask if user wants to continue it or create a new one
|
||||
- Verify each artifact file exists after writing before proceeding to next
|
||||
@@ -0,0 +1,138 @@
|
||||
---
|
||||
name: openspec-sync-specs
|
||||
description: Sync delta specs from a change to main specs. Use when the user wants to update main specs with changes from a delta spec, without archiving the change.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.3.1"
|
||||
---
|
||||
|
||||
Sync delta specs from a change to main specs.
|
||||
|
||||
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
|
||||
|
||||
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **If no change name provided, prompt for selection**
|
||||
|
||||
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
|
||||
|
||||
Show changes that have delta specs (under `specs/` directory).
|
||||
|
||||
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||
|
||||
2. **Find delta specs**
|
||||
|
||||
Look for delta spec files in `openspec/changes/<name>/specs/*/spec.md`.
|
||||
|
||||
Each delta spec file contains sections like:
|
||||
- `## ADDED Requirements` - New requirements to add
|
||||
- `## MODIFIED Requirements` - Changes to existing requirements
|
||||
- `## REMOVED Requirements` - Requirements to remove
|
||||
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
|
||||
|
||||
If no delta specs found, inform user and stop.
|
||||
|
||||
3. **For each delta spec, apply changes to main specs**
|
||||
|
||||
For each capability with a delta spec at `openspec/changes/<name>/specs/<capability>/spec.md`:
|
||||
|
||||
a. **Read the delta spec** to understand the intended changes
|
||||
|
||||
b. **Read the main spec** at `openspec/specs/<capability>/spec.md` (may not exist yet)
|
||||
|
||||
c. **Apply changes intelligently**:
|
||||
|
||||
**ADDED Requirements:**
|
||||
- If requirement doesn't exist in main spec → add it
|
||||
- If requirement already exists → update it to match (treat as implicit MODIFIED)
|
||||
|
||||
**MODIFIED Requirements:**
|
||||
- Find the requirement in main spec
|
||||
- Apply the changes - this can be:
|
||||
- Adding new scenarios (don't need to copy existing ones)
|
||||
- Modifying existing scenarios
|
||||
- Changing the requirement description
|
||||
- Preserve scenarios/content not mentioned in the delta
|
||||
|
||||
**REMOVED Requirements:**
|
||||
- Remove the entire requirement block from main spec
|
||||
|
||||
**RENAMED Requirements:**
|
||||
- Find the FROM requirement, rename to TO
|
||||
|
||||
d. **Create new main spec** if capability doesn't exist yet:
|
||||
- Create `openspec/specs/<capability>/spec.md`
|
||||
- Add Purpose section (can be brief, mark as TBD)
|
||||
- Add Requirements section with the ADDED requirements
|
||||
|
||||
4. **Show summary**
|
||||
|
||||
After applying all changes, summarize:
|
||||
- Which capabilities were updated
|
||||
- What changes were made (requirements added/modified/removed/renamed)
|
||||
|
||||
**Delta Spec Format Reference**
|
||||
|
||||
```markdown
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: New Feature
|
||||
The system SHALL do something new.
|
||||
|
||||
#### Scenario: Basic case
|
||||
- **WHEN** user does X
|
||||
- **THEN** system does Y
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Existing Feature
|
||||
#### Scenario: New scenario to add
|
||||
- **WHEN** user does A
|
||||
- **THEN** system does B
|
||||
|
||||
## REMOVED Requirements
|
||||
|
||||
### Requirement: Deprecated Feature
|
||||
|
||||
## RENAMED Requirements
|
||||
|
||||
- FROM: `### Requirement: Old Name`
|
||||
- TO: `### Requirement: New Name`
|
||||
```
|
||||
|
||||
**Key Principle: Intelligent Merging**
|
||||
|
||||
Unlike programmatic merging, you can apply **partial updates**:
|
||||
- To add a scenario, just include that scenario under MODIFIED - don't copy existing scenarios
|
||||
- The delta represents *intent*, not a wholesale replacement
|
||||
- Use your judgment to merge changes sensibly
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```
|
||||
## Specs Synced: <change-name>
|
||||
|
||||
Updated main specs:
|
||||
|
||||
**<capability-1>**:
|
||||
- Added requirement: "New Feature"
|
||||
- Modified requirement: "Existing Feature" (added 1 scenario)
|
||||
|
||||
**<capability-2>**:
|
||||
- Created new spec file
|
||||
- Added requirement: "Another Feature"
|
||||
|
||||
Main specs are now updated. The change remains active - archive when implementation is complete.
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Read both delta and main specs before making changes
|
||||
- Preserve existing content not mentioned in delta
|
||||
- If something is unclear, ask for clarification
|
||||
- Show what you're changing as you go
|
||||
- The operation should be idempotent - running twice should give same result
|
||||
@@ -0,0 +1,168 @@
|
||||
---
|
||||
name: openspec-verify-change
|
||||
description: Verify implementation matches change artifacts. Use when the user wants to validate that implementation is complete, correct, and coherent before archiving.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.3.1"
|
||||
---
|
||||
|
||||
Verify that an implementation matches the change artifacts (specs, tasks, design).
|
||||
|
||||
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **If no change name provided, prompt for selection**
|
||||
|
||||
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
|
||||
|
||||
Show changes that have implementation tasks (tasks artifact exists).
|
||||
Include the schema used for each change if available.
|
||||
Mark changes with incomplete tasks as "(In Progress)".
|
||||
|
||||
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||
|
||||
2. **Check status to understand the schema**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used (e.g., "spec-driven")
|
||||
- Which artifacts exist for this change
|
||||
|
||||
3. **Get the change directory and load artifacts**
|
||||
|
||||
```bash
|
||||
openspec instructions apply --change "<name>" --json
|
||||
```
|
||||
|
||||
This returns the change directory and `contextFiles` (artifact ID -> array of concrete file paths). Read all available artifacts from `contextFiles`.
|
||||
|
||||
4. **Initialize verification report structure**
|
||||
|
||||
Create a report structure with three dimensions:
|
||||
- **Completeness**: Track tasks and spec coverage
|
||||
- **Correctness**: Track requirement implementation and scenario coverage
|
||||
- **Coherence**: Track design adherence and pattern consistency
|
||||
|
||||
Each dimension can have CRITICAL, WARNING, or SUGGESTION issues.
|
||||
|
||||
5. **Verify Completeness**
|
||||
|
||||
**Task Completion**:
|
||||
- If `contextFiles.tasks` exists, read every file path in it
|
||||
- Parse checkboxes: `- [ ]` (incomplete) vs `- [x]` (complete)
|
||||
- Count complete vs total tasks
|
||||
- If incomplete tasks exist:
|
||||
- Add CRITICAL issue for each incomplete task
|
||||
- Recommendation: "Complete task: <description>" or "Mark as done if already implemented"
|
||||
|
||||
**Spec Coverage**:
|
||||
- If delta specs exist in `openspec/changes/<name>/specs/`:
|
||||
- Extract all requirements (marked with "### Requirement:")
|
||||
- For each requirement:
|
||||
- Search codebase for keywords related to the requirement
|
||||
- Assess if implementation likely exists
|
||||
- If requirements appear unimplemented:
|
||||
- Add CRITICAL issue: "Requirement not found: <requirement name>"
|
||||
- Recommendation: "Implement requirement X: <description>"
|
||||
|
||||
6. **Verify Correctness**
|
||||
|
||||
**Requirement Implementation Mapping**:
|
||||
- For each requirement from delta specs:
|
||||
- Search codebase for implementation evidence
|
||||
- If found, note file paths and line ranges
|
||||
- Assess if implementation matches requirement intent
|
||||
- If divergence detected:
|
||||
- Add WARNING: "Implementation may diverge from spec: <details>"
|
||||
- Recommendation: "Review <file>:<lines> against requirement X"
|
||||
|
||||
**Scenario Coverage**:
|
||||
- For each scenario in delta specs (marked with "#### Scenario:"):
|
||||
- Check if conditions are handled in code
|
||||
- Check if tests exist covering the scenario
|
||||
- If scenario appears uncovered:
|
||||
- Add WARNING: "Scenario not covered: <scenario name>"
|
||||
- Recommendation: "Add test or implementation for scenario: <description>"
|
||||
|
||||
7. **Verify Coherence**
|
||||
|
||||
**Design Adherence**:
|
||||
- If `contextFiles.design` exists:
|
||||
- Extract key decisions (look for sections like "Decision:", "Approach:", "Architecture:")
|
||||
- Verify implementation follows those decisions
|
||||
- If contradiction detected:
|
||||
- Add WARNING: "Design decision not followed: <decision>"
|
||||
- Recommendation: "Update implementation or revise design.md to match reality"
|
||||
- If no design.md: Skip design adherence check, note "No design.md to verify against"
|
||||
|
||||
**Code Pattern Consistency**:
|
||||
- Review new code for consistency with project patterns
|
||||
- Check file naming, directory structure, coding style
|
||||
- If significant deviations found:
|
||||
- Add SUGGESTION: "Code pattern deviation: <details>"
|
||||
- Recommendation: "Consider following project pattern: <example>"
|
||||
|
||||
8. **Generate Verification Report**
|
||||
|
||||
**Summary Scorecard**:
|
||||
```
|
||||
## Verification Report: <change-name>
|
||||
|
||||
### Summary
|
||||
| Dimension | Status |
|
||||
|--------------|------------------|
|
||||
| Completeness | X/Y tasks, N reqs|
|
||||
| Correctness | M/N reqs covered |
|
||||
| Coherence | Followed/Issues |
|
||||
```
|
||||
|
||||
**Issues by Priority**:
|
||||
|
||||
1. **CRITICAL** (Must fix before archive):
|
||||
- Incomplete tasks
|
||||
- Missing requirement implementations
|
||||
- Each with specific, actionable recommendation
|
||||
|
||||
2. **WARNING** (Should fix):
|
||||
- Spec/design divergences
|
||||
- Missing scenario coverage
|
||||
- Each with specific recommendation
|
||||
|
||||
3. **SUGGESTION** (Nice to fix):
|
||||
- Pattern inconsistencies
|
||||
- Minor improvements
|
||||
- Each with specific recommendation
|
||||
|
||||
**Final Assessment**:
|
||||
- If CRITICAL issues: "X critical issue(s) found. Fix before archiving."
|
||||
- If only warnings: "No critical issues. Y warning(s) to consider. Ready for archive (with noted improvements)."
|
||||
- If all clear: "All checks passed. Ready for archive."
|
||||
|
||||
**Verification Heuristics**
|
||||
|
||||
- **Completeness**: Focus on objective checklist items (checkboxes, requirements list)
|
||||
- **Correctness**: Use keyword search, file path analysis, reasonable inference - don't require perfect certainty
|
||||
- **Coherence**: Look for glaring inconsistencies, don't nitpick style
|
||||
- **False Positives**: When uncertain, prefer SUGGESTION over WARNING, WARNING over CRITICAL
|
||||
- **Actionability**: Every issue must have a specific recommendation with file/line references where applicable
|
||||
|
||||
**Graceful Degradation**
|
||||
|
||||
- If only tasks.md exists: verify task completion only, skip spec/design checks
|
||||
- If tasks + specs exist: verify completeness and correctness, skip design
|
||||
- If full artifacts: verify all three dimensions
|
||||
- Always note which checks were skipped and why
|
||||
|
||||
**Output Format**
|
||||
|
||||
Use clear markdown with:
|
||||
- Table for summary scorecard
|
||||
- Grouped lists for issues (CRITICAL/WARNING/SUGGESTION)
|
||||
- Code references in format: `file.ts:123`
|
||||
- Specific, actionable recommendations
|
||||
- No vague suggestions like "consider reviewing"
|
||||
+171
-594
@@ -5,391 +5,62 @@ path: backend/**
|
||||
|
||||
# 后端开发规范
|
||||
|
||||
## 代码完成规范
|
||||
|
||||
### TODO 处理规则
|
||||
- **禁止**在代码中添加 TODO 注释
|
||||
- **必须**根据 TODO 的内容直接完成代码实现
|
||||
- 如果遇到暂时无法完全实现的功能,应该:
|
||||
1. 实现一个可用的基础版本
|
||||
2. 添加清晰的注释说明当前实现的限制和后续改进方向
|
||||
3. 确保代码可以正常编译和运行
|
||||
- **禁止**使用 `// TODO: 实现XXX` 这样的注释
|
||||
- **禁止**使用 `// FIXME:` 或 `// XXX:` 这样的注释
|
||||
- 如果某个功能需要依赖外部资源(如 API、库等),应该:
|
||||
1. 先实现一个占位或模拟实现
|
||||
2. 在注释中说明依赖关系和实现方式
|
||||
3. 确保代码逻辑完整,不会因为未实现的功能而崩溃
|
||||
|
||||
### API 调用实现规则
|
||||
- **必须**查找相关的 API 文档或接口定义
|
||||
- **必须**根据 API 文档完成代码实现
|
||||
- **禁止**在 API 调用处添加 TODO 注释
|
||||
- **禁止**直接返回 mock 数据或硬编码的假数据
|
||||
- **必须**调用真实的 API 或查询真实的数据库
|
||||
- 如果 API 文档不完整,应该:
|
||||
1. 查找项目中已有的类似 API 调用作为参考
|
||||
2. 查看 API 接口定义(如 `PolymarketClobApi.kt`)
|
||||
3. 查看 API 文档(如 `docs/polymarket-api-reference.md`)
|
||||
4. 实现一个可用的版本,包含错误处理
|
||||
- 如果 API 调用失败,应该:
|
||||
1. 返回明确的错误信息
|
||||
2. 记录错误日志
|
||||
3. 返回错误响应,而不是返回 mock 数据
|
||||
|
||||
### 代码完成示例
|
||||
|
||||
```kotlin
|
||||
// ❌ 错误:添加 TODO 注释
|
||||
fun getAccountBalance(accountId: Long?): Result<AccountBalanceResponse> {
|
||||
// TODO: 调用 Polymarket API 查询余额
|
||||
return Result.success(AccountBalanceResponse(usdcBalance = "0"))
|
||||
}
|
||||
|
||||
// ✅ 正确:查找 API 文档并完成实现
|
||||
// 1. 查找 API 接口定义:PolymarketClobApi.getActiveOrders()
|
||||
// 2. 查找 API 文档:docs/polymarket-api-reference.md
|
||||
// 3. 实现完整的 API 调用逻辑,调用真实的 API
|
||||
fun getAccountBalance(accountId: Long?): Result<AccountBalanceResponse> {
|
||||
return try {
|
||||
val account = getAccount(accountId) ?: return Result.failure(IllegalArgumentException("账户不存在"))
|
||||
|
||||
// 如果账户没有配置 API 凭证,返回错误而不是 mock 数据
|
||||
if (account.apiKey == null || account.apiSecret == null || account.apiPassphrase == null) {
|
||||
return Result.failure(IllegalStateException("账户未配置 API 凭证,无法查询余额"))
|
||||
}
|
||||
|
||||
// 解密 API 凭证并创建认证客户端
|
||||
val apiKey = cryptoUtils.decrypt(account.apiKey!!)
|
||||
val apiSecret = cryptoUtils.decrypt(account.apiSecret!!)
|
||||
val apiPassphrase = cryptoUtils.decrypt(account.apiPassphrase!!)
|
||||
val clobApi = retrofitFactory.createClobApi(apiKey, apiSecret, apiPassphrase)
|
||||
|
||||
// 调用真实的 API 查询余额
|
||||
val response = clobApi.getActiveOrders(limit = 100)
|
||||
if (response.isSuccessful && response.body() != null) {
|
||||
// 根据 API 响应处理余额数据(从真实响应中解析)
|
||||
val orders = response.body()!!
|
||||
// 实际应该调用余额查询接口或从链上查询
|
||||
// 这里只是示例,实际应该调用真实的余额查询 API
|
||||
val balance = queryRealBalanceFromApi(clobApi, account.walletAddress)
|
||||
Result.success(AccountBalanceResponse(usdcBalance = balance))
|
||||
} else {
|
||||
logger.error("查询余额失败: ${response.code()} ${response.message()}")
|
||||
Result.failure(Exception("查询余额失败: ${response.code()} ${response.message()}"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("查询账户余额失败", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 需求文档引用
|
||||
|
||||
### 跟单系统需求
|
||||
- **需求文档**: `docs/copy-trading-requirements.md`
|
||||
- **说明**: 所有跟单系统相关的功能实现必须严格按照需求文档执行
|
||||
- **核心功能**:
|
||||
- 账户管理(通过私钥导入,支持多账户)
|
||||
- Leader 管理(被跟单者管理)
|
||||
- 订单同步与执行(监控 Leader 交易并自动复制)
|
||||
- 跟单配置管理(全局配置和单个 Leader 配置)
|
||||
- 风险控制(每日亏损限制、订单数限制等)
|
||||
- 跟单记录与统计
|
||||
|
||||
**重要提示**: 在实现跟单系统相关功能时,请先查阅 `docs/copy-trading-requirements.md` 了解详细需求,包括:
|
||||
- 数据模型设计(Account、Leader、CopyOrder 等)
|
||||
- API 接口设计(请求/响应格式)
|
||||
- 业务规则和验证逻辑
|
||||
- 安全要求(私钥加密存储、API Key 管理等)
|
||||
## 核心原则
|
||||
- **禁止**在代码中添加 TODO/FIXME/XXX 注释
|
||||
- **禁止**返回 mock 数据或硬编码的假数据
|
||||
- **禁止**在 API 调用失败时返回默认值作为 fallback
|
||||
- 所有功能必须完整实现,确保代码可以正常运行
|
||||
|
||||
## 项目范围
|
||||
|
||||
### 平台支持
|
||||
- **仅支持**: Polymarket 平台
|
||||
- **不支持**: 其他预测市场平台(如 Kalshi 等)
|
||||
|
||||
### 分类支持
|
||||
- **仅支持**:
|
||||
- `sports`: 体育相关市场
|
||||
- `crypto`: 加密货币相关市场
|
||||
- **不支持**: 其他分类(如 politics、entertainment 等)
|
||||
|
||||
### 分类验证
|
||||
- 所有涉及分类的接口、实体、服务必须验证分类参数
|
||||
- 分类参数只能是 `sports` 或 `crypto`
|
||||
- 无效分类应返回明确的错误提示
|
||||
|
||||
## 包名规范
|
||||
- **平台**: 仅支持 Polymarket
|
||||
- **包名**: `com.wrbug.polymarketbot`
|
||||
- 所有代码必须使用此包名
|
||||
|
||||
## 实体类规范
|
||||
|
||||
### ID字段规范
|
||||
- **必须**使用 `Long? = null` 作为 `@GeneratedValue` 的 id 字段
|
||||
- **禁止**使用 `Long = 0` 或其他默认值
|
||||
|
||||
```kotlin
|
||||
// ✅ 正确
|
||||
@Entity
|
||||
@Table(name = "example_table")
|
||||
data class ExampleEntity(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = null,
|
||||
// ...
|
||||
)
|
||||
|
||||
// ❌ 错误
|
||||
@Entity
|
||||
data class ExampleEntity(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long = 0, // 禁止使用
|
||||
// ...
|
||||
val id: Long? = null, // ✅ 正确:使用可空类型
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis(), // ✅ 使用 Long 时间戳
|
||||
|
||||
@Column(name = "amount", nullable = false, precision = 20, scale = 8)
|
||||
val amount: BigDecimal = BigDecimal.ZERO // ✅ 使用 BigDecimal
|
||||
)
|
||||
```
|
||||
|
||||
**规则**:
|
||||
- ID 字段必须使用 `Long? = null`
|
||||
- 时间字段使用 `Long` 时间戳(毫秒)
|
||||
- 数值字段使用 `BigDecimal`
|
||||
- **禁止**使用 `LocalDateTime` 或 `Double`
|
||||
|
||||
## 配置文件规范
|
||||
|
||||
### 配置文件格式
|
||||
- **必须**使用 `application.properties` 格式
|
||||
- **禁止**使用 `application.yml` 格式
|
||||
- 配置文件位置: `src/main/resources/application.properties`
|
||||
|
||||
### 配置示例
|
||||
```properties
|
||||
# 应用配置
|
||||
spring.application.name=polymarket-bot-backend
|
||||
|
||||
# 数据源配置
|
||||
spring.datasource.url=jdbc:mysql://localhost:3306/polymarket_bot?useSSL=false&serverTimezone=UTC&characterEncoding=utf8mb4
|
||||
spring.datasource.username=${DB_USERNAME:root}
|
||||
spring.datasource.password=${DB_PASSWORD:password}
|
||||
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
|
||||
|
||||
# HikariCP 连接池配置
|
||||
spring.datasource.hikari.maximum-pool-size=10
|
||||
spring.datasource.hikari.minimum-idle=2
|
||||
spring.datasource.hikari.connection-timeout=30000
|
||||
|
||||
# JPA 配置
|
||||
spring.jpa.hibernate.ddl-auto=validate
|
||||
spring.jpa.show-sql=false
|
||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
|
||||
|
||||
# Flyway 配置
|
||||
spring.flyway.enabled=true
|
||||
spring.flyway.locations=classpath:db/migration
|
||||
spring.flyway.baseline-on-migrate=true
|
||||
|
||||
# 服务器配置
|
||||
server.port=${SERVER_PORT:8000}
|
||||
|
||||
# 日志配置
|
||||
logging.level.root=INFO
|
||||
logging.level.com.wrbug.polymarketbot=DEBUG
|
||||
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n
|
||||
```
|
||||
|
||||
### 环境变量引用
|
||||
- 使用 `${ENV_VAR:default}` 格式引用环境变量
|
||||
- 支持多环境配置: `application-dev.properties`, `application-prod.properties`
|
||||
- **必须**使用 `application.properties` 格式(禁止 `application.yml`)
|
||||
- 使用 `${ENV_VAR:default}` 引用环境变量
|
||||
|
||||
## 代码规范
|
||||
|
||||
### Controller规范
|
||||
- Controller 方法**禁止**使用 `suspend`
|
||||
- 如需调用 suspend 方法,使用 `runBlocking`(最小化使用)
|
||||
- 只作用于 suspend 方法调用
|
||||
### Controller
|
||||
- **禁止**使用 `suspend`
|
||||
- 使用 `runBlocking` 调用 suspend 方法
|
||||
- 统一使用 `@PostMapping`
|
||||
|
||||
```kotlin
|
||||
// ✅ 正确
|
||||
@RestController
|
||||
class ExampleController(
|
||||
private val exampleService: ExampleService
|
||||
) {
|
||||
@PostMapping("/example")
|
||||
fun getExample(): ResponseEntity<ApiResponse<ExampleDto>> {
|
||||
val data = runBlocking { exampleService.getData() }
|
||||
return ResponseEntity.ok(ApiResponse.success(data))
|
||||
}
|
||||
}
|
||||
|
||||
// ❌ 错误
|
||||
@RestController
|
||||
class ExampleController {
|
||||
@PostMapping("/example")
|
||||
suspend fun getExample(): ResponseEntity<ApiResponse<ExampleDto>> { // 禁止使用suspend
|
||||
// ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Service规范
|
||||
- Service 层可以使用 `suspend` 方法
|
||||
### Service
|
||||
- 可以使用 `suspend` 方法
|
||||
- 使用 `@Transactional` 管理事务
|
||||
- 使用构造函数注入依赖
|
||||
|
||||
```kotlin
|
||||
@Service
|
||||
class ExampleService(
|
||||
private val exampleRepository: ExampleRepository
|
||||
) {
|
||||
suspend fun getAllData(): List<ExampleEntity> {
|
||||
return exampleRepository.findAll()
|
||||
}
|
||||
|
||||
@Transactional
|
||||
fun saveData(entity: ExampleEntity): ExampleEntity {
|
||||
return exampleRepository.save(entity)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Repository规范
|
||||
- Repository 接口继承 `JpaRepository`
|
||||
### Repository
|
||||
- 继承 `JpaRepository<Entity, Long>`
|
||||
- 使用 Spring Data JPA 方法命名规范
|
||||
|
||||
```kotlin
|
||||
@Repository
|
||||
interface ExampleRepository : JpaRepository<ExampleEntity, Long> {
|
||||
fun findByCode(code: String): ExampleEntity?
|
||||
fun findByCategoryAndStatus(category: String, status: String): List<ExampleEntity>
|
||||
fun findByCategory(category: String): List<ExampleEntity> // category: sports 或 crypto
|
||||
}
|
||||
```
|
||||
## API 接口规范
|
||||
|
||||
### Entity规范
|
||||
- 使用 `@Entity` 和 `@Table` 注解
|
||||
- ID字段使用 `Long? = null`
|
||||
- 时间字段使用 `Long` 时间戳(毫秒)
|
||||
- 数值字段使用 `BigDecimal`,使用 `String` 存储
|
||||
|
||||
```kotlin
|
||||
@Entity
|
||||
@Table(name = "example_table")
|
||||
data class ExampleEntity(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = null,
|
||||
|
||||
@Column(name = "code", unique = true, nullable = false, length = 100)
|
||||
val code: String = "",
|
||||
|
||||
@Column(name = "category", nullable = false, length = 20)
|
||||
val category: String = "", // sports 或 crypto
|
||||
|
||||
@Column(name = "amount", nullable = false, precision = 20, scale = 8)
|
||||
val amount: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "status", nullable = false, length = 20)
|
||||
val status: String = "", // active, inactive
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
var updatedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
```
|
||||
|
||||
## 数值计算规范
|
||||
|
||||
### BigDecimal使用
|
||||
- 所有数值计算必须使用 `BigDecimal`
|
||||
- 使用 `String` 存储数值
|
||||
- 使用扩展函数进行安全转换和比较
|
||||
|
||||
```kotlin
|
||||
// 使用扩展函数
|
||||
val amount = "0.5".toSafeBigDecimal()
|
||||
val total = amount.add("0.4".toSafeBigDecimal())
|
||||
|
||||
// 比较
|
||||
if (total.lt(BigDecimal.ONE)) {
|
||||
// 业务逻辑
|
||||
}
|
||||
```
|
||||
|
||||
## 时间字段规范
|
||||
|
||||
### 时间戳使用
|
||||
- 所有时间字段使用 `Long` 类型存储毫秒级时间戳
|
||||
- **禁止**使用 `LocalDateTime` 或其他时间类型
|
||||
|
||||
```kotlin
|
||||
// ✅ 正确
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis()
|
||||
|
||||
// ❌ 错误
|
||||
@Column(name = "created_at")
|
||||
val createdAt: LocalDateTime = LocalDateTime.now() // 禁止使用
|
||||
```
|
||||
|
||||
## HTTP客户端规范
|
||||
|
||||
### Retrofit使用
|
||||
- 使用 Retrofit 定义 API 接口
|
||||
- 使用 OkHttp 作为底层 HTTP 客户端
|
||||
- 使用拦截器处理认证
|
||||
|
||||
```kotlin
|
||||
// Polymarket CLOB API接口定义(跟单系统需要)
|
||||
interface PolymarketClobApi {
|
||||
@POST("/orders")
|
||||
suspend fun createOrder(@Body order: CreateOrderRequest): Response<OrderResponse>
|
||||
|
||||
@GET("/orders/active")
|
||||
suspend fun getActiveOrders(
|
||||
@Query("market") market: String?,
|
||||
@Query("limit") limit: Int?,
|
||||
@Query("offset") offset: Int?
|
||||
): Response<List<OrderResponse>>
|
||||
|
||||
@DELETE("/orders/{orderId}")
|
||||
suspend fun cancelOrder(@Path("orderId") orderId: String): Response<CancelOrderResponse>
|
||||
|
||||
@GET("/trades")
|
||||
suspend fun getTrades(
|
||||
@Query("market") market: String?,
|
||||
@Query("user") user: String?,
|
||||
@Query("limit") limit: Int?,
|
||||
@Query("offset") offset: Int?
|
||||
): Response<List<TradeResponse>>
|
||||
}
|
||||
|
||||
// Retrofit配置
|
||||
@Configuration
|
||||
class RetrofitConfig {
|
||||
@Bean
|
||||
fun polymarketClobApi(): PolymarketClobApi {
|
||||
val okHttpClient = OkHttpClient.Builder()
|
||||
.addInterceptor(AuthInterceptor())
|
||||
.build()
|
||||
|
||||
return Retrofit.Builder()
|
||||
.baseUrl("https://clob.polymarket.com")
|
||||
.client(okHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create())
|
||||
.build()
|
||||
.create(PolymarketClobApi::class.java)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## API接口规范
|
||||
|
||||
### 请求规范
|
||||
- **所有接口统一使用POST方法**,包括查询类接口
|
||||
- 请求头: `Content-Type: application/json`
|
||||
- 请求体: JSON格式
|
||||
|
||||
### 响应规范
|
||||
- **统一响应格式**:
|
||||
### 统一响应格式
|
||||
```json
|
||||
{
|
||||
"code": 0,
|
||||
@@ -398,77 +69,7 @@ class RetrofitConfig {
|
||||
}
|
||||
```
|
||||
|
||||
- **响应字段说明**:
|
||||
- `code`: 响应码,0表示成功,非0表示失败
|
||||
- `data`: 响应数据,可以是任意类型(对象、数组、字符串、数字等)
|
||||
- `msg`: 响应消息,成功时通常为空,失败时包含错误提示
|
||||
|
||||
### 响应示例
|
||||
|
||||
**成功响应**:
|
||||
```json
|
||||
{
|
||||
"code": 0,
|
||||
"data": {
|
||||
"id": "123",
|
||||
"name": "example"
|
||||
},
|
||||
"msg": ""
|
||||
}
|
||||
```
|
||||
|
||||
**失败响应**:
|
||||
```json
|
||||
{
|
||||
"code": 1001,
|
||||
"data": null,
|
||||
"msg": "参数错误:参数不能为空"
|
||||
}
|
||||
```
|
||||
|
||||
### Controller实现示例
|
||||
|
||||
```kotlin
|
||||
@RestController
|
||||
@RequestMapping("/api/example")
|
||||
class ExampleController(
|
||||
private val exampleService: ExampleService
|
||||
) {
|
||||
private val logger = LoggerFactory.getLogger(ExampleController::class.java)
|
||||
|
||||
@PostMapping("/list")
|
||||
fun getList(@RequestBody request: ExampleListRequest): ResponseEntity<ApiResponse<ExampleListResponse>> {
|
||||
return try {
|
||||
val data = runBlocking { exampleService.getList(request) }
|
||||
val response = ExampleListResponse(
|
||||
list = data,
|
||||
total = data.size.toLong(),
|
||||
page = request.page ?: 1,
|
||||
limit = request.limit ?: 20
|
||||
)
|
||||
ResponseEntity.ok(ApiResponse.success(response))
|
||||
} catch (e: Exception) {
|
||||
logger.error("Failed to get list", e)
|
||||
ResponseEntity.ok(ApiResponse.serverError("获取列表失败:${e.message}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 统一响应格式
|
||||
data class ApiResponse<T>(
|
||||
val code: Int,
|
||||
val data: T?,
|
||||
val msg: String
|
||||
) {
|
||||
companion object {
|
||||
fun <T> success(data: T): ApiResponse<T> = ApiResponse(0, data, "")
|
||||
fun <T> paramError(msg: String): ApiResponse<T> = ApiResponse(1001, null, msg)
|
||||
fun <T> serverError(msg: String): ApiResponse<T> = ApiResponse(5001, null, msg)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 错误码规范
|
||||
### 错误码范围
|
||||
- `0`: 成功
|
||||
- `1001-1999`: 参数错误
|
||||
- `2001-2999`: 认证/权限错误
|
||||
@@ -476,7 +77,131 @@ data class ApiResponse<T>(
|
||||
- `4001-4999`: 业务逻辑错误
|
||||
- `5001-5999`: 服务器内部错误
|
||||
|
||||
详细错误码定义参见需求文档
|
||||
### Controller 示例
|
||||
```kotlin
|
||||
@RestController
|
||||
@RequestMapping("/api/example")
|
||||
class ExampleController(
|
||||
private val exampleService: ExampleService,
|
||||
private val messageSource: MessageSource
|
||||
) {
|
||||
@PostMapping("/list")
|
||||
fun getList(@RequestBody request: ExampleListRequest): ResponseEntity<ApiResponse<ExampleListResponse>> {
|
||||
return try {
|
||||
val data = runBlocking { exampleService.getList(request) }
|
||||
ResponseEntity.ok(ApiResponse.success(data))
|
||||
} catch (e: Exception) {
|
||||
logger.error("Failed to get list", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, messageSource))
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 数值计算
|
||||
```kotlin
|
||||
val amount = "0.5".toSafeBigDecimal()
|
||||
val total = amount.add("0.4".toSafeBigDecimal())
|
||||
|
||||
if (total.lt(BigDecimal.ONE)) {
|
||||
// 业务逻辑
|
||||
}
|
||||
```
|
||||
|
||||
## JSON 解析规范
|
||||
|
||||
### 使用扩展函数(推荐)
|
||||
- **优先**使用扩展函数 `fromJson<T>()` 和 `toJson()`,禁止直接使用 `Gson`
|
||||
- 扩展函数提供了类型安全的解析,使用方便
|
||||
|
||||
```kotlin
|
||||
// ✅ 正确:使用扩展函数(推荐)
|
||||
val json = "{\"name\":\"test\"}"
|
||||
val obj = json.fromJson<MyDataClass>()
|
||||
val jsonStr = obj.toJson()
|
||||
|
||||
// ✅ 也可以:使用 JsonUtils 类(兼容旧代码)
|
||||
val obj = jsonUtils.fromJson<MyDataClass>(json)
|
||||
|
||||
// ❌ 错误:直接使用 Gson
|
||||
val obj = gson.fromJson(json, MyDataClass::class.java)
|
||||
```
|
||||
|
||||
### 扩展函数列表
|
||||
- `String?.fromJson<T>()` - 解析 JSON 字符串为对象(支持泛型)
|
||||
- `JsonElement?.fromJson<T>()` - 解析 JsonElement 为对象(支持泛型)
|
||||
- `Any?.toJson()` - 将对象转换为 JSON 字符串
|
||||
- `String?.parseStringArray()` - 解析 JSON 字符串数组
|
||||
|
||||
### JsonUtils 类
|
||||
- `JsonUtils` 主要用于初始化全局 Gson 实例,供扩展函数使用
|
||||
- 保留 `parseStringArray()` 方法用于兼容旧代码
|
||||
- 不推荐直接使用 `JsonUtils` 的方法,优先使用扩展函数
|
||||
|
||||
### Data Class 规范
|
||||
- **所有 data class 字段必须提供默认值**
|
||||
- 可空字段使用 `? = null`
|
||||
- 非空字段提供合适的默认值(空字符串、空集合、默认数值等)
|
||||
|
||||
```kotlin
|
||||
// ✅ 正确:所有字段都有默认值
|
||||
data class MyDto(
|
||||
val name: String = "",
|
||||
val age: Int = 0,
|
||||
val tags: List<String> = emptyList(),
|
||||
val optional: String? = null
|
||||
)
|
||||
|
||||
// ❌ 错误:缺少默认值
|
||||
data class MyDto(
|
||||
val name: String, // 缺少默认值
|
||||
val age: Int = 0
|
||||
)
|
||||
```
|
||||
|
||||
## Side 判断规范
|
||||
**禁止**使用 "YES"/"NO" 字符串判断 side
|
||||
|
||||
```kotlin
|
||||
// ❌ 错误
|
||||
if (side != null && side.uppercase() == "NO") { }
|
||||
|
||||
// ✅ 正确
|
||||
if (outcomeIndex != null && outcomeIndex == 1) { }
|
||||
```
|
||||
|
||||
## 多语言规范
|
||||
- **禁止**硬编码中文或英文错误消息
|
||||
- **必须**使用 `ErrorCode` 枚举和 `MessageSource`
|
||||
|
||||
```kotlin
|
||||
// ❌ 错误
|
||||
return ResponseEntity.ok(ApiResponse.paramError("配置ID不能为空"))
|
||||
|
||||
// ✅ 正确
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_EMPTY, messageSource))
|
||||
```
|
||||
|
||||
### 多语言支持范围
|
||||
1. **API 响应消息**: 使用 `ErrorCode` + `MessageSource`
|
||||
2. **日志消息**: 可使用中文或英文
|
||||
3. **代码注释**: 建议使用中文
|
||||
4. **数据库字段**: 使用英文(snake_case)
|
||||
|
||||
## HTTP 客户端
|
||||
- 使用 Retrofit + OkHttp
|
||||
- 使用拦截器处理认证
|
||||
|
||||
## 跟单系统需求
|
||||
参考文档: `docs/copy-trading-requirements.md`
|
||||
|
||||
核心功能:
|
||||
- 账户管理(私钥导入,多账户)
|
||||
- Leader 管理
|
||||
- 订单同步与执行
|
||||
- 跟单配置管理
|
||||
- 风险控制
|
||||
- 跟单记录与统计
|
||||
|
||||
## 禁止事项
|
||||
|
||||
@@ -484,173 +209,25 @@ data class ApiResponse<T>(
|
||||
- ❌ 禁止使用 `!!` 除非有明确原因
|
||||
- ❌ 禁止忽略异常
|
||||
- ❌ 禁止硬编码配置值
|
||||
- ❌ 禁止提交敏感信息到Git
|
||||
- ❌ Controller 方法禁止使用 `suspend`
|
||||
- ❌ 实体类ID禁止使用 `Long = 0`
|
||||
- ❌ **禁止直接返回 mock 数据或硬编码的假数据**
|
||||
- ❌ **禁止在 API 调用失败时返回 mock 数据作为默认值**
|
||||
- ❌ **所有返回的数据必须来自真实的 API 调用或数据库查询**
|
||||
|
||||
### 配置
|
||||
- ❌ 禁止使用 `application.yml`
|
||||
- ❌ 禁止在代码中硬编码配置值
|
||||
- ❌ 禁止提交敏感信息到 Git
|
||||
|
||||
### 类型
|
||||
- ❌ 禁止使用 `Double` 进行数值计算
|
||||
- ❌ 禁止使用 `LocalDateTime` 存储时间
|
||||
- ❌ 禁止实体类ID使用非空默认值
|
||||
- ❌ 禁止实体类 ID 使用非空默认值
|
||||
- ❌ 禁止直接使用 `Gson`(必须使用 `JsonUtils`)
|
||||
- ❌ 禁止 data class 字段缺少默认值
|
||||
|
||||
### API接口
|
||||
- ❌ 禁止使用GET、PUT、DELETE等方法(统一使用POST)
|
||||
### API 接口
|
||||
- ❌ 禁止使用 GET/PUT/DELETE(统一使用 POST)
|
||||
- ❌ 禁止返回不符合统一格式的响应
|
||||
- ❌ 禁止在响应中直接返回Map类型(使用data class)
|
||||
- ❌ 禁止在响应中直接返回 Map 类型
|
||||
|
||||
### Side 判断规范
|
||||
- ❌ **禁止使用 "YES" 或 "NO" 字符串去判断 side**
|
||||
- ✅ **必须使用 `outcomeIndex` 来判断方向**(0 = 第一个 outcome,1 = 第二个 outcome,以此类推)
|
||||
- ✅ 如果必须使用 side 字符串,应该从市场的 outcomes 数组中获取,而不是硬编码 "YES"/"NO"
|
||||
- ✅ 对于二元市场的价格转换,应该通过 `outcomeIndex` 判断是否为第二个 outcome(index = 1),而不是判断 side 是否为 "NO"
|
||||
### Side 判断
|
||||
- ❌ 禁止使用 "YES"/"NO" 字符串判断 side
|
||||
- ✅ 必须使用 `outcomeIndex` 判断
|
||||
|
||||
```kotlin
|
||||
// ❌ 错误:使用字符串比较判断 side
|
||||
if (side != null && side.uppercase() == "NO") {
|
||||
// 转换价格
|
||||
}
|
||||
|
||||
// ❌ 错误:硬编码 "YES"/"NO" 判断
|
||||
when (side.uppercase()) {
|
||||
"YES" -> // ...
|
||||
"NO" -> // ...
|
||||
}
|
||||
|
||||
// ✅ 正确:使用 outcomeIndex 判断
|
||||
if (outcomeIndex != null && outcomeIndex == 1) {
|
||||
// 第二个 outcome(在二元市场中通常是 NO),转换价格
|
||||
}
|
||||
|
||||
// ✅ 正确:从市场 outcomes 获取 side 信息
|
||||
val outcomes = JsonUtils.parseStringArray(market.outcomes)
|
||||
val targetOutcomeIndex = outcomes.indexOfFirst { it.equals(side, ignoreCase = true) }
|
||||
if (targetOutcomeIndex >= 0) {
|
||||
// 使用 targetOutcomeIndex 进行判断
|
||||
}
|
||||
```
|
||||
|
||||
## 多语言使用规范
|
||||
|
||||
### 错误消息和响应文本
|
||||
- **禁止**在代码中硬编码中文或英文错误消息
|
||||
- **必须**使用 `ErrorCode` 枚举定义错误码和消息
|
||||
- **必须**使用 `ApiResponse.error(ErrorCode, messageSource)` 或 `MessageUtils.getMessage()` 获取国际化消息
|
||||
- **禁止**直接使用 `ApiResponse.paramError("硬编码消息")` 或 `ApiResponse.serverError("硬编码消息")`
|
||||
- 错误消息的默认语言使用中文(在 `ErrorCode` 枚举中定义),通过 `MessageSource` 支持多语言
|
||||
|
||||
### 使用 ErrorCode 和 MessageSource
|
||||
项目已经实现了国际化支持,必须使用以下方式:
|
||||
|
||||
```kotlin
|
||||
// ❌ 错误:硬编码错误消息
|
||||
return ResponseEntity.ok(ApiResponse.paramError("配置ID不能为空"))
|
||||
return ResponseEntity.ok(ApiResponse.serverError("获取配置列表失败:${e.message}"))
|
||||
|
||||
// ✅ 正确:使用 ErrorCode 枚举
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_EMPTY, messageSource = messageSource))
|
||||
|
||||
// ✅ 正确:使用 ErrorCode 和自定义消息(如果需要动态消息)
|
||||
return ResponseEntity.ok(ApiResponse.error(
|
||||
ErrorCode.PARAM_ERROR,
|
||||
customMsg = "配置ID不能为空",
|
||||
messageSource = messageSource
|
||||
))
|
||||
|
||||
// ✅ 正确:使用 MessageUtils
|
||||
@Autowired
|
||||
private lateinit var messageUtils: MessageUtils
|
||||
|
||||
return ResponseEntity.ok(ApiResponse.error(
|
||||
ErrorCode.PARAM_EMPTY,
|
||||
messageSource = messageSource
|
||||
))
|
||||
```
|
||||
|
||||
### 添加新的错误码
|
||||
如果需要添加新的错误码,必须在 `ErrorCode` 枚举中定义:
|
||||
|
||||
```kotlin
|
||||
enum class ErrorCode(
|
||||
val code: Int,
|
||||
val message: String, // 默认消息(中文)
|
||||
val messageKey: String // 国际化消息键
|
||||
) {
|
||||
// 新错误码示例
|
||||
NOTIFICATION_CONFIG_NOT_FOUND(3009, "通知配置不存在", "error.notification_config_not_found"),
|
||||
NOTIFICATION_CONFIG_INVALID(4009, "通知配置无效", "error.notification_config_invalid"),
|
||||
}
|
||||
```
|
||||
|
||||
然后在语言资源文件中添加对应的翻译:
|
||||
- `src/main/resources/messages_zh_CN.properties`
|
||||
- `src/main/resources/messages_zh_TW.properties`
|
||||
- `src/main/resources/messages_en.properties`
|
||||
|
||||
### 日志消息规范
|
||||
- **日志消息可以使用中文或英文**,便于开发调试
|
||||
- **禁止**在日志中硬编码用户可见的错误消息(应该使用 ErrorCode)
|
||||
- 日志消息应该清晰、简洁,便于排查问题
|
||||
- 日志中的业务数据(如账户名、订单ID等)可以使用原始值
|
||||
|
||||
### 代码注释规范
|
||||
- **代码注释可以使用中文或英文**
|
||||
- **业务逻辑注释**建议使用中文,便于团队理解
|
||||
- **API 文档注释**(KDoc)建议使用中文,但也可以使用英文
|
||||
- **类和方法注释**应该清晰说明功能和参数
|
||||
|
||||
### 数据库字段和配置
|
||||
- **数据库字段名**使用英文(snake_case)
|
||||
- **配置项名称**使用英文(kebab-case 或 dot.notation)
|
||||
- **枚举值**使用英文(UPPER_SNAKE_CASE)
|
||||
- **常量定义**使用英文(UPPER_SNAKE_CASE)
|
||||
|
||||
### 多语言支持策略
|
||||
1. **API 响应消息**:使用 `ErrorCode` 枚举,通过 `MessageSource` 支持多语言
|
||||
2. **错误码**:使用 `ErrorCode` 枚举,包含 `code`、`message`(默认中文)和 `messageKey`(国际化键)
|
||||
3. **日志消息**:可以使用中文或英文,便于开发调试
|
||||
4. **代码注释**:可以使用中文或英文,建议使用中文
|
||||
5. **业务数据**:根据实际需求,可以包含多语言内容(如市场标题、描述等)
|
||||
|
||||
### Controller 中使用多语言示例
|
||||
|
||||
```kotlin
|
||||
@RestController
|
||||
class NotificationController(
|
||||
private val notificationConfigService: NotificationConfigService,
|
||||
private val messageSource: MessageSource // 注入 MessageSource
|
||||
) {
|
||||
@PostMapping("/configs/list")
|
||||
fun list(@RequestBody request: NotificationConfigListRequest): ResponseEntity<ApiResponse<List<NotificationConfigDto>>> {
|
||||
return try {
|
||||
// ... 业务逻辑
|
||||
ResponseEntity.ok(ApiResponse.success(configs))
|
||||
} catch (e: Exception) {
|
||||
logger.error("获取配置列表失败: ${e.message}", e)
|
||||
// ✅ 正确:使用 ErrorCode 和 MessageSource
|
||||
ResponseEntity.ok(ApiResponse.error(
|
||||
ErrorCode.SERVER_ERROR,
|
||||
messageSource = messageSource
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/configs/detail")
|
||||
fun detail(@RequestBody request: NotificationConfigDetailRequest): ResponseEntity<ApiResponse<NotificationConfigDto>> {
|
||||
if (request.id == null) {
|
||||
// ✅ 正确:使用 ErrorCode
|
||||
return ResponseEntity.ok(ApiResponse.error(
|
||||
ErrorCode.PARAM_EMPTY,
|
||||
messageSource = messageSource
|
||||
))
|
||||
}
|
||||
// ... 业务逻辑
|
||||
}
|
||||
}
|
||||
```
|
||||
### 数据源
|
||||
- ❌ 禁止直接返回 mock 数据
|
||||
- ❌ 禁止在 API 调用失败时返回 mock 数据
|
||||
- ✅ 所有数据必须来自真实 API 或数据库查询
|
||||
|
||||
+68
-232
@@ -5,107 +5,41 @@ path: frontend/**
|
||||
|
||||
# 前端开发规范
|
||||
|
||||
## 代码完成规范
|
||||
|
||||
### TODO 处理规则
|
||||
- **禁止**在代码中添加 TODO 注释
|
||||
- **必须**根据 TODO 的内容直接完成代码实现
|
||||
- 如果遇到暂时无法完全实现的功能,应该:
|
||||
1. 实现一个可用的基础版本
|
||||
2. 添加清晰的注释说明当前实现的限制和后续改进方向
|
||||
3. 确保代码可以正常编译和运行
|
||||
- **禁止**使用 `// TODO: 实现XXX` 这样的注释
|
||||
- **禁止**使用 `// FIXME:` 或 `// XXX:` 这样的注释
|
||||
- 如果某个功能需要依赖外部资源(如 API、库等),应该:
|
||||
1. 先实现一个占位或模拟实现
|
||||
2. 在注释中说明依赖关系和实现方式
|
||||
3. 确保代码逻辑完整,不会因为未实现的功能而崩溃
|
||||
|
||||
### API 调用实现规则
|
||||
- **必须**查找相关的 API 文档或接口定义
|
||||
- **必须**根据 API 文档完成代码实现
|
||||
- **禁止**在 API 调用处添加 TODO 注释
|
||||
- 如果 API 文档不完整,应该:
|
||||
1. 查找项目中已有的类似 API 调用作为参考
|
||||
2. 查看 API 服务定义(如 `services/api.ts`)
|
||||
3. 查看 API 文档(如 `docs/copy-trading-requirements.md`)
|
||||
4. 实现一个可用的版本,包含错误处理
|
||||
|
||||
### 代码完成示例
|
||||
|
||||
```typescript
|
||||
// ❌ 错误:添加 TODO 注释
|
||||
const fetchAccountBalance = async (accountId: number) => {
|
||||
// TODO: 调用 API 查询余额
|
||||
return { balance: '0' }
|
||||
}
|
||||
|
||||
// ✅ 正确:查找 API 定义并完成实现
|
||||
// 1. 查找 API 服务定义:services/api.ts 中的 accounts.balance
|
||||
// 2. 查找 API 文档:docs/copy-trading-requirements.md
|
||||
// 3. 实现完整的 API 调用逻辑
|
||||
const fetchAccountBalance = async (accountId: number) => {
|
||||
try {
|
||||
// 根据 API 服务定义调用接口
|
||||
const response = await apiService.accounts.balance({ accountId })
|
||||
|
||||
// 根据 API 响应格式处理数据
|
||||
if (response.data.code === 0 && response.data.data) {
|
||||
return response.data.data
|
||||
} else {
|
||||
// API 调用失败时返回默认值
|
||||
console.warn('查询余额失败,返回默认值:', response.data.msg)
|
||||
return { balance: '0' }
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('查询余额异常:', error)
|
||||
// 异常时返回默认值,确保代码可以正常运行
|
||||
return { balance: '0' }
|
||||
}
|
||||
}
|
||||
```
|
||||
## 核心原则
|
||||
- **禁止**在代码中添加 TODO/FIXME/XXX 注释
|
||||
- **禁止**使用 `any` 类型
|
||||
- **禁止**硬编码中文或英文文本
|
||||
- **必须**支持移动端和桌面端
|
||||
|
||||
## 技术栈
|
||||
- **框架**: React + TypeScript
|
||||
- **UI库**: Ant Design 或 Material-UI(推荐 Ant Design Mobile 用于移动端)
|
||||
- **HTTP客户端**: axios
|
||||
- **状态管理**: Zustand 或 Redux
|
||||
- **响应式设计**: 必须支持移动端和桌面端
|
||||
- **UI 库**: Ant Design(移动端使用 Ant Design Mobile)
|
||||
- **HTTP 客户端**: axios
|
||||
- **状态管理**: Zustand
|
||||
- **国际化**: react-i18next
|
||||
|
||||
## 移动端适配要求
|
||||
## 移动端适配
|
||||
|
||||
### 响应式设计
|
||||
- **必须支持移动端和桌面端**
|
||||
- 使用响应式布局(Responsive Design)
|
||||
- 移动端优先(Mobile First)设计原则
|
||||
- 支持触摸操作和手势
|
||||
|
||||
### 断点设置
|
||||
### 响应式断点
|
||||
- **移动端**: < 768px
|
||||
- **平板**: 768px - 1024px
|
||||
- **桌面端**: > 1024px
|
||||
|
||||
### UI 组件适配
|
||||
- 使用 Ant Design 的响应式组件
|
||||
- 移动端使用 Ant Design Mobile(如果使用 Ant Design)
|
||||
- 表格使用虚拟滚动或分页(移动端性能优化)
|
||||
- 表单使用移动端友好的输入组件
|
||||
|
||||
### 布局适配
|
||||
- 导航栏:移动端使用抽屉菜单,桌面端使用顶部导航
|
||||
- 列表:移动端使用卡片布局,桌面端使用表格布局
|
||||
- 按钮:移动端按钮尺寸不小于 44x44px(触摸友好)
|
||||
- 间距:移动端使用更大的间距,提高可点击区域
|
||||
### 适配要求
|
||||
- 使用响应式布局(Mobile First)
|
||||
- 导航栏:移动端抽屉菜单,桌面端顶部导航
|
||||
- 列表:移动端卡片布局,桌面端表格布局
|
||||
- 按钮:移动端不小于 44x44px
|
||||
- 支持触摸操作和手势
|
||||
|
||||
### 性能优化
|
||||
- 图片懒加载
|
||||
- 代码分割(Code Splitting)
|
||||
- 移动端减少动画效果
|
||||
- 使用 CSS 媒体查询优化样式
|
||||
|
||||
## 代码规范
|
||||
|
||||
### 组件规范
|
||||
### 组件
|
||||
- 使用函数式组件
|
||||
- 使用 TypeScript 类型定义
|
||||
- 组件文件使用 PascalCase 命名
|
||||
@@ -122,24 +56,18 @@ export const MarketCard: React.FC<MarketProps> = ({ marketId, platform }) => {
|
||||
};
|
||||
|
||||
// ❌ 错误
|
||||
export const marketCard = (props: any) => { // 禁止使用any
|
||||
// ...
|
||||
};
|
||||
export const marketCard = (props: any) => { }
|
||||
```
|
||||
|
||||
### API调用规范
|
||||
- 使用 axios 进行 HTTP 请求
|
||||
### API 调用
|
||||
- 使用 axios
|
||||
- 统一错误处理
|
||||
- 使用 TypeScript 定义响应类型
|
||||
|
||||
```typescript
|
||||
// API服务
|
||||
import axios from 'axios';
|
||||
|
||||
interface Market {
|
||||
id: string;
|
||||
marketId: string;
|
||||
platform: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
@@ -147,24 +75,16 @@ export const marketService = {
|
||||
getMarkets: async (): Promise<Market[]> => {
|
||||
const response = await axios.get<Market[]>('/api/markets');
|
||||
return response.data;
|
||||
},
|
||||
|
||||
getMarketById: async (id: string): Promise<Market> => {
|
||||
const response = await axios.get<Market>(`/api/markets/${id}`);
|
||||
return response.data;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 状态管理规范
|
||||
- 使用 Zustand 或 Redux 管理全局状态
|
||||
### 状态管理
|
||||
- 全局状态使用 Zustand
|
||||
- 本地状态使用 `useState`
|
||||
- 复杂状态使用 `useReducer`
|
||||
|
||||
```typescript
|
||||
// Zustand Store示例
|
||||
import { create } from 'zustand';
|
||||
|
||||
interface MarketStore {
|
||||
markets: Market[];
|
||||
setMarkets: (markets: Market[]) => void;
|
||||
@@ -176,80 +96,64 @@ export const useMarketStore = create<MarketStore>((set) => ({
|
||||
}));
|
||||
```
|
||||
|
||||
### USDC 金额格式化规范
|
||||
- **必须**使用 `formatUSDC` 函数格式化所有 USDC 金额显示
|
||||
- **禁止**直接使用 `toFixed()` 或 `parseFloat().toFixed()` 格式化 USDC
|
||||
- **禁止**硬编码小数位数格式化 USDC
|
||||
- 所有 USDC 金额显示必须统一使用 `formatUSDC` 函数
|
||||
|
||||
#### formatUSDC 函数说明
|
||||
- **位置**: `src/utils/index.ts`
|
||||
- **功能**: 格式化 USDC 金额,最多显示 4 位小数,自动去除尾随零(截断,不四舍五入)
|
||||
- **参数**: `value: string | number | undefined | null`
|
||||
- **返回值**: 格式化后的字符串,如果值为空或无效则返回 `'-'`
|
||||
|
||||
#### 使用示例
|
||||
### USDC 金额格式化
|
||||
**必须**使用 `formatUSDC` 函数(从 `../utils` 导入)
|
||||
|
||||
```typescript
|
||||
// ✅ 正确:使用 formatUSDC 格式化 USDC 金额
|
||||
import { formatUSDC } from '../utils'
|
||||
|
||||
const BalanceDisplay: React.FC<{ balance: string }> = ({ balance }) => {
|
||||
return <span>{formatUSDC(balance)} USDC</span>
|
||||
}
|
||||
|
||||
// ✅ 正确:在表格列中使用
|
||||
const columns = [
|
||||
{
|
||||
title: '余额',
|
||||
dataIndex: 'balance',
|
||||
render: (balance: string) => `${formatUSDC(balance)} USDC`
|
||||
}
|
||||
]
|
||||
|
||||
// ✅ 正确:在统计组件中使用
|
||||
// ✅ 正确
|
||||
<Statistic
|
||||
title="总盈亏"
|
||||
value={formatUSDC(stats?.totalPnl || '0')}
|
||||
suffix="USDC"
|
||||
/>
|
||||
|
||||
// ❌ 错误:直接使用 toFixed
|
||||
const balance = parseFloat(value).toFixed(4) // 禁止
|
||||
|
||||
// ❌ 错误:硬编码格式化
|
||||
const balance = `${parseFloat(value).toFixed(2)} USDC` // 禁止
|
||||
|
||||
// ❌ 错误:使用自定义格式化函数
|
||||
const formatBalance = (value: string) => parseFloat(value).toFixed(4) // 禁止
|
||||
// ❌ 错误
|
||||
const balance = parseFloat(value).toFixed(4)
|
||||
```
|
||||
|
||||
#### 格式化规则
|
||||
- **最多显示 4 位小数**:如果金额超过 4 位小数,截断到 4 位(不四舍五入)
|
||||
- **自动去除尾随零**:去除不必要的尾随零和小数点
|
||||
- **示例**:
|
||||
- `formatUSDC(1.23)` => `"1.23"`
|
||||
- `formatUSDC(1.23456)` => `"1.2345"`(截断,不四舍五入)
|
||||
- `formatUSDC(1.2)` => `"1.2"`
|
||||
- `formatUSDC(1)` => `"1"`
|
||||
- `formatUSDC(1.23459)` => `"1.2345"`(截断,不四舍五入)
|
||||
- `formatUSDC(null)` => `"-"`
|
||||
- `formatUSDC(undefined)` => `"-"`
|
||||
**格式化规则**:
|
||||
- 最多显示 4 位小数(截断,不四舍五入)
|
||||
- 自动去除尾随零
|
||||
- 空值返回 `'-'`
|
||||
|
||||
#### 工具函数统一导出
|
||||
- 所有工具函数统一从 `src/utils/index.ts` 导出
|
||||
- **必须**从 `../utils` 导入工具函数,而不是从具体文件导入
|
||||
- `ethers.ts` 中的函数也会在 `index.ts` 中统一导出
|
||||
## 多语言规范
|
||||
|
||||
### 使用方式
|
||||
**必须**使用 `useTranslation` Hook
|
||||
|
||||
```typescript
|
||||
// ✅ 正确:从 utils 统一导入
|
||||
import { formatUSDC, getAddressFromPrivateKey, isValidWalletAddress } from '../utils'
|
||||
// ✅ 正确
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
// ❌ 错误:从具体文件导入
|
||||
import { formatUSDC } from '../utils/index'
|
||||
import { getAddressFromPrivateKey } from '../utils/ethers'
|
||||
const MyComponent: React.FC = () => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1>{t('page.title')}</h1>
|
||||
<Button>{t('common.save')}</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ❌ 错误:硬编码文本
|
||||
<h1>页面标题</h1>
|
||||
<Button>保存</Button>
|
||||
```
|
||||
|
||||
### 语言文件
|
||||
- 位置: `src/locales/{locale}/common.json`
|
||||
- 支持: `zh-CN`、`zh-TW`、`en`
|
||||
- 键名: 点号分隔的层级结构(如 `notificationSettings.title`)
|
||||
|
||||
### 添加新翻译
|
||||
1. 在 `src/locales/zh-CN/common.json` 添加中文
|
||||
2. 在 `src/locales/zh-TW/common.json` 添加繁体
|
||||
3. 在 `src/locales/en/common.json` 添加英文
|
||||
4. 在组件中使用 `t('key')`
|
||||
|
||||
## 移动端适配示例
|
||||
|
||||
### 响应式布局
|
||||
@@ -267,29 +171,6 @@ const MyComponent: React.FC = () => {
|
||||
};
|
||||
```
|
||||
|
||||
### 移动端导航
|
||||
```typescript
|
||||
import { Drawer } from 'antd';
|
||||
|
||||
const MobileNav: React.FC = () => {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button onClick={() => setOpen(true)}>菜单</Button>
|
||||
<Drawer
|
||||
title="导航"
|
||||
placement="left"
|
||||
onClose={() => setOpen(false)}
|
||||
open={open}
|
||||
>
|
||||
{/* 导航内容 */}
|
||||
</Drawer>
|
||||
</>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### 响应式表格
|
||||
```typescript
|
||||
import { Table } from 'antd';
|
||||
@@ -316,63 +197,18 @@ const ResponsiveTable: React.FC = () => {
|
||||
### 代码质量
|
||||
- ❌ 禁止使用 `any` 类型
|
||||
- ❌ 禁止忽略错误处理
|
||||
- ❌ 禁止硬编码API地址
|
||||
- ❌ 禁止硬编码 API 地址
|
||||
- ❌ 禁止在组件中直接使用 `fetch`
|
||||
- ❌ 禁止忽略移动端适配
|
||||
|
||||
### 类型安全
|
||||
- ❌ 禁止使用 `any`
|
||||
- ❌ 禁止忽略 TypeScript 类型检查
|
||||
- ❌ 禁止使用 `@ts-ignore` 除非有明确原因
|
||||
|
||||
### 移动端适配
|
||||
- ❌ 禁止固定宽度布局
|
||||
- ❌ 禁止使用过小的触摸目标(< 44x44px)
|
||||
- ❌ 禁止忽略移动端性能优化
|
||||
- ❌ 禁止使用桌面端专用的交互方式(如 hover)
|
||||
- ❌ 禁止使用桌面端专用交互(如 hover)
|
||||
|
||||
### 多语言使用规范
|
||||
- **必须**使用多语言(i18n)进行所有文本显示
|
||||
- **禁止**在组件中硬编码中文或英文文本
|
||||
- **必须**使用 `useTranslation` Hook 获取翻译函数
|
||||
- **必须**在语言文件中定义所有显示的文本
|
||||
- **必须**支持至少中文(简体/繁体)和英文
|
||||
|
||||
#### 多语言使用示例
|
||||
|
||||
```typescript
|
||||
// ✅ 正确:使用多语言
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
const MyComponent: React.FC = () => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1>{t('page.title')}</h1>
|
||||
<Button>{t('common.save')}</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ❌ 错误:硬编码文本
|
||||
const MyComponent: React.FC = () => {
|
||||
return (
|
||||
<div>
|
||||
<h1>页面标题</h1> {/* 禁止硬编码 */}
|
||||
<Button>保存</Button> {/* 禁止硬编码 */}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
#### 语言文件结构
|
||||
- 语言文件位置:`src/locales/{locale}/common.json`
|
||||
- 支持的语言:`zh-CN`(简体中文)、`zh-TW`(繁体中文)、`en`(英文)
|
||||
- 键名使用点号分隔的层级结构,如:`notificationSettings.title`
|
||||
|
||||
#### 添加新翻译的步骤
|
||||
1. 在 `src/locales/zh-CN/common.json` 中添加中文翻译
|
||||
2. 在 `src/locales/zh-TW/common.json` 中添加繁体中文翻译
|
||||
3. 在 `src/locales/en/common.json` 中添加英文翻译
|
||||
4. 在组件中使用 `t('key')` 获取翻译
|
||||
### 多语言
|
||||
- ❌ 禁止硬编码中文或英文文本
|
||||
- ❌ 禁止绕过 `useTranslation` 直接显示文本
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# Cursor Skills 目录结构
|
||||
|
||||
本目录遵循 [Cursor Agent Skills 规范](https://cursor.com/cn/docs/context/skills):每个技能为一个**文件夹**,内含 `SKILL.md` 及可选的 `scripts/`、`references/`、`assets/`。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
.cursor/skills/
|
||||
├── frontend/ # 前端相关 skill 分组
|
||||
│ └── check-i18n-keys/ # 单个 skill(文件夹名 = name)
|
||||
│ ├── SKILL.md # 必填,技能定义与指令
|
||||
│ └── scripts/
|
||||
│ ├── check-i18n-keys.ts
|
||||
│ └── package.json
|
||||
├── backend/ # 后端相关 skill
|
||||
└── common/ # 通用 skill
|
||||
└── create-release/ # 创建 GitHub Release
|
||||
├── SKILL.md
|
||||
└── scripts/
|
||||
└── create-release.sh
|
||||
```
|
||||
|
||||
- **SKILL.md**:YAML frontmatter(`name`、`description` 必填,`name` 须与父文件夹名一致、小写连字符)+ 给 Agent 的详细指令。
|
||||
- **scripts/**:Agent 可执行的脚本,在 SKILL.md 中用相对路径引用。
|
||||
|
||||
## 添加新 Skill
|
||||
|
||||
1. **确定分组**:在 `frontend/`、`backend/` 或 `common/` 下新建**以技能名命名的文件夹**(仅小写、数字、连字符,如 `check-i18n-keys`)。
|
||||
2. **创建 SKILL.md**:在该文件夹内创建 `SKILL.md`(大写),frontmatter 中 `name` 必须与文件夹名一致。
|
||||
3. **可选 scripts/**:在技能文件夹内建 `scripts/`,放入可执行脚本;在 SKILL.md 正文中写明运行命令(如 `cd .cursor/skills/.../scripts && npm run xxx`)。
|
||||
|
||||
## 示例
|
||||
|
||||
- `frontend/check-i18n-keys/SKILL.md` + `frontend/check-i18n-keys/scripts/` — 检查前端多语言 key
|
||||
- `common/create-release/SKILL.md` + `common/create-release/scripts/` — 创建 GitHub Release
|
||||
|
||||
## 运行 check-i18n-keys
|
||||
|
||||
```bash
|
||||
cd .cursor/skills/frontend/check-i18n-keys/scripts
|
||||
npm install
|
||||
npm run check-i18n
|
||||
```
|
||||
|
||||
## 运行 create-release
|
||||
|
||||
```bash
|
||||
cd .cursor/skills/common/create-release/scripts
|
||||
./create-release.sh -t v1.0.0 -T "Release v1.0.0" -d "发布说明"
|
||||
```
|
||||
|
||||
参数说明:
|
||||
- `-t` 版本号(必需,格式 v1.0.0)
|
||||
- `-T` Release 标题
|
||||
- `-d` Release 描述
|
||||
- `-p` 标记为 Pre-release(自动加 -beta 后缀)
|
||||
- `-y` 无交互模式
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
---
|
||||
name: create-release
|
||||
description: 创建 PolyHermes 项目的 GitHub Release。当用户要求发布版本、创建 release、打 tag 或发布新版本时使用。
|
||||
---
|
||||
|
||||
# Create Release
|
||||
|
||||
创建 PolyHermes 项目的 GitHub Release,包括创建 Git tag、推送 tag、创建 GitHub Release(支持 pre-release),并自动在 Issue #1 发布公告。
|
||||
|
||||
## 使用时机
|
||||
|
||||
- 用户要求「发布版本」「创建 release」「打 tag」「发布新版本」时
|
||||
- 用户要求「创建 pre-release」「beta 版本」时
|
||||
- 用户提到「v1.x.x」等版本号相关操作时
|
||||
|
||||
## 前置条件
|
||||
|
||||
1. **GitHub CLI 已安装**:确保 `gh` 命令可用
|
||||
2. **已登录 GitHub**:运行 `gh auth status` 确认
|
||||
3. **工作目录干净**:建议先提交所有更改
|
||||
|
||||
## 指令
|
||||
|
||||
### 步骤 1:收集发布信息
|
||||
|
||||
询问用户以下信息:
|
||||
- 版本号(格式:vX.Y.Z,如 v1.0.0)
|
||||
- 是否为 Pre-release(测试版本)
|
||||
- Release 标题和描述(可选,如未提供则自动生成)
|
||||
|
||||
### 步骤 2:生成 Release 内容
|
||||
|
||||
**重要**:如果用户未提供描述,需要根据 Git commits 自动生成。
|
||||
|
||||
1. **获取上一个版本的 tag**:
|
||||
```bash
|
||||
git describe --tags --abbrev=0 HEAD
|
||||
```
|
||||
|
||||
2. **获取版本间的 commits**:
|
||||
```bash
|
||||
git log <PREVIOUS_TAG>..HEAD --oneline --no-merges
|
||||
```
|
||||
|
||||
3. **过滤 commit 规则**:
|
||||
- **排除**:版本内新增功能的修复 commit
|
||||
- **判断方法**:如果一个 commit 的消息包含「fix」「修复」「bugfix」等关键词,且是针对同一版本内新增代码的修复,则不包含
|
||||
- **保留**:新功能、性能优化、重构、文档更新等
|
||||
|
||||
4. **生成中英文 Release 内容**:
|
||||
- 格式要求:**中文在上,英文在下**
|
||||
- 使用分隔线 `---` 分隔中英文部分
|
||||
- 按功能类型分组(新功能、改进、修复等)
|
||||
|
||||
示例格式:
|
||||
```markdown
|
||||
## 新功能
|
||||
|
||||
- 添加了 A 功能
|
||||
- 支持了 B 操作
|
||||
|
||||
## 改进
|
||||
|
||||
- 优化了 C 性能
|
||||
|
||||
---
|
||||
|
||||
## New Features
|
||||
|
||||
- Added feature A
|
||||
- Supported operation B
|
||||
|
||||
## Improvements
|
||||
|
||||
- Optimized performance C
|
||||
```
|
||||
|
||||
### 步骤 3:运行发布脚本
|
||||
|
||||
在项目根目录下执行:
|
||||
|
||||
```bash
|
||||
cd .cursor/skills/common/create-release/scripts && \
|
||||
chmod +x create-release.sh && \
|
||||
./create-release.sh -t <VERSION> [-T "<TITLE>"] [-d "<DESCRIPTION>"] [-p] [-y]
|
||||
```
|
||||
|
||||
### 步骤 4:发布公告到 Issue #1
|
||||
|
||||
**重要**:Release 创建成功后,必须自动在 Issue #1 下发布公告 comment。
|
||||
|
||||
1. **生成公告内容**(面向用户,通俗易懂):
|
||||
|
||||
公告格式模板:
|
||||
```markdown
|
||||
# 🎉 PolyHermes vX.X.X 版本发布公告
|
||||
|
||||
## 📅 发布日期
|
||||
|
||||
YYYY年MM月DD日
|
||||
|
||||
---
|
||||
|
||||
## ✨ 本次更新亮点
|
||||
|
||||
### 🚀 新功能
|
||||
|
||||
**功能名称**
|
||||
- 用通俗的语言描述这个功能是什么
|
||||
- 用户能从中获得什么好处
|
||||
- 如何使用这个功能
|
||||
|
||||
### 🔧 改进优化
|
||||
|
||||
- 优化了 XXX,现在 XXX 更快/更稳定了
|
||||
- 改进了 XXX 体验,操作更简单了
|
||||
|
||||
### 🐛 问题修复
|
||||
|
||||
- 修复了 XXX 问题,不再出现 XXX 情况
|
||||
|
||||
---
|
||||
|
||||
## 📦 如何更新
|
||||
|
||||
### Docker 部署(推荐)
|
||||
|
||||
```bash
|
||||
# 拉取最新镜像
|
||||
docker pull wrbug/polyhermes:vX.X.X
|
||||
|
||||
# 重启服务
|
||||
docker-compose -f docker-compose.prod.yml down
|
||||
docker-compose -f docker-compose.prod.yml up -d
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 安全提醒
|
||||
|
||||
**请务必使用官方 Docker 镜像源,避免财产损失!**
|
||||
|
||||
**官方镜像地址**:`wrbug/polyhermes`
|
||||
|
||||
---
|
||||
|
||||
## 📚 相关链接
|
||||
|
||||
- **GitHub Release**: https://github.com/WrBug/PolyHermes/releases/tag/vX.X.X
|
||||
- **Docker Hub**: https://hub.docker.com/r/wrbug/polyhermes
|
||||
```
|
||||
|
||||
2. **公告内容编写原则**:
|
||||
|
||||
- ✅ **通俗易懂**:避免技术术语,用用户能理解的语言
|
||||
- ✅ **突出价值**:告诉用户这个更新对他们有什么好处
|
||||
- ✅ **简洁明了**:每个功能点用 1-2 句话说明
|
||||
- ✅ **包含操作指引**:告诉用户如何使用新功能
|
||||
- ✅ **中英文双语**:中文在上,英文在下(可选)
|
||||
- ❌ **避免**:commit hash、代码细节、内部实现
|
||||
|
||||
3. **执行发布公告命令**:
|
||||
|
||||
```bash
|
||||
gh issue comment 1 --repo WrBug/PolyHermes --body "$(cat <<'EOF'
|
||||
# 🎉 PolyHermes vX.X.X 版本发布公告
|
||||
|
||||
[公告内容...]
|
||||
|
||||
---
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
或使用文件方式(内容较长时推荐):
|
||||
|
||||
```bash
|
||||
echo "[公告内容...]" > /tmp/announcement.md
|
||||
gh issue comment 1 --repo WrBug/PolyHermes --body-file /tmp/announcement.md
|
||||
```
|
||||
|
||||
### 参数说明
|
||||
|
||||
| 参数 | 说明 | 示例 |
|
||||
|------|------|------|
|
||||
| `-t, --tag` | 版本号(必需) | `-t v1.0.0` |
|
||||
| `-T, --title` | Release 标题 | `-T "Release v1.0.0"` |
|
||||
| `-d, --description` | Release 描述 | `-d "## 新功能\n- 功能1"` |
|
||||
| `-f, --description-file` | 从文件读取描述 | `-f CHANGELOG.md` |
|
||||
| `-p, --prerelease` | 标记为 Pre-release(自动加 -beta 后缀) | `-p` |
|
||||
| `-y, --yes` | 无交互模式 | `-y` |
|
||||
|
||||
## 版本号格式
|
||||
|
||||
- 必须格式:`v数字.数字.数字`(如 v1.0.0, v1.10.2, v1.1.12)
|
||||
- 如果指定 `--prerelease`,会自动拼接 `-beta` 后缀(如 v1.0.1 → v1.0.1-beta)
|
||||
|
||||
## Release 内容生成规则
|
||||
|
||||
### 中英文格式
|
||||
|
||||
Release 描述**必须**使用中英文双语格式:
|
||||
|
||||
```markdown
|
||||
## 中文标题
|
||||
|
||||
- 内容项1
|
||||
- 内容项2
|
||||
|
||||
---
|
||||
|
||||
## English Title
|
||||
|
||||
- Item 1
|
||||
- Item 2
|
||||
```
|
||||
|
||||
### Commit 过滤规则
|
||||
|
||||
**需要排除的 commit 类型**:
|
||||
|
||||
1. **版本内修复**:对同一版本新增功能的后续修复
|
||||
- 例如:v1.0.1 新增了功能 A,然后有一个 commit 修复功能 A 的 bug → 不包含
|
||||
- 判断依据:commit 消息包含「fix」「修复」「bugfix」且相关功能在本版本新增
|
||||
|
||||
2. **琐碎修改**:
|
||||
- typo 修正
|
||||
- 代码格式调整
|
||||
- 注释更新
|
||||
|
||||
**需要保留的 commit 类型**:
|
||||
|
||||
1. 新功能(feat、feature)
|
||||
2. 改进/优化(improve、optimize、enhance)
|
||||
3. 重要 bug 修复(针对旧版本的 bug)
|
||||
4. 重构(refactor)
|
||||
5. 文档更新(docs)
|
||||
|
||||
### 分组建议
|
||||
|
||||
- **新功能 / New Features**
|
||||
- **改进 / Improvements**
|
||||
- **修复 / Bug Fixes**(仅包含对旧版本 bug 的修复)
|
||||
- **其他 / Others**
|
||||
|
||||
## 公告内容示例
|
||||
|
||||
以下是一个面向用户的公告示例:
|
||||
|
||||
```markdown
|
||||
# 🎉 PolyHermes v1.2.0 版本发布公告
|
||||
|
||||
## 📅 发布日期
|
||||
|
||||
2026年3月2日
|
||||
|
||||
---
|
||||
|
||||
## ✨ 本次更新亮点
|
||||
|
||||
### 🚀 新功能
|
||||
|
||||
**系统自动更新**
|
||||
- 现在可以在网页上直接更新系统,无需手动重启 Docker
|
||||
- 更新过程约 30-60 秒,系统会自动处理
|
||||
- 如果更新失败,系统会自动恢复到旧版本
|
||||
|
||||
**RPC 节点管理**
|
||||
- 可以在系统设置中添加、编辑、删除自定义 RPC 节点
|
||||
- 可以随时启用或禁用节点
|
||||
- 系统会自动选择可用的节点
|
||||
|
||||
### 🔧 改进优化
|
||||
|
||||
- **更快的跟单响应**:通过实时监听链上交易,跟单速度提升到秒级
|
||||
- **更准确的盈亏统计**:系统会自动追踪实际成交价,统计数据更准确
|
||||
- **内存占用优化**:修复了内存泄漏问题,系统可以长时间稳定运行
|
||||
|
||||
### 🐛 问题修复
|
||||
|
||||
- 修复了部分市场无法正确查询价格的问题
|
||||
- 修复了卖出订单偶发失败的问题
|
||||
|
||||
---
|
||||
|
||||
## 📦 如何更新
|
||||
|
||||
### 方式一:网页更新(推荐)
|
||||
|
||||
1. 登录系统,进入 **系统设置** → **系统更新**
|
||||
2. 点击 **检查更新**
|
||||
3. 如果有新版本,点击 **立即升级**
|
||||
4. 等待更新完成即可
|
||||
|
||||
### 方式二:Docker 更新
|
||||
|
||||
```bash
|
||||
docker pull wrbug/polyhermes:v1.2.0
|
||||
docker-compose -f docker-compose.prod.yml down
|
||||
docker-compose -f docker-compose.prod.yml up -d
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 安全提醒
|
||||
|
||||
**请务必使用官方 Docker 镜像源!**
|
||||
|
||||
官方镜像:`wrbug/polyhermes`
|
||||
|
||||
---
|
||||
|
||||
## 📚 相关链接
|
||||
|
||||
- **GitHub Release**: https://github.com/WrBug/PolyHermes/releases/tag/v1.2.0
|
||||
- **Docker Hub**: https://hub.docker.com/r/wrbug/polyhermes
|
||||
```
|
||||
|
||||
## 发布流程
|
||||
|
||||
1. 验证版本号格式
|
||||
2. 检查 Git 工作目录状态
|
||||
3. 检查 tag 是否已存在
|
||||
4. 生成 Release 内容(中英文)
|
||||
5. 创建本地 tag
|
||||
6. 推送 tag 到远程
|
||||
7. 创建 GitHub Release
|
||||
8. **生成面向用户的公告内容**
|
||||
9. **发布公告到 Issue #1**
|
||||
10. 返回 Release URL 和公告链接
|
||||
|
||||
## 注意事项
|
||||
|
||||
- Pre-release 版本不会触发 Telegram 通知
|
||||
- GitHub Actions 会自动触发构建流程
|
||||
- 如果 tag 已存在,会提示是否删除并重新创建
|
||||
- **必须**在 Release 创建成功后发布公告到 Issue #1
|
||||
|
||||
## 可选目录说明
|
||||
|
||||
- `scripts/`:包含 `create-release.sh` 发布脚本
|
||||
@@ -0,0 +1,348 @@
|
||||
#!/bin/bash
|
||||
|
||||
# PolyHermes Release 创建脚本
|
||||
# 功能:创建 tag、推送 tag、创建 GitHub Release(支持 pre-release)
|
||||
|
||||
set -e
|
||||
|
||||
# 颜色输出
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# 打印信息
|
||||
info() {
|
||||
echo -e "${BLUE}[INFO]${NC} $1"
|
||||
}
|
||||
|
||||
success() {
|
||||
echo -e "${GREEN}[SUCCESS]${NC} $1"
|
||||
}
|
||||
|
||||
warn() {
|
||||
echo -e "${YELLOW}[WARN]${NC} $1"
|
||||
}
|
||||
|
||||
error() {
|
||||
echo -e "${RED}[ERROR]${NC} $1"
|
||||
}
|
||||
|
||||
# 显示使用说明
|
||||
usage() {
|
||||
cat << EOF
|
||||
用法: $0 [选项]
|
||||
|
||||
选项:
|
||||
-t, --tag TAG 版本号 tag(必需,格式:v1.0.0)
|
||||
-T, --title TITLE Release 标题(可选,默认使用 tag)
|
||||
-d, --description DESC Release 描述内容(可选)
|
||||
-f, --description-file FILE 从文件读取 Release 描述(可选)
|
||||
-p, --prerelease 标记为 Pre-release(会自动拼接 -beta 后缀,默认:false)
|
||||
-y, --yes 无交互模式,自动确认所有操作(默认:false)
|
||||
-h, --help 显示此帮助信息
|
||||
|
||||
示例:
|
||||
# 创建正式版本
|
||||
$0 -t v1.0.1 -T "Release v1.0.1" -d "## 新功能\n- 功能1\n- 功能2"
|
||||
|
||||
# 创建 Pre-release(自动拼接 -beta)
|
||||
$0 -t v1.0.1 -T "Release v1.0.1-beta" -d "测试版本" --prerelease
|
||||
# 实际创建的 tag: v1.0.1-beta
|
||||
|
||||
# 从文件读取描述
|
||||
$0 -t v1.0.1 -f CHANGELOG.md --prerelease
|
||||
# 实际创建的 tag: v1.0.1-beta
|
||||
|
||||
# 无交互模式(适合 CI/CD 或自动化脚本)
|
||||
$0 -t v1.0.1 -d "更新内容" --yes
|
||||
|
||||
版本号格式:
|
||||
- 必须格式: v数字.数字.数字 (例如: v1.0.0, v1.10.2, v1.1.12)
|
||||
- 如果指定 --prerelease,会自动拼接 -beta 后缀 (例如: v1.0.1 -> v1.0.1-beta)
|
||||
|
||||
EOF
|
||||
}
|
||||
|
||||
# 验证版本号格式(只允许 v数字.数字.数字,不允许后缀)
|
||||
validate_tag() {
|
||||
local tag=$1
|
||||
# 匹配格式:v数字.数字.数字(不允许后缀)
|
||||
if [[ ! "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
error "版本号格式不正确:$tag"
|
||||
error "应为 v数字.数字.数字 (例如: v1.0.0, v1.10.2, v1.1.12)"
|
||||
error "如果创建 Pre-release,请使用 --prerelease 参数,脚本会自动拼接 -beta 后缀"
|
||||
exit 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
# 检查必要的工具
|
||||
check_requirements() {
|
||||
local auto_yes=$1
|
||||
|
||||
# 检查 git
|
||||
if ! command -v git &> /dev/null; then
|
||||
error "未找到 git 命令,请先安装 git"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 检查 GitHub CLI
|
||||
if ! command -v gh &> /dev/null; then
|
||||
error "未找到 GitHub CLI (gh) 命令"
|
||||
error "请先安装 GitHub CLI: https://cli.github.com/"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 检查是否已登录 GitHub
|
||||
if ! gh auth status &> /dev/null; then
|
||||
error "未登录 GitHub,请先运行: gh auth login"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 检查是否有未提交的更改
|
||||
if [[ -n $(git status --porcelain) ]]; then
|
||||
warn "检测到未提交的更改,建议先提交或暂存"
|
||||
if [[ "$auto_yes" == "true" ]]; then
|
||||
info "无交互模式:自动继续"
|
||||
else
|
||||
read -p "是否继续?(y/N): " -n 1 -r
|
||||
echo
|
||||
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
|
||||
info "已取消"
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# 检查是否在正确的分支
|
||||
local current_branch=$(git branch --show-current)
|
||||
info "当前分支: $current_branch"
|
||||
}
|
||||
|
||||
# 检查 tag 是否已存在
|
||||
check_tag_exists() {
|
||||
local tag=$1
|
||||
local auto_yes=$2
|
||||
|
||||
if git rev-parse "$tag" >/dev/null 2>&1; then
|
||||
error "Tag $tag 已存在(本地)"
|
||||
if [[ "$auto_yes" == "true" ]]; then
|
||||
info "无交互模式:自动删除并重新创建"
|
||||
git tag -d "$tag" || true
|
||||
git push origin ":refs/tags/$tag" || true
|
||||
info "已删除旧 tag: $tag"
|
||||
else
|
||||
read -p "是否删除并重新创建?(y/N): " -n 1 -r
|
||||
echo
|
||||
if [[ $REPLY =~ ^[Yy]$ ]]; then
|
||||
git tag -d "$tag" || true
|
||||
git push origin ":refs/tags/$tag" || true
|
||||
info "已删除旧 tag: $tag"
|
||||
else
|
||||
error "已取消"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# 检查远程是否存在
|
||||
if git ls-remote --tags origin "$tag" | grep -q "$tag"; then
|
||||
error "Tag $tag 已存在于远程仓库"
|
||||
if [[ "$auto_yes" == "true" ]]; then
|
||||
info "无交互模式:自动删除并重新创建"
|
||||
git tag -d "$tag" || true
|
||||
git push origin ":refs/tags/$tag" || true
|
||||
info "已删除远程 tag: $tag"
|
||||
else
|
||||
read -p "是否删除并重新创建?(y/N): " -n 1 -r
|
||||
echo
|
||||
if [[ $REPLY =~ ^[Yy]$ ]]; then
|
||||
git tag -d "$tag" || true
|
||||
git push origin ":refs/tags/$tag" || true
|
||||
info "已删除远程 tag: $tag"
|
||||
else
|
||||
error "已取消"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# 主函数
|
||||
main() {
|
||||
local TAG=""
|
||||
local TITLE=""
|
||||
local DESCRIPTION=""
|
||||
local DESCRIPTION_FILE=""
|
||||
local PRERELEASE=false
|
||||
local AUTO_YES=false
|
||||
|
||||
# 解析参数
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case $1 in
|
||||
-t|--tag)
|
||||
TAG="$2"
|
||||
shift 2
|
||||
;;
|
||||
-T|--title)
|
||||
TITLE="$2"
|
||||
shift 2
|
||||
;;
|
||||
-d|--description)
|
||||
DESCRIPTION="$2"
|
||||
shift 2
|
||||
;;
|
||||
-f|--description-file)
|
||||
DESCRIPTION_FILE="$2"
|
||||
shift 2
|
||||
;;
|
||||
-p|--prerelease)
|
||||
PRERELEASE=true
|
||||
shift
|
||||
;;
|
||||
-y|--yes)
|
||||
AUTO_YES=true
|
||||
shift
|
||||
;;
|
||||
-h|--help)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
error "未知参数: $1"
|
||||
usage
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# 检查必需参数
|
||||
if [[ -z "$TAG" ]]; then
|
||||
error "缺少必需参数: --tag"
|
||||
usage
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 验证版本号格式(不允许后缀)
|
||||
validate_tag "$TAG"
|
||||
|
||||
# 如果指定了 --prerelease,自动拼接 -beta 后缀
|
||||
local BASE_TAG="$TAG"
|
||||
if [[ "$PRERELEASE" == "true" ]]; then
|
||||
TAG="${BASE_TAG}-beta"
|
||||
info "Pre-release 模式:tag 将自动拼接 -beta 后缀"
|
||||
info "基础版本: $BASE_TAG -> 实际 tag: $TAG"
|
||||
fi
|
||||
|
||||
# 检查工具和环境
|
||||
check_requirements "$AUTO_YES"
|
||||
|
||||
# 检查 tag 是否已存在(使用拼接后的 tag)
|
||||
check_tag_exists "$TAG" "$AUTO_YES"
|
||||
|
||||
# 设置默认标题
|
||||
if [[ -z "$TITLE" ]]; then
|
||||
TITLE="$TAG"
|
||||
fi
|
||||
|
||||
# 读取描述内容
|
||||
if [[ -n "$DESCRIPTION_FILE" ]]; then
|
||||
if [[ ! -f "$DESCRIPTION_FILE" ]]; then
|
||||
error "描述文件不存在: $DESCRIPTION_FILE"
|
||||
exit 1
|
||||
fi
|
||||
DESCRIPTION=$(cat "$DESCRIPTION_FILE")
|
||||
fi
|
||||
|
||||
# 如果没有描述,使用默认值
|
||||
if [[ -z "$DESCRIPTION" ]]; then
|
||||
if [[ "$PRERELEASE" == "true" ]]; then
|
||||
DESCRIPTION="Pre-release $TAG"
|
||||
else
|
||||
DESCRIPTION="Release $TAG"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 显示即将执行的操作
|
||||
echo
|
||||
info "========================================="
|
||||
info " PolyHermes Release 创建"
|
||||
info "========================================="
|
||||
info "Tag: $TAG"
|
||||
info "Title: $TITLE"
|
||||
info "Pre-release: $PRERELEASE"
|
||||
if [[ "$AUTO_YES" == "true" ]]; then
|
||||
info "模式: 无交互模式(自动确认)"
|
||||
fi
|
||||
info "Description:"
|
||||
echo "$DESCRIPTION" | sed 's/^/ /'
|
||||
info "========================================="
|
||||
echo
|
||||
|
||||
# 确认操作
|
||||
if [[ "$AUTO_YES" == "true" ]]; then
|
||||
info "无交互模式:自动确认创建 Release"
|
||||
else
|
||||
read -p "确认创建 Release?(y/N): " -n 1 -r
|
||||
echo
|
||||
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
|
||||
info "已取消"
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
|
||||
# 1. 创建 tag(基于当前 HEAD)
|
||||
info "创建 tag: $TAG"
|
||||
git tag "$TAG"
|
||||
success "Tag 创建成功: $TAG"
|
||||
|
||||
# 2. 推送 tag 到远程
|
||||
info "推送 tag 到远程..."
|
||||
git push origin "$TAG"
|
||||
success "Tag 推送成功"
|
||||
|
||||
# 3. 创建 GitHub Release
|
||||
info "创建 GitHub Release..."
|
||||
|
||||
local RELEASE_ARGS=(
|
||||
"$TAG"
|
||||
--title "$TITLE"
|
||||
--notes "$DESCRIPTION"
|
||||
)
|
||||
|
||||
if [[ "$PRERELEASE" == "true" ]]; then
|
||||
RELEASE_ARGS+=(--prerelease)
|
||||
fi
|
||||
|
||||
if gh release create "${RELEASE_ARGS[@]}"; then
|
||||
success "GitHub Release 创建成功!"
|
||||
|
||||
# 获取 release URL
|
||||
local RELEASE_URL=$(gh release view "$TAG" --json url -q .url)
|
||||
info "Release URL: $RELEASE_URL"
|
||||
|
||||
echo
|
||||
success "========================================="
|
||||
success " Release 创建完成!"
|
||||
success "========================================="
|
||||
success "Tag: $TAG"
|
||||
success "Pre-release: $PRERELEASE"
|
||||
success "URL: $RELEASE_URL"
|
||||
success "========================================="
|
||||
echo
|
||||
info "GitHub Actions 将自动触发构建流程"
|
||||
|
||||
if [[ "$PRERELEASE" == "true" ]]; then
|
||||
warn "这是 Pre-release,GitHub Actions 不会发送 Telegram 通知"
|
||||
fi
|
||||
else
|
||||
error "GitHub Release 创建失败"
|
||||
error "请手动在 GitHub 上创建 Release: https://github.com/WrBug/PolyHermes/releases/new"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# 执行主函数
|
||||
main "$@"
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
name: check-i18n-keys
|
||||
description: 检查前端多语言 key 完整性。当用户要求检查 i18n、多语言缺失、翻译 key 或运行 check-i18n 时使用。
|
||||
---
|
||||
|
||||
# Check I18n Keys
|
||||
|
||||
检查前端代码中使用的 i18n key 是否在所有语言文件(zh-CN、zh-TW、en)中存在,并报告缺失或语言间不一致的 key。
|
||||
|
||||
## 使用时机
|
||||
|
||||
- 用户要求「检查多语言」「检查 i18n」「扫一下 key」「多语言缺失」时
|
||||
- 用户要求运行多语言检查或执行 check-i18n 时
|
||||
- 在修改或新增前端文案后,需要确认三语言 key 一致时
|
||||
|
||||
## 指令
|
||||
|
||||
1. **运行检查脚本**(在项目仓库根目录下执行):
|
||||
```bash
|
||||
cd .cursor/skills/frontend/check-i18n-keys/scripts && npm install && npm run check-i18n
|
||||
```
|
||||
首次运行需先 `npm install`,之后可直接 `npm run check-i18n`。
|
||||
|
||||
2. **脚本行为**:
|
||||
- 扫描 `frontend/` 下所有 `.ts`、`.tsx`、`.js`、`.jsx`(排除 node_modules、dist、build、*.d.ts)
|
||||
- 提取代码中 `t('key')` / `t("key")` 的 key
|
||||
- 与 `frontend/src/locales/{zh-CN,zh-TW,en}/common.json` 对比
|
||||
- 报告:代码中使用但某语言 JSON 缺失的 key;某语言有而另一语言没有的 key(不一致)
|
||||
|
||||
3. **结果处理**:
|
||||
- 若有缺失或不一致,退出码为 1;可根据报告在对应 `common.json` 中补全 key
|
||||
- 脚本路径:`scripts/check-i18n-keys.ts`(相对本 skill 根目录)
|
||||
|
||||
## 可选目录说明
|
||||
|
||||
- `scripts/`:可执行检查脚本,Agent 按上述命令调用。
|
||||
@@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
*.log
|
||||
.DS_Store
|
||||
@@ -0,0 +1,302 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* 检查前端多语言 key 完整性
|
||||
*
|
||||
* 扫描范围:frontend 下所有 .ts / .tsx / .js / .jsx(排除 node_modules、dist、build、*.d.ts)
|
||||
*
|
||||
* 支持的检查:
|
||||
* 1. 代码引用但 JSON 没有:某 ts/js 引用了 t("common.test"),但任意语言 common.json 里没有该 key → 报缺失
|
||||
* 2. 语言间不一致:zh-CN/zh-TW 的 JSON 有 common.xxx,但 en 的没有 → 报不一致(某些语言有、某些没有)
|
||||
*/
|
||||
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { glob } from 'glob';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
interface CheckResult {
|
||||
usedKeys: Set<string>;
|
||||
localeKeys: {
|
||||
'zh-CN': Set<string>;
|
||||
'zh-TW': Set<string>;
|
||||
'en': Set<string>;
|
||||
};
|
||||
missingKeys: {
|
||||
'zh-CN': string[];
|
||||
'zh-TW': string[];
|
||||
'en': string[];
|
||||
};
|
||||
inconsistentKeys: Array<{
|
||||
key: string;
|
||||
existsIn: string[];
|
||||
missingIn: string[];
|
||||
}>;
|
||||
}
|
||||
|
||||
const LOCALES = ['zh-CN', 'zh-TW', 'en'] as const;
|
||||
type Locale = typeof LOCALES[number];
|
||||
|
||||
// 颜色输出(如果支持)
|
||||
const colors = {
|
||||
reset: '\x1b[0m',
|
||||
red: '\x1b[31m',
|
||||
green: '\x1b[32m',
|
||||
yellow: '\x1b[33m',
|
||||
blue: '\x1b[34m',
|
||||
cyan: '\x1b[36m',
|
||||
};
|
||||
|
||||
function log(message: string, color: keyof typeof colors = 'reset') {
|
||||
console.log(`${colors[color]}${message}${colors.reset}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从代码文件中提取所有 t() 调用中的 key
|
||||
*/
|
||||
function extractKeysFromCode(frontendDir: string): Set<string> {
|
||||
const keys = new Set<string>();
|
||||
|
||||
// 匹配 t('key') 或 t("key") 或 t(`key`)
|
||||
const tPattern = /t\(['"`]([^'"`]+)['"`]\)/g;
|
||||
|
||||
// 扫描所有 TS/JS 文件(含 .ts .tsx .js .jsx),排除 node_modules、dist、build、*.d.ts
|
||||
const files = glob.sync('**/*.{ts,tsx,js,jsx}', {
|
||||
cwd: frontendDir,
|
||||
ignore: ['**/node_modules/**', '**/dist/**', '**/build/**', '**/*.d.ts'],
|
||||
absolute: true,
|
||||
});
|
||||
|
||||
for (const file of files) {
|
||||
try {
|
||||
const content = fs.readFileSync(file, 'utf-8');
|
||||
let match;
|
||||
|
||||
while ((match = tPattern.exec(content)) !== null) {
|
||||
const key = match[1];
|
||||
// 过滤掉模板字符串中的变量(如 t(`key.${variable}`))
|
||||
if (!key.includes('${') && !key.includes('${')) {
|
||||
keys.add(key);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error reading file ${file}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载语言文件
|
||||
*/
|
||||
function loadLocaleFile(localeDir: string, locale: Locale): Record<string, any> {
|
||||
const filePath = path.join(localeDir, locale, 'common.json');
|
||||
|
||||
if (!fs.existsSync(filePath)) {
|
||||
log(`⚠️ 语言文件不存在: ${filePath}`, 'yellow');
|
||||
return {};
|
||||
}
|
||||
|
||||
try {
|
||||
const content = fs.readFileSync(filePath, 'utf-8');
|
||||
return JSON.parse(content);
|
||||
} catch (error) {
|
||||
log(`❌ 解析语言文件失败 ${filePath}: ${error}`, 'red');
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 展平嵌套对象为点分隔的 key 路径
|
||||
*/
|
||||
function flattenKeys(obj: Record<string, any>, prefix = ''): Set<string> {
|
||||
const keys = new Set<string>();
|
||||
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
const fullKey = prefix ? `${prefix}.${key}` : key;
|
||||
|
||||
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
||||
// 递归处理嵌套对象
|
||||
const nestedKeys = flattenKeys(value, fullKey);
|
||||
nestedKeys.forEach(k => keys.add(k));
|
||||
} else {
|
||||
// 叶子节点
|
||||
keys.add(fullKey);
|
||||
}
|
||||
}
|
||||
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查 key 完整性
|
||||
*/
|
||||
function checkKeys(usedKeys: Set<string>, localeKeys: Record<Locale, Set<string>>): CheckResult {
|
||||
const result: CheckResult = {
|
||||
usedKeys,
|
||||
localeKeys,
|
||||
missingKeys: {
|
||||
'zh-CN': [],
|
||||
'zh-TW': [],
|
||||
'en': [],
|
||||
},
|
||||
inconsistentKeys: [],
|
||||
};
|
||||
|
||||
// 检查每个语言文件中缺失的 key
|
||||
for (const locale of LOCALES) {
|
||||
for (const key of usedKeys) {
|
||||
if (!localeKeys[locale].has(key)) {
|
||||
result.missingKeys[locale].push(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 检查不一致的 key(某些语言有,某些没有)
|
||||
const allLocaleKeys = new Set<string>();
|
||||
LOCALES.forEach(locale => {
|
||||
localeKeys[locale].forEach(key => allLocaleKeys.add(key));
|
||||
});
|
||||
|
||||
for (const key of allLocaleKeys) {
|
||||
const existsIn: Locale[] = [];
|
||||
const missingIn: Locale[] = [];
|
||||
|
||||
for (const locale of LOCALES) {
|
||||
if (localeKeys[locale].has(key)) {
|
||||
existsIn.push(locale);
|
||||
} else {
|
||||
missingIn.push(locale);
|
||||
}
|
||||
}
|
||||
|
||||
// 如果某些语言有,某些没有,则不一致
|
||||
if (existsIn.length > 0 && existsIn.length < LOCALES.length) {
|
||||
result.inconsistentKeys.push({
|
||||
key,
|
||||
existsIn,
|
||||
missingIn,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印检查报告
|
||||
*/
|
||||
function printReport(result: CheckResult): void {
|
||||
log('\n=== 多语言 Key 检查报告 ===\n', 'cyan');
|
||||
|
||||
// 统计信息
|
||||
log('📊 统计信息:', 'blue');
|
||||
log(` - 代码中使用的 key 数量: ${result.usedKeys.size}`);
|
||||
log(` - zh-CN 语言文件 key 数量: ${result.localeKeys['zh-CN'].size}`);
|
||||
log(` - zh-TW 语言文件 key 数量: ${result.localeKeys['zh-TW'].size}`);
|
||||
log(` - en 语言文件 key 数量: ${result.localeKeys['en'].size}`);
|
||||
log('');
|
||||
|
||||
// 缺失的 key
|
||||
let hasMissing = false;
|
||||
for (const locale of LOCALES) {
|
||||
if (result.missingKeys[locale].length > 0) {
|
||||
hasMissing = true;
|
||||
log(`❌ 缺失的 Key (代码中使用但 ${locale} 语言文件中不存在):`, 'red');
|
||||
result.missingKeys[locale].forEach(key => {
|
||||
log(` - ${key}`, 'red');
|
||||
});
|
||||
log('');
|
||||
}
|
||||
}
|
||||
|
||||
// 不一致的 key
|
||||
if (result.inconsistentKeys.length > 0) {
|
||||
log('⚠️ 不一致的 Key (某些语言文件有,某些没有):', 'yellow');
|
||||
result.inconsistentKeys.forEach(({ key, existsIn, missingIn }) => {
|
||||
log(` - ${key}`, 'yellow');
|
||||
log(` 存在于: ${existsIn.join(', ')}`, 'yellow');
|
||||
log(` 缺失于: ${missingIn.join(', ')}`, 'yellow');
|
||||
});
|
||||
log('');
|
||||
}
|
||||
|
||||
// 总结
|
||||
const hasErrors = hasMissing || result.inconsistentKeys.length > 0;
|
||||
|
||||
if (hasErrors) {
|
||||
log('❌ 检查失败:发现缺失或不一致的 key', 'red');
|
||||
} else {
|
||||
log('✅ 检查通过:所有 key 都完整且一致', 'green');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 主函数
|
||||
*/
|
||||
function main(): void {
|
||||
// 脚本位于 .cursor/skills/frontend/check-i18n-keys/scripts/,向上到项目根
|
||||
const scriptDir = __dirname;
|
||||
const skillDir = path.resolve(scriptDir, '..');
|
||||
const frontendSkillDir = path.resolve(skillDir, '..');
|
||||
const repoRoot = path.resolve(frontendSkillDir, '../../..');
|
||||
const frontendDir = path.join(repoRoot, 'frontend');
|
||||
const localesDir = path.join(frontendDir, 'src', 'locales');
|
||||
|
||||
// 检查目录是否存在
|
||||
if (!fs.existsSync(frontendDir)) {
|
||||
log(`❌ 前端目录不存在: ${frontendDir}`, 'red');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (!fs.existsSync(localesDir)) {
|
||||
log(`❌ 语言文件目录不存在: ${localesDir}`, 'red');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
log('🔍 开始检查多语言 key...\n', 'cyan');
|
||||
|
||||
// 1. 提取代码中使用的 key
|
||||
log('📝 扫描代码文件...', 'blue');
|
||||
const usedKeys = extractKeysFromCode(frontendDir);
|
||||
log(` 找到 ${usedKeys.size} 个使用的 key\n`, 'green');
|
||||
|
||||
// 2. 加载语言文件
|
||||
log('📚 加载语言文件...', 'blue');
|
||||
const localeKeys: Record<Locale, Set<string>> = {
|
||||
'zh-CN': new Set(),
|
||||
'zh-TW': new Set(),
|
||||
'en': new Set(),
|
||||
};
|
||||
|
||||
for (const locale of LOCALES) {
|
||||
const localeObj = loadLocaleFile(localesDir, locale);
|
||||
localeKeys[locale] = flattenKeys(localeObj);
|
||||
log(` ${locale}: ${localeKeys[locale].size} 个 key`, 'green');
|
||||
}
|
||||
log('');
|
||||
|
||||
// 3. 检查
|
||||
log('🔎 检查 key 完整性...', 'blue');
|
||||
const result = checkKeys(usedKeys, localeKeys);
|
||||
|
||||
// 4. 输出报告
|
||||
printReport(result);
|
||||
|
||||
// 5. 退出码
|
||||
const hasErrors =
|
||||
result.missingKeys['zh-CN'].length > 0 ||
|
||||
result.missingKeys['zh-TW'].length > 0 ||
|
||||
result.missingKeys['en'].length > 0 ||
|
||||
result.inconsistentKeys.length > 0;
|
||||
|
||||
process.exit(hasErrors ? 1 : 0);
|
||||
}
|
||||
|
||||
// 运行
|
||||
main();
|
||||
|
||||
@@ -0,0 +1,680 @@
|
||||
{
|
||||
"name": "cursor-skill-frontend-scripts",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "cursor-skill-frontend-scripts",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"glob": "^13.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.10.0",
|
||||
"tsx": "^4.7.0",
|
||||
"typescript": "^5.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.3.tgz",
|
||||
"integrity": "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"aix"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-arm": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.3.tgz",
|
||||
"integrity": "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-arm64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.3.tgz",
|
||||
"integrity": "sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-x64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.3.tgz",
|
||||
"integrity": "sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/darwin-arm64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.3.tgz",
|
||||
"integrity": "sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/darwin-x64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.3.tgz",
|
||||
"integrity": "sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/freebsd-arm64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.3.tgz",
|
||||
"integrity": "sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/freebsd-x64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.3.tgz",
|
||||
"integrity": "sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-arm": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.3.tgz",
|
||||
"integrity": "sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-arm64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.3.tgz",
|
||||
"integrity": "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-ia32": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.3.tgz",
|
||||
"integrity": "sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-loong64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.3.tgz",
|
||||
"integrity": "sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==",
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-mips64el": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.3.tgz",
|
||||
"integrity": "sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==",
|
||||
"cpu": [
|
||||
"mips64el"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-ppc64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.3.tgz",
|
||||
"integrity": "sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-riscv64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.3.tgz",
|
||||
"integrity": "sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==",
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-s390x": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.3.tgz",
|
||||
"integrity": "sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==",
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-x64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.3.tgz",
|
||||
"integrity": "sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/netbsd-arm64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.3.tgz",
|
||||
"integrity": "sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"netbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/netbsd-x64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.3.tgz",
|
||||
"integrity": "sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"netbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openbsd-arm64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.3.tgz",
|
||||
"integrity": "sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openbsd-x64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.3.tgz",
|
||||
"integrity": "sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openharmony-arm64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.3.tgz",
|
||||
"integrity": "sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openharmony"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/sunos-x64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.3.tgz",
|
||||
"integrity": "sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"sunos"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-arm64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.3.tgz",
|
||||
"integrity": "sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-ia32": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.3.tgz",
|
||||
"integrity": "sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-x64": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.3.tgz",
|
||||
"integrity": "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@isaacs/balanced-match": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@isaacs/balanced-match/-/balanced-match-4.0.1.tgz",
|
||||
"integrity": "sha512-yzMTt9lEb8Gv7zRioUilSglI0c0smZ9k5D65677DLWLtWJaXIS3CqcGyUFByYKlnUj6TkjLVs54fBl6+TiGQDQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/@isaacs/brace-expansion": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@isaacs/brace-expansion/-/brace-expansion-5.0.1.tgz",
|
||||
"integrity": "sha512-WMz71T1JS624nWj2n2fnYAuPovhv7EUhk69R6i9dsVyzxt5eM3bjwvgk9L+APE1TRscGysAVMANkB0jh0LQZrQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@isaacs/balanced-match": "^4.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "20.19.33",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.33.tgz",
|
||||
"integrity": "sha512-Rs1bVAIdBs5gbTIKza/tgpMuG1k3U/UMJLWecIMxNdJFDMzcM5LOiLVRYh3PilWEYDIeUDv7bpiHPLPsbydGcw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/esbuild": {
|
||||
"version": "0.27.3",
|
||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.3.tgz",
|
||||
"integrity": "sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"esbuild": "bin/esbuild"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@esbuild/aix-ppc64": "0.27.3",
|
||||
"@esbuild/android-arm": "0.27.3",
|
||||
"@esbuild/android-arm64": "0.27.3",
|
||||
"@esbuild/android-x64": "0.27.3",
|
||||
"@esbuild/darwin-arm64": "0.27.3",
|
||||
"@esbuild/darwin-x64": "0.27.3",
|
||||
"@esbuild/freebsd-arm64": "0.27.3",
|
||||
"@esbuild/freebsd-x64": "0.27.3",
|
||||
"@esbuild/linux-arm": "0.27.3",
|
||||
"@esbuild/linux-arm64": "0.27.3",
|
||||
"@esbuild/linux-ia32": "0.27.3",
|
||||
"@esbuild/linux-loong64": "0.27.3",
|
||||
"@esbuild/linux-mips64el": "0.27.3",
|
||||
"@esbuild/linux-ppc64": "0.27.3",
|
||||
"@esbuild/linux-riscv64": "0.27.3",
|
||||
"@esbuild/linux-s390x": "0.27.3",
|
||||
"@esbuild/linux-x64": "0.27.3",
|
||||
"@esbuild/netbsd-arm64": "0.27.3",
|
||||
"@esbuild/netbsd-x64": "0.27.3",
|
||||
"@esbuild/openbsd-arm64": "0.27.3",
|
||||
"@esbuild/openbsd-x64": "0.27.3",
|
||||
"@esbuild/openharmony-arm64": "0.27.3",
|
||||
"@esbuild/sunos-x64": "0.27.3",
|
||||
"@esbuild/win32-arm64": "0.27.3",
|
||||
"@esbuild/win32-ia32": "0.27.3",
|
||||
"@esbuild/win32-x64": "0.27.3"
|
||||
}
|
||||
},
|
||||
"node_modules/fsevents": {
|
||||
"version": "2.3.3",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
||||
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/get-tsconfig": {
|
||||
"version": "4.13.6",
|
||||
"resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.6.tgz",
|
||||
"integrity": "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"resolve-pkg-maps": "^1.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/glob": {
|
||||
"version": "13.0.1",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-13.0.1.tgz",
|
||||
"integrity": "sha512-B7U/vJpE3DkJ5WXTgTpTRN63uV42DseiXXKMwG14LQBXmsdeIoHAPbU/MEo6II0k5ED74uc2ZGTC6MwHFQhF6w==",
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
"minimatch": "^10.1.2",
|
||||
"minipass": "^7.1.2",
|
||||
"path-scurry": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "20 || >=22"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/lru-cache": {
|
||||
"version": "11.2.5",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.5.tgz",
|
||||
"integrity": "sha512-vFrFJkWtJvJnD5hg+hJvVE8Lh/TcMzKnTgCWmtBipwI5yLX/iX+5UB2tfuyODF5E7k9xEzMdYgGqaSb1c0c5Yw==",
|
||||
"license": "BlueOak-1.0.0",
|
||||
"engines": {
|
||||
"node": "20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/minimatch": {
|
||||
"version": "10.1.2",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.1.2.tgz",
|
||||
"integrity": "sha512-fu656aJ0n2kcXwsnwnv9g24tkU5uSmOlTjd6WyyaKm2Z+h1qmY6bAjrcaIxF/BslFqbZ8UBtbJi7KgQOZD2PTw==",
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
"@isaacs/brace-expansion": "^5.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "20 || >=22"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/minipass": {
|
||||
"version": "7.1.2",
|
||||
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz",
|
||||
"integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=16 || 14 >=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/path-scurry": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.1.tgz",
|
||||
"integrity": "sha512-oWyT4gICAu+kaA7QWk/jvCHWarMKNs6pXOGWKDTr7cw4IGcUbW+PeTfbaQiLGheFRpjo6O9J0PmyMfQPjH71oA==",
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
"lru-cache": "^11.0.0",
|
||||
"minipass": "^7.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "20 || >=22"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/resolve-pkg-maps": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",
|
||||
"integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/tsx": {
|
||||
"version": "4.21.0",
|
||||
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz",
|
||||
"integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"esbuild": "~0.27.0",
|
||||
"get-tsconfig": "^4.7.5"
|
||||
},
|
||||
"bin": {
|
||||
"tsx": "dist/cli.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"fsevents": "~2.3.3"
|
||||
}
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.9.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "6.21.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "cursor-skill-frontend-scripts",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"check-i18n": "tsx check-i18n-keys.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"glob": "^13.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.10.0",
|
||||
"tsx": "^4.7.0",
|
||||
"typescript": "^5.3.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ES2022",
|
||||
"moduleResolution": "node",
|
||||
"lib": ["ES2022"],
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"downlevelIteration": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["*.ts"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
|
||||
+2
-2
@@ -14,11 +14,11 @@
|
||||
.DS_Store
|
||||
|
||||
# 构建产物
|
||||
backend/build/
|
||||
# 注意:frontend/dist 和 backend/build/libs 在使用 BUILD_IN_DOCKER=false 时是必需的
|
||||
# 所以不能忽略它们。在 BUILD_IN_DOCKER=true 时,它们会被 Docker 内部编译覆盖
|
||||
backend/.gradle/
|
||||
backend/out/
|
||||
backend/bin/
|
||||
frontend/dist/
|
||||
frontend/node_modules/
|
||||
frontend/.vite/
|
||||
frontend/.cache/
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
---
|
||||
name: 🤖 Bug Report for AI Fix / AI Bug 报告
|
||||
description: Bug 报告模板(提交后请手动添加 'fix via ai' 标签触发自动修复)
|
||||
title: '[Bug] / '
|
||||
assignees: []
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
## Bug Report Template 🐛
|
||||
|
||||
本模板用于报告 PolyHermes 项目的 bug。
|
||||
|
||||
⚠️ **Important / 重要提示**:
|
||||
- After submission, if you need AI auto-fix, please manually add the `fix via ai` label
|
||||
/ 提交后,如需 AI 自动修复,请手动添加 `fix via ai` 标签
|
||||
- AI fixes will be on the `fix_issues_by_ai` branch / AI 修复将在 `fix_issues_by_ai` 分支上进行
|
||||
- All AI fixes require human review before merging / 所有 AI 修复需要人工审核后才能合并
|
||||
- Security vulnerabilities, database migrations, major changes are not recommended for AI auto-fix
|
||||
/ 涉及安全漏洞、数据库迁移、重大变更等问题不建议使用 AI 自动修复
|
||||
|
||||
---
|
||||
|
||||
本模板用于报告 PolyHermes 项目的 bug。
|
||||
|
||||
This template is for reporting bugs in the PolyHermes project.
|
||||
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: 📝 Bug Description / Bug 描述
|
||||
description: Clearly and concisely describe the bug / 清晰简洁地描述这个 bug
|
||||
placeholder: Describe the bug you encountered / 描述你遇到的问题...
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: type
|
||||
attributes:
|
||||
label: 🎯 Bug Type / 问题类型
|
||||
description: Select the type of bug / 选择问题类型
|
||||
options:
|
||||
- Frontend bug (UI/UX/interaction) / 前端 bug (UI/UX/交互问题)
|
||||
- Backend bug (API/logic/data) / 后端 bug (API/逻辑/数据处理)
|
||||
- Database issue / 数据库问题
|
||||
- Performance issue / 性能问题
|
||||
- Configuration/Deployment / 配置/部署问题
|
||||
- Documentation / 文档问题
|
||||
- Other / 其他
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: scope
|
||||
attributes:
|
||||
label: 📍 Affected Scope / 影响范围
|
||||
description: Select the scope of impact / 选择问题影响范围
|
||||
options:
|
||||
- Specific page/function only / 仅影响特定页面/功能
|
||||
- Entire system / 影响整个系统
|
||||
- Specific user role / 影响特定用户角色
|
||||
- Only in specific environment / 仅在特定环境下重现
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: 🔍 Steps to Reproduce / 复现步骤
|
||||
description: Provide clear, detailed steps to reproduce the bug / 提供清晰、详细的步骤来重现这个 bug
|
||||
placeholder: |
|
||||
1. Visit page: `...` / 访问页面:`...`
|
||||
2. Click button: `...` / 点击按钮:`...`
|
||||
3. Input data: `...` / 输入数据:`...`
|
||||
4. Submit form: `...` / 提交表单:`...`
|
||||
5. Observe error: `...` / 观察到错误:`...`
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: frequency
|
||||
attributes:
|
||||
label: Reproduction Frequency / 复现频率
|
||||
options:
|
||||
- Always reproducible (100%) / 总是能复现 (100%)
|
||||
- Frequently reproducible (50%+) / 经常能复现 (50%+)
|
||||
- Occasionally reproducible (<50%) / 偶尔能复现 (<50%)
|
||||
- Hard to reproduce / 很难复现
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: 💻 Expected Behavior / 预期行为
|
||||
description: Describe what you expected to happen / 描述你期望发生什么
|
||||
placeholder: What should happen / 应该发生什么...
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: actual
|
||||
attributes:
|
||||
label: ❌ Actual Behavior / 实际行为
|
||||
description: Describe what actually happened / 描述实际发生了什么
|
||||
placeholder: What actually happened / 实际发生了什么...
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: screenshots
|
||||
attributes:
|
||||
label: 📸 Screenshots / Recordings / 截图/录屏
|
||||
description: If applicable, add screenshots or recordings to illustrate the problem (drag and drop files here)
|
||||
/ 如果适用,添加截图或录屏来说明问题(可以拖拽文件到这里)
|
||||
placeholder: Add screenshots or recordings / 添加截图或录屏...
|
||||
|
||||
- type: textarea
|
||||
id: environment
|
||||
attributes:
|
||||
label: 🌐 Environment / 环境
|
||||
description: Provide relevant environment information / 提供相关环境信息
|
||||
value: |
|
||||
**Browser (for frontend issues) / 浏览器(前端问题):**
|
||||
- Browser: ______ / 浏览器:______
|
||||
- Browser version: ______ / 浏览器版本:______
|
||||
- Operating System: ______ / 操作系统:______
|
||||
|
||||
**Backend Environment (for backend issues) / 后端环境(后端问题):**
|
||||
- Node.js version: ______ / Node.js 版本:______
|
||||
- Database version: ______ / 数据库版本:______
|
||||
- Docker version (if used): ______ / Docker 版本(如果使用):______
|
||||
- Other relevant dependencies: ______ / 其他相关依赖版本:______
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
id: related-files
|
||||
attributes:
|
||||
label: 📁 Related Files / Code / 相关文件/代码
|
||||
description: Provide relevant file paths or code snippets / 提供可能涉及的文件路径或相关代码片段
|
||||
placeholder: |
|
||||
Possibly related files / 可能涉及的文件:
|
||||
- frontend/src/components/...
|
||||
- backend/src/main/kotlin/...
|
||||
|
||||
Error logs / 错误日志:
|
||||
```
|
||||
Paste error logs here / 粘贴错误日志
|
||||
```
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
id: suggestions
|
||||
attributes:
|
||||
label: 🎯 Fix Suggestions (Optional) / 修复建议(可选)
|
||||
description: If you have fix ideas, describe them briefly / 如果你有修复思路,可以在这里简单描述
|
||||
placeholder: |
|
||||
Suggest adding ZZZ check in the YYY method of file XXX
|
||||
/ 建议在 XXX 文件的 YYY 方法中,添加 ZZZ 检查
|
||||
...
|
||||
|
||||
- type: dropdown
|
||||
id: priority
|
||||
attributes:
|
||||
label: 🚨 Priority / 优先级
|
||||
options:
|
||||
- 🔴 High - Blocking core functionality, affects user experience / 高 - 阻塞核心功能,影响用户体验
|
||||
- 🟡 Medium - Limited functionality but not blocking / 中 - 功能受限但不阻塞
|
||||
- 🟢 Low - Minor issue, doesn't affect usage / 低 - 小问题,不影响使用
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: additional
|
||||
attributes:
|
||||
label: 📝 Additional Information / 补充说明
|
||||
description: Any other information that helps AI understand and fix the issue / 任何其他有助于 AI 理解和修复问题的信息
|
||||
placeholder: |
|
||||
- Was this bug introduced recently? / 这个 bug 是最近引入的吗?
|
||||
- Is it related to a specific PR or commit? / 是否与某个特定的 PR 或 commit 相关?
|
||||
- Does it only occur with specific datasets or users? / 是否只在特定数据集或特定用户情况下出现?
|
||||
/ ...
|
||||
Any other context / 其他任何上下文信息...
|
||||
|
||||
- type: checkboxes
|
||||
id: ai-fix-approval
|
||||
attributes:
|
||||
label: 🤖 AI Auto-Fix Confirmation / AI 自动修复确认
|
||||
description: If you need AI to auto-fix this issue, check the options below (remember to add 'fix via ai' label after submission)
|
||||
/ 如需 AI 自动修复此 issue,请勾选下方选项(提交后记得添加 'fix via ai' 标签)
|
||||
options:
|
||||
- label: |
|
||||
I understand the AI auto-fix workflow and agree to manually review the AI-created PR
|
||||
/ 我已了解 AI 自动修复的工作流程,并同意在 AI 创建 PR 后进行人工审核
|
||||
required: false
|
||||
- label: |
|
||||
This issue is suitable for AI auto-fix (not a security vulnerability, not a database migration, not a major change)
|
||||
/ 此问题适合 AI 自动修复(非安全漏洞、非数据库迁移、非重大变更)
|
||||
required: false
|
||||
@@ -0,0 +1,127 @@
|
||||
# PR 合并后自动关闭关联的 Issue
|
||||
# 当 PR 从 ai_fix/N_xxx 分支合并到 main 时,关闭 #N 对应的 Issue(若 PR 描述中未含 Closes #N 则通过分支名解析)
|
||||
# 关闭后发送 Telegram 通知(复用 TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID)
|
||||
|
||||
name: Close issue on PR merge
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [closed]
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
close-issue:
|
||||
if: github.event.pull_request.merged == true
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: read
|
||||
|
||||
steps:
|
||||
- name: Get PR info
|
||||
id: pr
|
||||
run: |
|
||||
# 从 PR body 查找 Closes #N / Fixes #N(若已有则 GitHub 已自动关 issue,本 step 仅做解析)
|
||||
BODY="${{ github.event.pull_request.body }}"
|
||||
HEAD_REF="${{ github.event.pull_request.head.ref }}"
|
||||
|
||||
# 优先从 PR 描述解析(无匹配时 grep 会 exit 1,需 || true 避免 set -e 导致脚本退出)
|
||||
ISSUE_NUM=$(echo "$BODY" | grep -oE '(Closes|Fixes|Resolves) #([0-9]+)' | head -1 | grep -oE '[0-9]+' || true)
|
||||
if [ -z "$ISSUE_NUM" ]; then
|
||||
# 从分支名解析 ai_fix/N_xxx
|
||||
ISSUE_NUM=$(echo "$HEAD_REF" | sed -n 's|^ai_fix/\([0-9]*\)_.*|\1|p')
|
||||
fi
|
||||
|
||||
if [ -z "$ISSUE_NUM" ]; then
|
||||
echo "ISSUE_NUMBER=" >> $GITHUB_OUTPUT
|
||||
echo "skip=true" >> $GITHUB_OUTPUT
|
||||
echo "未从 PR 描述或分支名解析到 Issue 编号,跳过关闭"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "ISSUE_NUMBER=$ISSUE_NUM" >> $GITHUB_OUTPUT
|
||||
echo "skip=false" >> $GITHUB_OUTPUT
|
||||
echo "解析到 Issue #$ISSUE_NUM"
|
||||
|
||||
- name: Get issue details
|
||||
if: steps.pr.outputs.skip != 'true'
|
||||
id: issue
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
ISSUE_NUM="${{ steps.pr.outputs.ISSUE_NUMBER }}"
|
||||
# 获取 issue 标题与 URL(用于 TG 消息)
|
||||
JSON=$(gh issue view "$ISSUE_NUM" --json title,url 2>/dev/null || echo '{"title":"","url":""}')
|
||||
TITLE=$(echo "$JSON" | jq -r '.title')
|
||||
ISSUE_URL=$(echo "$JSON" | jq -r '.url')
|
||||
echo "title<<EOF" >> $GITHUB_OUTPUT
|
||||
echo "$TITLE" >> $GITHUB_OUTPUT
|
||||
echo "EOF" >> $GITHUB_OUTPUT
|
||||
echo "url=$ISSUE_URL" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Close issue
|
||||
if: steps.pr.outputs.skip != 'true'
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const issueNumber = parseInt('${{ steps.pr.outputs.ISSUE_NUMBER }}', 10);
|
||||
if (!issueNumber || isNaN(issueNumber)) {
|
||||
console.log('No valid issue number, skip');
|
||||
return;
|
||||
}
|
||||
const { data: issue } = await github.rest.issues.get({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber
|
||||
});
|
||||
if (issue.state === 'open') {
|
||||
await github.rest.issues.update({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
state: 'closed'
|
||||
});
|
||||
console.log(`Issue #${issueNumber} closed.`);
|
||||
} else {
|
||||
console.log(`Issue #${issueNumber} already closed.`);
|
||||
}
|
||||
|
||||
- name: Send Telegram notification
|
||||
if: steps.pr.outputs.skip != 'true'
|
||||
env:
|
||||
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
|
||||
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
|
||||
run: |
|
||||
# 与 docker-build 一致:未配置则跳过
|
||||
if [ -z "$TELEGRAM_BOT_TOKEN" ] || [ -z "$TELEGRAM_CHAT_ID" ]; then
|
||||
echo "⚠️ Telegram Bot Token 或 Chat ID 未配置,跳过通知"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
ISSUE_NUM="${{ steps.pr.outputs.ISSUE_NUMBER }}"
|
||||
ISSUE_TITLE="${{ steps.issue.outputs.title }}"
|
||||
ISSUE_URL="${{ steps.issue.outputs.url }}"
|
||||
PR_URL="${{ github.event.pull_request.html_url }}"
|
||||
|
||||
# 与 docker-build 相同的 HTML 消息格式
|
||||
MESSAGE="✅ <b>AI 修复的 Issue 已关闭</b>"$'\n'$'\n'"🔢 <b>Issue:</b> #${ISSUE_NUM} ${ISSUE_TITLE}"$'\n'"📎 <a href=\"${ISSUE_URL}\">查看 Issue</a>"$'\n'"🔗 <a href=\"${PR_URL}\">查看 PR</a>"
|
||||
|
||||
curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$(jq -n \
|
||||
--arg chat_id "$TELEGRAM_CHAT_ID" \
|
||||
--arg text "$MESSAGE" \
|
||||
'{chat_id: $chat_id, text: $text, parse_mode: "HTML", disable_web_page_preview: false}')" > /tmp/telegram_response.json
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
RESPONSE=$(cat /tmp/telegram_response.json)
|
||||
if echo "$RESPONSE" | grep -q '"ok":true'; then
|
||||
echo "✅ Telegram 通知发送成功"
|
||||
else
|
||||
echo "❌ Telegram 通知发送失败: $RESPONSE"
|
||||
exit 0
|
||||
fi
|
||||
else
|
||||
echo "❌ 发送 Telegram 消息时发生错误"
|
||||
exit 0
|
||||
fi
|
||||
@@ -4,39 +4,197 @@ on:
|
||||
release:
|
||||
types:
|
||||
- published # 当通过 GitHub Releases 页面创建 release 时触发
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: '版本号(例如: v1.0.0)'
|
||||
required: false
|
||||
type: string
|
||||
tag_name:
|
||||
description: 'Git Tag 名称(留空则使用 version)'
|
||||
required: false
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
permissions:
|
||||
contents: write # 需要写权限以上传 Assets
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.release.tag_name }} # 使用 release 对应的 tag
|
||||
ref: ${{ github.event.release.tag_name || github.event.inputs.tag_name || github.event.inputs.version || github.ref }}
|
||||
|
||||
- name: Extract version from release
|
||||
- name: Extract version and check if pre-release
|
||||
id: extract_version
|
||||
run: |
|
||||
# 从 release tag 中提取版本号(例如 v1.0.0 -> 1.0.0)
|
||||
TAG_NAME="${{ github.event.release.tag_name }}"
|
||||
if [ -z "$TAG_NAME" ]; then
|
||||
TAG_NAME=${GITHUB_REF#refs/tags/}
|
||||
# 从不同事件源提取版本号
|
||||
if [ "${{ github.event_name }}" = "release" ]; then
|
||||
# Release 事件:从 release tag 中提取
|
||||
TAG_NAME="${{ github.event.release.tag_name }}"
|
||||
IS_PRERELEASE="${{ github.event.release.prerelease }}"
|
||||
else
|
||||
# workflow_dispatch 事件:从输入参数中提取
|
||||
TAG_NAME="${{ github.event.inputs.tag_name }}"
|
||||
if [ -z "$TAG_NAME" ]; then
|
||||
TAG_NAME="${{ github.event.inputs.version }}"
|
||||
fi
|
||||
# 如果仍然为空,尝试从 git ref 中提取
|
||||
if [ -z "$TAG_NAME" ]; then
|
||||
TAG_NAME=${GITHUB_REF#refs/tags/}
|
||||
if [ "$TAG_NAME" = "$GITHUB_REF" ]; then
|
||||
# 不是 tag,尝试从分支名或 commit SHA 获取
|
||||
TAG_NAME=${GITHUB_REF#refs/heads/}
|
||||
if [ "$TAG_NAME" = "$GITHUB_REF" ]; then
|
||||
TAG_NAME="dev-$(date +%Y%m%d-%H%M%S)"
|
||||
echo "⚠️ 未指定版本号,使用临时版本: $TAG_NAME"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
IS_PRERELEASE="false"
|
||||
fi
|
||||
|
||||
# 验证版本号格式:v数字.数字.数字[-后缀](例如 v1.0.0, v2.10.102, v1.0.0-beta)
|
||||
if [[ ! "$TAG_NAME" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.-]+)?$ ]]; then
|
||||
echo "错误: 版本号格式不正确,应为 v数字.数字.数字 或 v数字.数字.数字-后缀 (例如: v1.0.0, v1.0.0-beta)"
|
||||
exit 1
|
||||
if [[ ! "$TAG_NAME" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.-]+)?$ ]] && [[ ! "$TAG_NAME" =~ ^dev- ]]; then
|
||||
echo "⚠️ 警告: 版本号格式不符合标准,但仍将继续构建"
|
||||
echo " 当前版本号: $TAG_NAME"
|
||||
echo " 标准格式应为: v数字.数字.数字 或 v数字.数字.数字-后缀 (例如: v1.0.0, v1.0.0-beta)"
|
||||
fi
|
||||
|
||||
VERSION=${TAG_NAME#v} # 移除 v 前缀
|
||||
VERSION=${TAG_NAME#v} # 移除 v 前缀(如果存在)
|
||||
|
||||
echo "VERSION=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "TAG=$TAG_NAME" >> $GITHUB_OUTPUT
|
||||
echo "Extracted version: $VERSION"
|
||||
echo "Full tag: $TAG_NAME"
|
||||
echo "IS_PRERELEASE=$IS_PRERELEASE" >> $GITHUB_OUTPUT
|
||||
|
||||
if [ "$IS_PRERELEASE" = "true" ]; then
|
||||
echo "📋 这是 Pre-release: $TAG_NAME"
|
||||
else
|
||||
echo "📦 这是正式版本: $TAG_NAME"
|
||||
fi
|
||||
|
||||
- name: Send Telegram notification (build started)
|
||||
# ============ 编译前后端产物 ============
|
||||
- name: Setup JDK 17
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: '17'
|
||||
distribution: 'temurin'
|
||||
|
||||
- name: Build Backend JAR
|
||||
run: |
|
||||
cd backend
|
||||
chmod +x gradlew
|
||||
./gradlew bootJar --no-daemon
|
||||
echo "✅ 后端构建完成"
|
||||
ls -lh build/libs/*.jar
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '18'
|
||||
|
||||
- name: Build Frontend
|
||||
env:
|
||||
VERSION: ${{ steps.extract_version.outputs.VERSION }}
|
||||
GIT_TAG: ${{ steps.extract_version.outputs.TAG }}
|
||||
GITHUB_REPO_URL: https://github.com/WrBug/PolyHermes
|
||||
run: |
|
||||
cd frontend
|
||||
npm ci
|
||||
npm run build
|
||||
echo "✅ 前端构建完成"
|
||||
echo "📦 版本信息: VERSION=${{ steps.extract_version.outputs.VERSION }}, GIT_TAG=${{ steps.extract_version.outputs.TAG }}"
|
||||
du -sh dist/
|
||||
|
||||
# ============ 打包更新包 ============
|
||||
- name: Create Update Package
|
||||
run: |
|
||||
echo "📦 开始打包更新包..."
|
||||
|
||||
# 创建目录结构
|
||||
mkdir -p update-package/backend
|
||||
mkdir -p update-package/frontend
|
||||
|
||||
# 复制后端 JAR
|
||||
cp backend/build/libs/*.jar update-package/backend/polyhermes.jar
|
||||
echo "✅ 后端 JAR 已复制"
|
||||
|
||||
# 复制前端产物
|
||||
cp -r frontend/dist/* update-package/frontend/
|
||||
echo "✅ 前端文件已复制"
|
||||
|
||||
# 创建版本信息文件
|
||||
if [ "${{ github.event_name }}" = "release" ]; then
|
||||
RELEASE_NOTES=$(echo '${{ github.event.release.body }}' | jq -Rs .)
|
||||
else
|
||||
RELEASE_NOTES="\"手动构建 - workflow_dispatch\""
|
||||
fi
|
||||
|
||||
cat > update-package/version.json <<EOF
|
||||
{
|
||||
"version": "${{ steps.extract_version.outputs.VERSION }}",
|
||||
"tag": "${{ steps.extract_version.outputs.TAG }}",
|
||||
"buildTime": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
|
||||
"releaseNotes": ${RELEASE_NOTES}
|
||||
}
|
||||
EOF
|
||||
echo "✅ 版本信息已创建"
|
||||
|
||||
# 打包成 tar.gz
|
||||
cd update-package
|
||||
tar -czf ../polyhermes-${{ steps.extract_version.outputs.TAG }}-update.tar.gz .
|
||||
cd ..
|
||||
|
||||
echo "✅ 打包完成: polyhermes-${{ steps.extract_version.outputs.TAG }}-update.tar.gz"
|
||||
ls -lh polyhermes-*.tar.gz
|
||||
|
||||
- name: Calculate Checksum
|
||||
id: checksum
|
||||
run: |
|
||||
FILE="polyhermes-${{ steps.extract_version.outputs.TAG }}-update.tar.gz"
|
||||
CHECKSUM=$(sha256sum "$FILE" | awk '{print $1}')
|
||||
echo "CHECKSUM=$CHECKSUM" >> $GITHUB_OUTPUT
|
||||
echo "✅ SHA256: $CHECKSUM"
|
||||
echo "$CHECKSUM $FILE" > checksums.txt
|
||||
|
||||
- name: Upload Update Package to Release
|
||||
if: github.event_name == 'release'
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ github.event.release.upload_url }}
|
||||
asset_path: ./polyhermes-${{ steps.extract_version.outputs.TAG }}-update.tar.gz
|
||||
asset_name: polyhermes-${{ steps.extract_version.outputs.TAG }}-update.tar.gz
|
||||
asset_content_type: application/gzip
|
||||
|
||||
- name: Upload Checksums to Release
|
||||
if: github.event_name == 'release'
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ github.event.release.upload_url }}
|
||||
asset_path: ./checksums.txt
|
||||
asset_name: checksums.txt
|
||||
asset_content_type: text/plain
|
||||
|
||||
- name: Upload Update Package as Artifact
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: polyhermes-${{ steps.extract_version.outputs.TAG }}-update
|
||||
path: |
|
||||
polyhermes-${{ steps.extract_version.outputs.TAG }}-update.tar.gz
|
||||
checksums.txt
|
||||
retention-days: 30
|
||||
|
||||
# ============ 发送产物上传成功通知 ============
|
||||
- name: Send Telegram notification (package uploaded)
|
||||
if: steps.extract_version.outputs.IS_PRERELEASE == 'false'
|
||||
env:
|
||||
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
|
||||
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
|
||||
@@ -48,12 +206,15 @@ jobs:
|
||||
fi
|
||||
|
||||
# 获取构建信息
|
||||
VERSION="${{ steps.extract_version.outputs.VERSION }}"
|
||||
TAG="${{ steps.extract_version.outputs.TAG }}"
|
||||
RELEASE_URL="${{ github.event.release.html_url }}"
|
||||
|
||||
# 构建消息内容(仅包含关键信息)
|
||||
MESSAGE="🔨 <b>Docker 镜像构建中</b>"$'\n'$'\n'"📦 <b>版本:</b> ${VERSION}"$'\n'"🏷️ <b>Tag:</b> <code>${TAG}</code>"$'\n'"🔗 <a href=\"${RELEASE_URL}\">查看 Release</a>"
|
||||
if [ "${{ github.event_name }}" = "release" ]; then
|
||||
RELEASE_URL="${{ github.event.release.html_url }}"
|
||||
MESSAGE="✅ <b>PolyHermes Package Built</b>"$'\n'$'\n'"🏷️ <b>Version:</b> <code>${TAG}</code>"$'\n'"🔧 <b>Type:</b> Online Update"$'\n'"🔗 <a href=\"${RELEASE_URL}\">View Release</a>"$'\n'"📍 <b>Update Path:</b> System Management → Overview → Check for Updates"$'\n'$'\n'"🐳 Building Docker image..."
|
||||
else
|
||||
WORKFLOW_URL="https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"
|
||||
MESSAGE="✅ <b>PolyHermes Package Built</b>"$'\n'$'\n'"🏷️ <b>Version:</b> <code>${TAG}</code>"$'\n'"🔧 <b>Type:</b> Online Update"$'\n'"🔗 <a href=\"${WORKFLOW_URL}\">View Workflow</a>"$'\n'$'\n'"🐳 Building Docker image..."
|
||||
fi
|
||||
|
||||
# 发送 Telegram 消息(使用 jq 转义 JSON)
|
||||
curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
|
||||
@@ -70,15 +231,14 @@ jobs:
|
||||
echo "✅ Telegram 通知发送成功"
|
||||
else
|
||||
echo "❌ Telegram 通知发送失败: $RESPONSE"
|
||||
# 通知失败不应该导致整个 job 失败
|
||||
exit 0
|
||||
fi
|
||||
else
|
||||
echo "❌ 发送 Telegram 消息时发生错误"
|
||||
# 通知失败不应该导致整个 job 失败
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# ============ Docker 构建 ============
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
@@ -91,7 +251,24 @@ jobs:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Prepare Docker build context
|
||||
run: |
|
||||
echo "📦 准备 Docker 构建上下文..."
|
||||
# 确保构建产物存在且可访问
|
||||
if [ ! -d "frontend/dist" ]; then
|
||||
echo "❌ 错误:frontend/dist 不存在"
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -d "backend/build/libs" ] || [ -z "$(ls -A backend/build/libs/*.jar 2>/dev/null)" ]; then
|
||||
echo "❌ 错误:backend/build/libs/*.jar 不存在"
|
||||
exit 1
|
||||
fi
|
||||
echo "✅ 构建产物已准备好"
|
||||
ls -lh frontend/dist/ | head -5
|
||||
ls -lh backend/build/libs/*.jar
|
||||
|
||||
- name: Build and push Docker image
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
@@ -101,15 +278,18 @@ jobs:
|
||||
platforms: linux/amd64,linux/arm64
|
||||
tags: |
|
||||
wrbug/polyhermes:${{ steps.extract_version.outputs.TAG }}
|
||||
wrbug/polyhermes:latest
|
||||
${{ steps.extract_version.outputs.IS_PRERELEASE == 'false' && 'wrbug/polyhermes:latest' || '' }}
|
||||
build-args: |
|
||||
BUILD_IN_DOCKER=false
|
||||
VERSION=${{ steps.extract_version.outputs.VERSION }}
|
||||
GIT_TAG=${{ steps.extract_version.outputs.TAG }}
|
||||
GITHUB_REPO_URL=https://github.com/WrBug/PolyHermes
|
||||
cache-from: type=registry,ref=wrbug/polyhermes:latest
|
||||
cache-to: type=inline
|
||||
|
||||
- name: Send Telegram notification
|
||||
|
||||
# ============ 发送 Docker 构建成功通知 ============
|
||||
- name: Send Telegram notification (Docker build completed)
|
||||
if: steps.extract_version.outputs.IS_PRERELEASE == 'false'
|
||||
env:
|
||||
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
|
||||
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
|
||||
@@ -123,13 +303,15 @@ jobs:
|
||||
# 获取构建信息
|
||||
VERSION="${{ steps.extract_version.outputs.VERSION }}"
|
||||
TAG="${{ steps.extract_version.outputs.TAG }}"
|
||||
RELEASE_NAME="${{ github.event.release.name }}"
|
||||
RELEASE_URL="${{ github.event.release.html_url }}"
|
||||
REPO_NAME="${{ github.repository }}"
|
||||
|
||||
# 构建消息内容(仅包含关键信息)
|
||||
DEPLOY_DOC_URL="https://github.com/WrBug/PolyHermes/blob/main/docs/zh/DEPLOYMENT.md"
|
||||
MESSAGE="✅ <b>Docker 镜像构建成功</b>"$'\n'$'\n'"📦 <b>版本:</b> ${VERSION}"$'\n'"🏷️ <b>Tag:</b> <code>${TAG}</code>"$'\n'"🔗 <a href=\"${RELEASE_URL}\">查看 Release</a>"$'\n'"📚 <a href=\"${DEPLOY_DOC_URL}\">Docker 部署文档</a>"
|
||||
|
||||
if [ "${{ github.event_name }}" = "release" ]; then
|
||||
RELEASE_URL="${{ github.event.release.html_url }}"
|
||||
MESSAGE="🐳 <b>Docker Image Built Successfully</b>"$'\n'$'\n'"🏷️ <b>Version:</b> <code>${TAG}</code>"$'\n'"📦 <b>Image:</b> <code>wrbug/polyhermes:${TAG}</code>"$'\n'"🔗 <a href=\"${RELEASE_URL}\">View Release</a>"$'\n'"📚 <a href=\"${DEPLOY_DOC_URL}\">Docker Deployment Guide</a>"
|
||||
else
|
||||
WORKFLOW_URL="https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"
|
||||
MESSAGE="🐳 <b>Docker Image Built Successfully</b>"$'\n'$'\n'"🏷️ <b>Version:</b> <code>${TAG}</code>"$'\n'"📦 <b>Image:</b> <code>wrbug/polyhermes:${TAG}</code>"$'\n'"🔗 <a href=\"${WORKFLOW_URL}\">View Workflow</a>"$'\n'"📚 <a href=\"${DEPLOY_DOC_URL}\">Docker Deployment Guide</a>"
|
||||
fi
|
||||
|
||||
# 发送 Telegram 消息(使用 jq 转义 JSON)
|
||||
curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
|
||||
@@ -146,11 +328,9 @@ jobs:
|
||||
echo "✅ Telegram 通知发送成功"
|
||||
else
|
||||
echo "❌ Telegram 通知发送失败: $RESPONSE"
|
||||
# 构建成功,通知失败不应该导致整个 job 失败
|
||||
exit 0
|
||||
fi
|
||||
else
|
||||
echo "❌ 发送 Telegram 消息时发生错误"
|
||||
# 构建成功,通知失败不应该导致整个 job 失败
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
name: Sync fork
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
# 10:00 Asia/Shanghai every day (GitHub Actions cron uses UTC).
|
||||
- cron: "0 2 * * *"
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
concurrency:
|
||||
group: sync-fork-main
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
sync-main:
|
||||
if: github.repository == 'codychen123/PolyHermes'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Sync fork main from upstream
|
||||
run: |
|
||||
gh repo sync "$GITHUB_REPOSITORY" \
|
||||
--source WrBug/PolyHermes \
|
||||
--branch main
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
@@ -1,103 +0,0 @@
|
||||
name: Telegram Notification on PR Merge
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types:
|
||||
- closed # 当 PR 被关闭(合并或关闭)时触发
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
# 只在 PR 被合并到 main 分支时执行
|
||||
if: github.event.pull_request.merged == true && github.event.pull_request.base.ref == 'main'
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Get PR details
|
||||
id: pr_details
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
PR_NUMBER="${{ github.event.pull_request.number }}"
|
||||
REPO="${{ github.repository }}"
|
||||
|
||||
# 获取 PR 详细信息
|
||||
PR_RESPONSE=$(curl -s -H "Authorization: token ${GITHUB_TOKEN}" \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
"https://api.github.com/repos/${REPO}/pulls/${PR_NUMBER}")
|
||||
|
||||
# 获取 PR 变更的文件列表
|
||||
FILES_RESPONSE=$(curl -s -H "Authorization: token ${GITHUB_TOKEN}" \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
"https://api.github.com/repos/${REPO}/pulls/${PR_NUMBER}/files")
|
||||
|
||||
# 提取 PR 描述(body),保留换行,限制长度
|
||||
PR_BODY=$(echo "$PR_RESPONSE" | jq -r '.body // ""')
|
||||
if [ ${#PR_BODY} -gt 500 ]; then
|
||||
PR_BODY="${PR_BODY:0:500}..."
|
||||
fi
|
||||
|
||||
# 保存到输出变量(使用 base64 编码避免特殊字符问题)
|
||||
echo "pr_body<<EOF" >> $GITHUB_OUTPUT
|
||||
echo "$PR_BODY" >> $GITHUB_OUTPUT
|
||||
echo "EOF" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Send Telegram notification
|
||||
env:
|
||||
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
|
||||
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
|
||||
run: |
|
||||
# 检查 PR 是否被合并(而不是仅关闭)
|
||||
PR_MERGED="${{ github.event.pull_request.merged }}"
|
||||
if [ "$PR_MERGED" != "true" ]; then
|
||||
echo "ℹ️ PR 仅关闭,未合并,跳过通知"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# 检查必要的环境变量
|
||||
# 注意:TELEGRAM_CHAT_ID 可以是个人聊天 ID(正数)或群组 ID(负数,如 -1001234567890)
|
||||
if [ -z "$TELEGRAM_BOT_TOKEN" ] || [ -z "$TELEGRAM_CHAT_ID" ]; then
|
||||
echo "⚠️ Telegram Bot Token 或 Chat ID 未配置,跳过通知"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# 获取 PR 基本信息
|
||||
PR_NUMBER="${{ github.event.pull_request.number }}"
|
||||
PR_TITLE="${{ github.event.pull_request.title }}"
|
||||
PR_URL="${{ github.event.pull_request.html_url }}"
|
||||
PR_MERGE_COMMIT="${{ github.event.pull_request.merge_commit_sha }}"
|
||||
|
||||
# 获取 PR 详细信息
|
||||
PR_BODY="${{ steps.pr_details.outputs.pr_body }}"
|
||||
|
||||
# 转义 PR 标题中的 HTML 特殊字符
|
||||
PR_TITLE_ESCAPED=$(echo "$PR_TITLE" | sed 's/&/\&/g' | sed 's/</\</g' | sed 's/>/\>/g')
|
||||
|
||||
# 构建消息内容(仅包含关键信息)
|
||||
MESSAGE="🚀 <b>main 分支代码更新</b>"$'\n'$'\n'"📝 <b>PR #${PR_NUMBER}:</b> ${PR_TITLE_ESCAPED}"$'\n'"🔗 <a href=\"${PR_URL}\">查看 PR</a>"
|
||||
|
||||
# 发送 Telegram 消息(使用 jq 转义 JSON)
|
||||
curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$(jq -n \
|
||||
--arg chat_id "$TELEGRAM_CHAT_ID" \
|
||||
--arg text "$MESSAGE" \
|
||||
'{chat_id: $chat_id, text: $text, parse_mode: "HTML", disable_web_page_preview: false}')" > /tmp/telegram_response.json
|
||||
|
||||
# 检查发送结果
|
||||
if [ $? -eq 0 ]; then
|
||||
RESPONSE=$(cat /tmp/telegram_response.json)
|
||||
if echo "$RESPONSE" | grep -q '"ok":true'; then
|
||||
echo "✅ Telegram 通知发送成功"
|
||||
else
|
||||
echo "❌ Telegram 通知发送失败: $RESPONSE"
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
echo "❌ 发送 Telegram 消息时发生错误"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
+8
-3
@@ -17,14 +17,16 @@ backend/out/
|
||||
backend/*.log
|
||||
backend/gradle-app.setting
|
||||
backend/.gradle
|
||||
backend/gradle-wrapper.jar
|
||||
|
||||
# 注意:gradle-wrapper.jar 应该被提交,不要忽略
|
||||
# backend/gradle/wrapper/gradle-wrapper.jar
|
||||
polyhub/
|
||||
# Kotlin
|
||||
*.kt.bak
|
||||
*.class
|
||||
|
||||
# Java
|
||||
*.jar
|
||||
!backend/gradle/wrapper/gradle-wrapper.jar # Gradle Wrapper JAR 应该被提交
|
||||
*.war
|
||||
*.ear
|
||||
*.class
|
||||
@@ -93,6 +95,7 @@ coverage/
|
||||
# Test
|
||||
test-results/
|
||||
*.test.log
|
||||
.playwright-cli/
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
@@ -110,4 +113,6 @@ __pycache__/
|
||||
clob-client/
|
||||
builder-relayer-client/
|
||||
landing-page/
|
||||
|
||||
clob-client-v2/
|
||||
settings.local.json
|
||||
.gstack/
|
||||
|
||||
+100
-32
@@ -1,6 +1,12 @@
|
||||
# 多阶段构建:前后端一体化部署
|
||||
# 阶段1:构建前端
|
||||
# 多阶段构建:前后端一体化部署(支持混合编译)
|
||||
# 构建参数:控制是否在 Docker 内编译
|
||||
# - BUILD_IN_DOCKER=true (默认): Docker 内部编译(本地开发)
|
||||
# - BUILD_IN_DOCKER=false: 使用外部产物(GitHub Actions)
|
||||
ARG BUILD_IN_DOCKER=true
|
||||
|
||||
# ==================== 阶段1:构建前端 ====================
|
||||
FROM node:18-alpine AS frontend-build
|
||||
ARG BUILD_IN_DOCKER
|
||||
|
||||
WORKDIR /app/frontend
|
||||
|
||||
@@ -13,19 +19,37 @@ ARG GITHUB_REPO_URL=https://github.com/WrBug/PolyHermes
|
||||
ENV VERSION=${VERSION}
|
||||
ENV GIT_TAG=${GIT_TAG}
|
||||
ENV GITHUB_REPO_URL=${GITHUB_REPO_URL}
|
||||
|
||||
# 复制前端文件
|
||||
# 复制前端文件(先复制 package.json 以利用 Docker 缓存)
|
||||
COPY frontend/package*.json ./
|
||||
RUN npm ci
|
||||
|
||||
# 条件:仅在 Docker 内部编译时安装依赖
|
||||
RUN if [ "$BUILD_IN_DOCKER" = "true" ]; then \
|
||||
npm ci; \
|
||||
fi
|
||||
|
||||
# 复制所有前端源文件
|
||||
COPY frontend/ ./
|
||||
|
||||
# 构建前端(使用相对路径,通过 Nginx 代理)
|
||||
# 版本号会通过环境变量注入到构建产物中
|
||||
RUN npm run build
|
||||
# 条件:仅在 Docker 内部编译时执行构建
|
||||
# 如果 BUILD_IN_DOCKER=false,需要确保构建上下文中存在 frontend/dist
|
||||
# 注意:COPY frontend/ ./ 已经复制了整个 frontend 目录(包括 dist,如果存在)
|
||||
RUN if [ "$BUILD_IN_DOCKER" = "true" ]; then \
|
||||
echo "🔨 Docker 内部编译前端..."; \
|
||||
npm run build; \
|
||||
else \
|
||||
echo "⏭️ 使用外部产物..."; \
|
||||
if [ ! -d "dist" ] || [ -z "$(ls -A dist 2>/dev/null)" ]; then \
|
||||
echo "❌ 错误:BUILD_IN_DOCKER=false 但找不到外部产物 frontend/dist"; \
|
||||
echo " 请先执行: cd frontend && npm install && npm run build"; \
|
||||
exit 1; \
|
||||
else \
|
||||
echo "✅ 找到外部构建的前端产物"; \
|
||||
fi; \
|
||||
fi
|
||||
|
||||
# 阶段2:构建后端
|
||||
# ==================== 阶段2:构建后端 ====================
|
||||
FROM gradle:8.5-jdk17 AS backend-build
|
||||
ARG BUILD_IN_DOCKER
|
||||
|
||||
WORKDIR /app/backend
|
||||
|
||||
@@ -33,60 +57,104 @@ WORKDIR /app/backend
|
||||
COPY backend/build.gradle.kts backend/settings.gradle.kts ./
|
||||
COPY backend/gradle ./gradle
|
||||
|
||||
# 下载依赖(利用 Docker 缓存)
|
||||
RUN gradle dependencies --no-daemon || true
|
||||
# 条件:仅在 Docker 内部编译时下载依赖
|
||||
RUN if [ "$BUILD_IN_DOCKER" = "true" ]; then \
|
||||
gradle dependencies --no-daemon || true; \
|
||||
fi
|
||||
|
||||
# 复制源代码
|
||||
COPY backend/src ./src
|
||||
|
||||
# 构建应用
|
||||
RUN gradle bootJar --no-daemon
|
||||
# 尝试复制外部构建的 JAR(如果存在)
|
||||
# 注意:COPY 指令如果源不存在会失败
|
||||
# GitHub Actions 使用 BUILD_IN_DOCKER=false,会先构建产物,所以 backend/build 应该存在
|
||||
# 本地开发使用 BUILD_IN_DOCKER=true,会在 Docker 内编译,所以 backend/build 可能不存在
|
||||
# 解决方案:先复制整个 backend 目录(包括 build,如果存在),然后只使用需要的部分
|
||||
# 使用 .dockerignore 确保不会复制不需要的文件(如 .gradle、out、bin 等)
|
||||
COPY backend/build ./build-external
|
||||
|
||||
# 阶段3:运行环境
|
||||
# 处理外部构建的 JAR(如果存在)
|
||||
RUN if [ -d "build-external/libs" ] && [ -n "$(ls -A build-external/libs/*.jar 2>/dev/null)" ]; then \
|
||||
echo "📦 找到外部构建的后端产物,复制到 build/libs..."; \
|
||||
mkdir -p build/libs; \
|
||||
cp build-external/libs/*.jar build/libs/; \
|
||||
rm -rf build-external; \
|
||||
else \
|
||||
echo "⏭️ 未找到外部构建的 JAR,将在 Docker 内编译"; \
|
||||
rm -rf build-external; \
|
||||
mkdir -p build/libs; \
|
||||
fi
|
||||
|
||||
# 条件:仅在 Docker 内部编译时执行构建(会覆盖外部产物)
|
||||
RUN if [ "$BUILD_IN_DOCKER" = "true" ]; then \
|
||||
echo "🔨 Docker 内部编译后端..."; \
|
||||
gradle bootJar --no-daemon; \
|
||||
else \
|
||||
echo "⏭️ 使用外部产物"; \
|
||||
if [ -z "$(ls -A build/libs/*.jar 2>/dev/null)" ]; then \
|
||||
echo "❌ 错误:BUILD_IN_DOCKER=false 但找不到外部产物 backend/build/libs/*.jar"; \
|
||||
echo " 请先执行: cd backend && ./gradlew bootJar"; \
|
||||
exit 1; \
|
||||
else \
|
||||
echo "✅ 使用外部构建的后端产物"; \
|
||||
fi; \
|
||||
fi
|
||||
|
||||
# 统一选出可执行 JAR,避免 *-plain.jar 和 bootJar 同时存在导致最终 COPY 匹配多个文件
|
||||
RUN set -e; \
|
||||
JAR="$(find build/libs -maxdepth 1 -type f -name '*.jar' ! -name '*-plain.jar' | head -n 1)"; \
|
||||
if [ -z "$JAR" ]; then \
|
||||
echo "❌ 错误:找不到可执行 JAR(已排除 *-plain.jar)"; \
|
||||
exit 1; \
|
||||
fi; \
|
||||
if [ "$JAR" != "build/libs/app.jar" ]; then \
|
||||
cp "$JAR" build/libs/app.jar; \
|
||||
fi
|
||||
|
||||
# ==================== 阶段3:运行环境 ====================
|
||||
FROM eclipse-temurin:17-jre-jammy
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# 安装 Nginx 和必要的工具
|
||||
# 安装 Nginx、Python 和必要的工具
|
||||
RUN apt-get update && \
|
||||
apt-get install -y nginx curl && \
|
||||
apt-get install -y nginx curl tzdata jq python3 python3-flask python3-requests && \
|
||||
rm -rf /var/lib/apt/lists/* && \
|
||||
rm -rf /etc/nginx/sites-enabled/default
|
||||
|
||||
# 从构建阶段复制文件
|
||||
# 当 BUILD_IN_DOCKER=false 时,构建阶段已经复制了外部产物
|
||||
COPY --from=frontend-build /app/frontend/dist /usr/share/nginx/html
|
||||
COPY --from=backend-build /app/backend/build/libs/*.jar app.jar
|
||||
COPY --from=backend-build /app/backend/build/libs/app.jar app.jar
|
||||
|
||||
# 复制 Nginx 配置
|
||||
COPY docker/nginx.conf /etc/nginx/nginx.conf
|
||||
|
||||
# 创建启动脚本
|
||||
# 创建更新服务相关目录和脚本
|
||||
RUN mkdir -p /app/updates /app/backups /var/log/polyhermes
|
||||
COPY docker/update-service.py /app/update-service.py
|
||||
COPY docker/start.sh /app/start.sh
|
||||
RUN chmod +x /app/start.sh
|
||||
|
||||
# 创建非 root 用户(用于运行后端应用)
|
||||
# 记录初始版本(从构建参数)
|
||||
ARG VERSION=dev
|
||||
ARG GIT_TAG=dev
|
||||
RUN echo "{\"version\":\"${VERSION}\",\"tag\":\"${GIT_TAG}\",\"buildTime\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}" > /app/version.json
|
||||
|
||||
# 创建非 root 用户
|
||||
RUN useradd -m -u 1000 appuser
|
||||
|
||||
# 设置目录权限(Nginx 以 root 运行,后端应用以 appuser 运行)
|
||||
# 设置目录权限
|
||||
RUN mkdir -p /var/log/nginx /var/lib/nginx /var/cache/nginx /var/run && \
|
||||
chown -R appuser:appuser /app && \
|
||||
chown -R root:root /usr/share/nginx/html && \
|
||||
chown -R root:root /var/log/nginx && \
|
||||
chown -R root:root /var/lib/nginx && \
|
||||
chown -R root:root /var/cache/nginx && \
|
||||
chown -R root:root /etc/nginx && \
|
||||
chown -R root:root /var/run
|
||||
|
||||
# 保持 root 用户(Nginx 需要 root 权限绑定 80 端口)
|
||||
# USER appuser
|
||||
chown -R root:root /usr/share/nginx/html /var/log/nginx /var/lib/nginx /var/cache/nginx /etc/nginx /var/run
|
||||
|
||||
# 暴露端口
|
||||
EXPOSE 80
|
||||
|
||||
# 健康检查
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \
|
||||
CMD curl -f http://localhost/api/health || exit 1
|
||||
CMD curl -f http://localhost/api/system/health || exit 1
|
||||
|
||||
# 启动服务(同时启动 Nginx 和后端)
|
||||
# 启动服务
|
||||
ENTRYPOINT ["/app/start.sh"]
|
||||
|
||||
|
||||
@@ -116,6 +116,7 @@
|
||||
- **API 健康检查**:实时监控 Polymarket API 的健康状态
|
||||
- **用户管理**:管理系统用户,支持添加、编辑、删除用户
|
||||
- **公告管理**:查看系统公告和更新信息
|
||||
- **动态更新**:支持在线更新系统版本,无需重新部署容器
|
||||
|
||||
### 🚀 技术特性
|
||||
|
||||
@@ -164,6 +165,29 @@
|
||||
|
||||
**部署步骤**:
|
||||
|
||||
#### ⚡ 一键安装(最快,推荐新用户)
|
||||
|
||||
**使用 curl(推荐):**
|
||||
```bash
|
||||
mkdir -p ~/polyhermes && cd ~/polyhermes && curl -fsSL https://raw.githubusercontent.com/WrBug/PolyHermes/main/deploy-interactive.sh -o deploy.sh && chmod +x deploy.sh && ./deploy.sh
|
||||
```
|
||||
|
||||
**使用 wget:**
|
||||
```bash
|
||||
mkdir -p ~/polyhermes && cd ~/polyhermes && wget -O deploy.sh https://raw.githubusercontent.com/WrBug/PolyHermes/main/deploy-interactive.sh && chmod +x deploy.sh && ./deploy.sh
|
||||
```
|
||||
|
||||
这个命令会自动:
|
||||
- 📁 创建专用工作目录 `~/polyhermes`
|
||||
- ✅ 自动检查 Docker 环境
|
||||
- ⚙️ 交互式配置所有参数(支持回车使用默认值)
|
||||
- 🔐 自动生成安全的随机密钥
|
||||
- 🚀 自动下载最新镜像并部署
|
||||
|
||||
---
|
||||
|
||||
#### 📋 其他部署方式
|
||||
|
||||
1. **使用 Docker Hub 镜像(推荐,生产环境首选)**
|
||||
|
||||
**方式 1:独立部署(无需 clone 代码,推荐)**
|
||||
@@ -397,6 +421,9 @@ cd frontend
|
||||
- [开发文档](docs/zh/DEVELOPMENT.md) - 开发指南
|
||||
- [跟单系统需求文档](docs/zh/copy-trading-requirements.md) - 后端 API 接口文档
|
||||
- [前端需求文档](docs/zh/copy-trading-frontend-requirements.md) - 前端功能文档
|
||||
- [跟单亏损诊断与风险安全带](docs/zh/copy-trading-risk-seatbelt.md) - PnL 诊断、安全带确认流程和运维排查命令
|
||||
- [Leader Research Agent](docs/zh/leader-research-agent.md) - 自动发现、纸跟、评分和禁用试跟审批说明
|
||||
- [动态更新文档](docs/zh/DYNAMIC_UPDATE.md) - 动态更新功能说明
|
||||
|
||||
### 🤝 贡献指南
|
||||
|
||||
|
||||
+24
-1
@@ -164,6 +164,29 @@ Deploy both frontend and backend together in a single Docker container, using Ng
|
||||
|
||||
**Deployment Steps**:
|
||||
|
||||
#### ⚡ One-Liner Installation (Fastest, Recommended for New Users)
|
||||
|
||||
**Using curl (Recommended):**
|
||||
```bash
|
||||
mkdir -p ~/polyhermes && cd ~/polyhermes && curl -fsSL https://raw.githubusercontent.com/WrBug/PolyHermes/main/deploy-interactive.sh -o deploy.sh && chmod +x deploy.sh && ./deploy.sh
|
||||
```
|
||||
|
||||
**Using wget:**
|
||||
```bash
|
||||
mkdir -p ~/polyhermes && cd ~/polyhermes && wget -O deploy.sh https://raw.githubusercontent.com/WrBug/PolyHermes/main/deploy-interactive.sh && chmod +x deploy.sh && ./deploy.sh
|
||||
```
|
||||
|
||||
This command will automatically:
|
||||
- 📁 Create dedicated working directory `~/polyhermes`
|
||||
- ✅ Automatically check Docker environment
|
||||
- ⚙️ Interactive configuration for all parameters (supports pressing Enter for defaults)
|
||||
- 🔐 Automatically generate secure random keys
|
||||
- 🚀 Automatically download latest images and deploy
|
||||
|
||||
---
|
||||
|
||||
#### 📋 Alternative Deployment Methods
|
||||
|
||||
1. **Using Docker Hub Images (Recommended, Production First Choice)**
|
||||
|
||||
**Method 1: Standalone Deployment (No code clone required, Recommended)**
|
||||
@@ -397,6 +420,7 @@ The development documentation includes:
|
||||
- [Development Documentation](docs/en/DEVELOPMENT.md) - Development guide
|
||||
- [Copy Trading System Requirements](docs/zh/copy-trading-requirements.md) - Backend API documentation (Chinese only)
|
||||
- [Frontend Requirements](docs/zh/copy-trading-frontend-requirements.md) - Frontend feature documentation (Chinese only)
|
||||
- [Leader Research Agent](docs/zh/leader-research-agent.md) - Auto-discovery, paper trading, scoring, and disabled-trial approval guide (Chinese only)
|
||||
|
||||
### 🤝 Contributing
|
||||
|
||||
@@ -444,4 +468,3 @@ Thanks to all developers and users who have contributed to this project!
|
||||
---
|
||||
|
||||
**⭐ If this project helps you, please give it a Star!**
|
||||
|
||||
|
||||
-556
@@ -1,556 +0,0 @@
|
||||
# v1.1.7
|
||||
|
||||
## 🚀 主要功能
|
||||
|
||||
### 💰 Polymarket Maker Rebates Program 费率支持
|
||||
|
||||
- **新增费率查询 API 接口** (`getFeeRate`)
|
||||
- 支持动态查询 Maker Rebates Program 费率
|
||||
- 修正 API 返回字段名:使用 `base_fee` 而非 `fee_rate_bps`(与 TypeScript clob-client 一致)
|
||||
|
||||
- **动态费率获取**
|
||||
- 在所有订单创建处动态获取费率:
|
||||
* 跟单买入订单 (`processBuyTrade`)
|
||||
* 跟单卖出订单 (`matchSellOrder`)
|
||||
* 账户卖出订单 (`sellPosition`)
|
||||
- 费率获取失败时降级到默认值 "0",确保系统可用性
|
||||
- 添加详细的日志记录,便于监控和调试
|
||||
|
||||
- **参考文档**: https://docs.polymarket.com/developers/market-makers/maker-rebates-program
|
||||
|
||||
### 🔧 Docker 部署优化
|
||||
|
||||
- **日志级别环境变量支持**
|
||||
- 在 `application.properties` 中支持通过 `LOG_LEVEL_ROOT` 和 `LOG_LEVEL_APP` 环境变量配置日志级别
|
||||
- 在 `docker-compose.yml` 和 `docker-compose.prod.yml` 中添加日志级别环境变量配置
|
||||
- 在 `deploy.sh` 的 `.env` 模板中添加日志级别配置说明
|
||||
- 支持通过环境变量动态配置日志级别,无需修改配置文件
|
||||
- 默认值:`root=INFO`, `app=DEBUG`
|
||||
|
||||
## 🐛 Bug 修复
|
||||
|
||||
### 修复市场条件查询的 RPC 调用错误
|
||||
|
||||
- **问题**:使用错误的函数签名 `conditions(bytes32)` 导致 RPC 调用失败(execution reverted)
|
||||
- **修复**:
|
||||
- 将错误的 `conditions(bytes32)` 函数调用改为正确的 `getOutcomeSlotCount(bytes32)` 和 `payoutDenominator(bytes32)` 函数调用
|
||||
- 修复 `BlockchainService.getCondition` 方法,使用正确的 ConditionalTokens 合约函数签名
|
||||
- 改进 `MarketPriceService` 的错误处理:当链上查询出现 RPC 错误时,降级到 CLOB API 或 Gamma API 查询,而不是直接抛出异常,提高容错性
|
||||
|
||||
### 修复 RPC 错误时误创建自动卖出记录的问题
|
||||
|
||||
- **问题**:当链上查询市场条件出现 RPC 错误(execution reverted)时,系统会误判为市场已卖出,创建错误的自动卖出记录
|
||||
- **修复**:
|
||||
- 修改 `getPriceFromChainCondition` 返回 `Pair<BigDecimal?, Boolean>`,第二个值表示是否发生 RPC 错误
|
||||
- 在 `getCurrentMarketPrice` 中检测到 RPC 错误时抛出异常,`PositionCheckService` 会捕获并跳过该市场的处理
|
||||
- 避免在市场不存在或尚未创建时误判为已卖出
|
||||
|
||||
## 📝 文档更新
|
||||
|
||||
### 更新 Telegram 群链接
|
||||
|
||||
- 将所有 Telegram 群链接统一更新为 `t.me/polyhermes`
|
||||
- 更新了以下文件:
|
||||
- `frontend/src/components/Layout.tsx` - 桌面端和移动端导航链接
|
||||
- `RELEASE.md` - 相关链接
|
||||
- `README.md` 和 `README_EN.md` - 相关链接部分
|
||||
|
||||
### 添加 Docker 版本徽章
|
||||
|
||||
- 在 README 和 README_EN.md 中添加动态 Docker 版本徽章
|
||||
- 使用 shields.io 自动显示 Docker Hub 上 `wrbug/polyhermes` 镜像的最新版本
|
||||
- 版本信息自动更新,无需手动维护
|
||||
|
||||
## 📊 变更统计
|
||||
|
||||
- **提交数量**:5 个提交
|
||||
- **文件变更**:16 个文件
|
||||
- **代码变更**:+205 行 / -886 行(净减少 681 行)
|
||||
|
||||
### 详细文件变更
|
||||
|
||||
**后端变更**:
|
||||
- `PolymarketClobApi.kt` - 添加费率查询接口(+25 行)
|
||||
- `AccountService.kt` - 在订单创建处添加动态费率获取(+11 行)
|
||||
- `BlockchainService.kt` - 修复市场条件查询的 RPC 调用错误(+84 行)
|
||||
- `MarketPriceService.kt` - 改进错误处理,支持降级到其他数据源(+36 行)
|
||||
- `PolymarketClobService.kt` - 添加费率查询服务(+32 行)
|
||||
- `CopyOrderTrackingService.kt` - 在跟单订单创建处添加费率获取(+34 行)
|
||||
- `PositionCheckService.kt` - 修复 RPC 错误处理逻辑(+2 行)
|
||||
- `application.properties` - 添加日志级别环境变量支持(+6 行)
|
||||
|
||||
**前端变更**:
|
||||
- `Layout.tsx` - 更新 Telegram 群链接(+4 行)
|
||||
|
||||
**配置文件变更**:
|
||||
- `docker-compose.yml` - 添加日志级别环境变量(+4 行)
|
||||
- `docker-compose.prod.yml` - 添加日志级别环境变量(+4 行)
|
||||
- `deploy.sh` - 添加日志级别配置说明(+5 行)
|
||||
|
||||
**文档变更**:
|
||||
- `README.md` - 更新 Telegram 链接,添加 Docker 版本徽章(+2 行)
|
||||
- `README_EN.md` - 更新 Telegram 链接,添加 Docker 版本徽章(+2 行)
|
||||
- `RELEASE.md` - 更新 Telegram 链接(+4 行)
|
||||
- `docs/zh/smart-money-analysis.md` - 删除文档(-836 行)
|
||||
|
||||
## 🔧 技术细节
|
||||
|
||||
### API 变更
|
||||
|
||||
- **新增接口**:
|
||||
- `POST /api/clob/fee-rate` - 获取 Maker Rebates Program 费率(内部使用)
|
||||
- **无移除接口**
|
||||
|
||||
### 环境变量变更
|
||||
|
||||
- **新增环境变量**:
|
||||
- `LOG_LEVEL_ROOT` - Root 日志级别(默认:INFO)
|
||||
- `LOG_LEVEL_APP` - 应用日志级别(默认:DEBUG)
|
||||
|
||||
### 合约调用修复
|
||||
|
||||
- **修复的函数调用**:
|
||||
- 从 `conditions(bytes32)` 改为 `getOutcomeSlotCount(bytes32)` 和 `payoutDenominator(bytes32)`
|
||||
- 使用正确的 ConditionalTokens 合约函数签名
|
||||
- 参考:https://polygonscan.com/address/0x4d97dcd97ec945f40cf65f87097ace5ea0476045#code
|
||||
|
||||
## 📝 升级说明
|
||||
|
||||
### 数据库升级
|
||||
|
||||
- **无需数据库迁移**:本次更新不涉及数据库结构变更
|
||||
|
||||
### 配置更新
|
||||
|
||||
- **可选配置**:新增日志级别环境变量,如不配置将使用默认值
|
||||
- `LOG_LEVEL_ROOT=INFO`(默认)
|
||||
- `LOG_LEVEL_APP=DEBUG`(默认)
|
||||
|
||||
### Docker 部署
|
||||
|
||||
- **推荐更新**:使用 Docker Hub 镜像部署的用户,建议更新到最新版本
|
||||
```bash
|
||||
docker pull wrbug/polyhermes:latest
|
||||
docker-compose -f docker-compose.prod.yml up -d
|
||||
```
|
||||
|
||||
## 🔗 相关链接
|
||||
|
||||
- **GitHub 仓库**:https://github.com/WrBug/PolyHermes
|
||||
- **Twitter**:@polyhermes
|
||||
- **Telegram 群组**:https://t.me/polyhermes
|
||||
|
||||
---
|
||||
|
||||
**发布日期**:2026-01-07
|
||||
|
||||
---
|
||||
|
||||
# v1.1.5
|
||||
|
||||
## 🔧 功能优化与改进
|
||||
|
||||
### 前端优化
|
||||
|
||||
#### 优化 InputNumber 输入框格式化
|
||||
- 优化数值输入框的格式化逻辑,修正正则表达式以正确处理整数显示
|
||||
- 更新所有相关 InputNumber 组件的 formatter 函数,确保显示准确性
|
||||
- 影响的组件:CopyTradingAdd、CopyTradingEdit、EditModal、TemplateAdd、TemplateEdit、TemplateList
|
||||
- 影响范围:跟单配置、模板配置中的所有数值输入框
|
||||
|
||||
#### 优化数字显示格式
|
||||
- 添加 `formatNumber` 工具函数,自动去除小数尾随零(如 100.00 → 100)
|
||||
- 统一所有数值输入框的显示格式,提升用户体验
|
||||
|
||||
### 后端优化
|
||||
|
||||
#### 优化按比例跟单金额计算逻辑
|
||||
- 优化按比例计算的订单金额处理,使用向上取整确保满足最小限制要求
|
||||
- 对订单金额进行向上取整处理(保留 2 位小数精度)
|
||||
- 自动调整订单数量以满足最小限制要求
|
||||
- 使用 `RoundingMode.CEILING` 确保金额满足最小限制
|
||||
- 影响范围:按比例跟单的订单创建逻辑
|
||||
- 技术细节:
|
||||
- 扩展 `BigDecimal.div()` 扩展函数,支持指定精度和舍入模式
|
||||
- 在 `CopyOrderTrackingService` 中优化金额计算和验证逻辑
|
||||
|
||||
#### 增强 copyRatio 精度支持
|
||||
- 将 copyRatio 字段精度从 DECIMAL(10,2) 增加到 DECIMAL(20,8)
|
||||
- 支持更精确的跟单比例设置(最小 0.01%,最大 10000%)
|
||||
- 影响的实体:CopyTrading、CopyTradingTemplate
|
||||
- 数据库迁移:新增 V18 迁移脚本,自动升级数据库字段精度
|
||||
|
||||
## 🔧 功能优化
|
||||
|
||||
### 移除刷新代理钱包接口
|
||||
- **移除接口**:
|
||||
- `POST /api/accounts/refresh-proxy` - 刷新单个账户的代理地址
|
||||
- `POST /api/accounts/refresh-all-proxies` - 刷新所有账户的代理地址
|
||||
- **原因**:代理地址应在账户导入时自动计算,无需手动刷新
|
||||
- **影响范围**:AccountController、AccountService
|
||||
- **向后兼容性**:这些接口已不再使用,移除不影响现有功能
|
||||
|
||||
### 前端跟单比例配置优化
|
||||
- **最小比例**:从 10% 降低到 0.01%,支持更灵活的跟单比例设置
|
||||
- **最大比例**:增加到 10000%,满足大比例跟单需求
|
||||
- **显示格式**:比例模式显示为百分比(如 "100%" 而不是 "1x")
|
||||
- **输入验证**:增强输入验证,确保比例在合理范围内
|
||||
|
||||
## 📊 变更统计
|
||||
|
||||
- **提交数量**:3 个提交
|
||||
- **文件变更**:15 个文件
|
||||
- **代码变更**:+575 行 / -194 行(净增加 381 行)
|
||||
|
||||
### 详细文件变更
|
||||
|
||||
**后端变更**:
|
||||
- `AccountController.kt` - 移除刷新代理钱包接口(-59 行)
|
||||
- `AccountService.kt` - 移除刷新代理钱包方法(-79 行)
|
||||
- `CopyTrading.kt` - 增加 copyRatio 精度
|
||||
- `CopyTradingTemplate.kt` - 增加 copyRatio 精度
|
||||
- `CopyOrderTrackingService.kt` - 优化按比例跟单金额计算逻辑(+45 行)
|
||||
- `MathExt.kt` - 扩展 div 函数支持精度和舍入模式(+20 行)
|
||||
- `V18__increase_copy_ratio_precision.sql` - 数据库迁移脚本(+14 行)
|
||||
|
||||
**前端变更**:
|
||||
- `CopyTradingAdd.tsx` - 优化 formatter、优化比例配置(+106 行)
|
||||
- `CopyTradingEdit.tsx` - 优化 formatter、优化比例配置(+106 行)
|
||||
- `CopyTradingList.tsx` - 优化比例显示格式
|
||||
- `CopyTradingOrders/EditModal.tsx` - 优化 formatter、优化比例配置(+106 行)
|
||||
- `TemplateAdd.tsx` - 优化 formatter、优化比例配置(+65 行)
|
||||
- `TemplateEdit.tsx` - 优化 formatter、优化比例配置(+65 行)
|
||||
- `TemplateList.tsx` - 优化 formatter、优化比例配置(+65 行)
|
||||
- `utils/index.ts` - 添加 formatNumber 工具函数(+31 行)
|
||||
|
||||
## 🔧 技术细节
|
||||
|
||||
### 数据库变更
|
||||
- **迁移脚本**:`V18__increase_copy_ratio_precision.sql`
|
||||
- **变更内容**:
|
||||
- `copy_trading.copy_ratio`: DECIMAL(10,2) → DECIMAL(20,8)
|
||||
- `copy_trading_templates.copy_ratio`: DECIMAL(10,2) → DECIMAL(20,8)
|
||||
- **自动执行**:升级时会自动执行迁移脚本
|
||||
|
||||
### API 变更
|
||||
- **移除接口**:
|
||||
- `POST /api/accounts/refresh-proxy`
|
||||
- `POST /api/accounts/refresh-all-proxies`
|
||||
- **无新增接口**
|
||||
|
||||
### 前端变更
|
||||
- **工具函数**:新增 `formatNumber()` 函数,用于格式化数字显示
|
||||
- **组件更新**:所有数值输入框统一使用新的 formatter 函数
|
||||
- **显示优化**:跟单模式的比例显示为百分比格式
|
||||
|
||||
## 📝 升级说明
|
||||
|
||||
### 数据库升级
|
||||
本次版本包含数据库迁移脚本,升级时会自动执行:
|
||||
- 自动增加 `copy_ratio` 字段的精度
|
||||
- 现有数据不受影响,精度升级是向后兼容的
|
||||
|
||||
### 配置变更
|
||||
无需额外配置变更。
|
||||
|
||||
### 兼容性
|
||||
- **向后兼容**:所有变更都是向后兼容的
|
||||
- **API 兼容**:移除的接口不影响现有功能(这些接口已不再使用)
|
||||
- **数据兼容**:数据库字段精度升级不会影响现有数据
|
||||
|
||||
## 🎯 主要改进
|
||||
|
||||
1. **优化输入框格式化**:优化数值输入框的显示逻辑
|
||||
2. **优化跟单金额计算**:确保按比例跟单的金额满足最小限制要求
|
||||
3. **提升精度支持**:支持更精确的跟单比例设置(0.01% - 10000%)
|
||||
4. **代码清理**:移除不再使用的刷新代理钱包接口
|
||||
|
||||
## 🔗 相关链接
|
||||
|
||||
- [GitHub Tag](https://github.com/WrBug/PolyHermes/releases/tag/v1.1.5)
|
||||
- [变更日志](https://github.com/WrBug/PolyHermes/compare/v1.1.4...v1.1.5)
|
||||
|
||||
## 🙏 致谢
|
||||
|
||||
感谢所有贡献者和测试用户的反馈与支持!
|
||||
|
||||
---
|
||||
|
||||
# v1.1.2
|
||||
|
||||
## 🚀 主要功能
|
||||
|
||||
### 🐛 修复内存泄漏问题
|
||||
- 修复 Retrofit/OkHttpClient 实例重复创建导致的内存泄漏问题
|
||||
- 为不需要认证的 API 创建共享的 OkHttpClient 实例(Gamma API、Data API、GitHub API 等)
|
||||
- 带认证的 CLOB API 按钱包地址缓存(每个账户一个客户端)
|
||||
- RPC API 按 RPC URL 缓存,Builder Relayer API 按 relayerUrl 缓存
|
||||
- 添加 `@PreDestroy` 方法清理缓存,确保资源正确释放
|
||||
- **效果**:内存占用从运行几小时后从 400MB 涨到 1GB+ 变为保持稳定,大幅减少内存占用
|
||||
|
||||
### 📊 市场价格服务优化
|
||||
- 移除降级查询逻辑,仅保留链上 RPC 查询和 CLOB 订单簿查询
|
||||
- 移除 CLOB Trades、Gamma Market Status、Gamma Market Price 查询逻辑
|
||||
- 如果所有数据源都失败,抛出明确的异常信息
|
||||
- 价格截位到 4 位小数(向下截断,不四舍五入)
|
||||
- 简化代码逻辑,提高查询效率和准确性
|
||||
|
||||
### 🔧 代码架构优化
|
||||
- 统一 Gson 使用,改为依赖注入方式
|
||||
- 在 `GsonConfig` 中统一配置 Gson Bean(lenient 模式)
|
||||
- 所有 Service 类通过构造函数注入 Gson 实例
|
||||
- 移除所有 `GsonConverterFactory.create()` 无参调用,统一使用注入的 Gson
|
||||
- 提高代码一致性和可维护性
|
||||
|
||||
### 🗑️ 功能清理
|
||||
- 移除下单失败存储数据库的功能
|
||||
- 删除 `FailedTrade` 实体类和 `FailedTradeRepository`
|
||||
- 从 `CopyOrderTrackingService` 中移除失败交易存储逻辑
|
||||
- 创建 Flyway migration V16 删除 `failed_trade` 表
|
||||
- 下单失败时仅记录日志,不再存储到数据库,简化数据模型
|
||||
|
||||
### 🚀 部署优化
|
||||
- 自动使用当前分支名作为 Docker 版本号
|
||||
- 分支名中的 `/` 自动替换为 `-`(Docker tag 不支持 `/)
|
||||
- `docker-compose.yml` 启用 build args,从环境变量读取版本号
|
||||
- 前端页面将显示当前分支名作为版本号
|
||||
- 如果没有 Git 仓库或获取失败,使用默认值 `dev`
|
||||
|
||||
## 🐛 Bug 修复
|
||||
|
||||
### 修复 Flyway Migration 问题
|
||||
- 恢复 V1 migration 文件,避免 checksum 不匹配
|
||||
- 保持 `V1__init_database.sql` 的原有内容不变
|
||||
- `failed_trade` 表的删除通过 V16 migration 处理
|
||||
- 确保已有数据库的 migration checksum 保持一致
|
||||
|
||||
### 修复前端编译错误
|
||||
- 修复 `PositionList.tsx` 中引用不存在的 `bestBid` 属性导致的编译错误
|
||||
- 使用 `currentPrice` 替代 `bestBid`,确保前端代码可以正常编译
|
||||
|
||||
## 📚 文档更新
|
||||
|
||||
- 新增智能资金分析文档(`docs/zh/smart-money-analysis.md`)
|
||||
- 详细说明智能资金分析功能的使用方法和策略
|
||||
|
||||
## 🔧 技术改进
|
||||
|
||||
- 优化 `RetrofitFactory`,实现客户端实例缓存和复用
|
||||
- 优化 `CopyOrderTrackingService`,移除失败交易相关逻辑
|
||||
- 优化 `OrderStatusUpdateService`,增强订单状态更新功能
|
||||
- 优化 `TelegramNotificationService`,改进通知逻辑
|
||||
- 优化 `PositionCheckService`,简化代码结构
|
||||
- 优化 `PolymarketClobService`,改进 API 调用逻辑
|
||||
|
||||
## 📦 数据库变更
|
||||
|
||||
- 删除 `failed_trade` 表(Migration: V16)
|
||||
|
||||
## 🔗 相关链接
|
||||
|
||||
- **GitHub Release**: https://github.com/WrBug/PolyHermes/releases/tag/v1.1.2
|
||||
- **完整更新日志**: https://github.com/WrBug/PolyHermes/compare/v1.1.1...v1.1.2
|
||||
- **Docker Hub**: https://hub.docker.com/r/wrbug/polyhermes
|
||||
|
||||
## 📊 统计信息
|
||||
|
||||
- **文件变更**: 29 个文件
|
||||
- **代码变更**: +1597 行 / -678 行
|
||||
- **主要提交**: 8 个提交
|
||||
|
||||
## ⚠️ 重要提醒
|
||||
|
||||
**请务必使用官方 Docker 镜像源,避免财产损失!**
|
||||
|
||||
### ✅ 官方 Docker Hub 镜像
|
||||
|
||||
**官方镜像地址**:`wrbug/polyhermes`
|
||||
|
||||
```bash
|
||||
# ✅ 正确:使用官方镜像
|
||||
docker pull wrbug/polyhermes:v1.1.2
|
||||
|
||||
# ❌ 错误:不要使用其他来源的镜像
|
||||
# 任何非官方来源的镜像都可能包含恶意代码,导致您的私钥和资产被盗
|
||||
```
|
||||
|
||||
### 🔗 官方渠道
|
||||
|
||||
请通过以下**唯一官方渠道**获取 PolyHermes:
|
||||
|
||||
* **GitHub 仓库**:https://github.com/WrBug/PolyHermes
|
||||
* **Twitter**:@polyhermes
|
||||
* **Telegram 群组**:https://t.me/polyhermes
|
||||
|
||||
---
|
||||
|
||||
**⭐ 如果这个项目对您有帮助,请给个 Star 支持一下!**
|
||||
|
||||
---
|
||||
|
||||
# v1.1.1
|
||||
|
||||
## 🚀 主要功能
|
||||
|
||||
### 🔗 链上 WebSocket 监听优化
|
||||
- 创建 `UnifiedOnChainWsService` 统一管理 WebSocket 连接,所有服务共享同一个连接
|
||||
- 创建 `OnChainWsUtils` 工具类,提取公共的链上 WebSocket 相关功能
|
||||
- 创建 `AccountOnChainMonitorService` 监听账户链上卖出和赎回事件
|
||||
- 优化 `OnChainWsService`,复用公共代码,减少代码重复
|
||||
- 支持通过链上 WebSocket 实时监听账户的卖出和赎回交易,自动更新订单状态
|
||||
|
||||
### 📊 市场状态查询优化
|
||||
- 优化市场结算状态查询,优先使用链上查询 `ConditionalTokens.getCondition`
|
||||
- 如果链上查询失败,自动降级到 Gamma API 查询
|
||||
- 提供更实时和准确的市场结算结果
|
||||
|
||||
### 🔕 自动订单通知优化
|
||||
- 自动生成的订单(AUTO_、AUTO_FIFO_、AUTO_WS_ 前缀)不再发送 Telegram 通知
|
||||
- 优化 `OrderStatusUpdateService`,跳过自动生成订单的通知处理
|
||||
- 减少不必要的通知,提升用户体验
|
||||
|
||||
## 🐛 Bug 修复
|
||||
|
||||
### 修复移动端 API 健康页面缺少数据显示
|
||||
- 移动端添加 URL 地址显示
|
||||
- 移动端添加状态文本显示(正常/异常/未配置)
|
||||
- 移动端添加消息/状态信息显示
|
||||
- 移动端和桌面端显示信息保持一致
|
||||
|
||||
## 🔧 功能优化
|
||||
|
||||
### 优化 Telegram 推送消息格式
|
||||
- 添加价格和数量截位处理:
|
||||
* 价格保留最多4位小数(截断,不四舍五入)
|
||||
* 数量保留最多2位小数(截断,不四舍五入)
|
||||
- 优化账户信息显示格式:
|
||||
* 有账户名和钱包地址时显示:账户名(0x123...123)
|
||||
* 只有账户名时显示账户名
|
||||
* 只有钱包地址时显示脱敏后的地址
|
||||
* 都没有时显示未知账户
|
||||
|
||||
### 配置优化
|
||||
- 移除 `polygon.rpc.url` 配置,使用 RpcNodeService 统一管理 RPC 节点
|
||||
- 删除无用的 `position.push.polling-interval` 和 `position.push.heartbeat-timeout` 配置项
|
||||
- 修正日志配置中的包名(polyhermes -> polymarketbot)
|
||||
- 更新 `ApiHealthCheckService` 直接使用 `RpcNodeService.getHttpUrl()`
|
||||
|
||||
## 📚 文档更新
|
||||
|
||||
- 统一发布说明文件,使用 RELEASE.md 替代版本化文件(RELEASE_v1.0.1.md、RELEASE_v1.1.0.md)
|
||||
- 更新所有部署文档,移除 POLYGON_RPC_URL 相关说明
|
||||
- 更新所有 Docker Compose 配置文件,移除 POLYGON_RPC_URL 环境变量
|
||||
- 更新所有部署脚本,移除 POLYGON_RPC_URL 环境变量定义
|
||||
|
||||
## 🔧 技术改进
|
||||
|
||||
- 重构链上 WebSocket 服务,提取公共代码到 `OnChainWsUtils`
|
||||
- 创建统一的 WebSocket 连接管理服务 `UnifiedOnChainWsService`
|
||||
- 添加链上查询市场结算结果的功能(`BlockchainService.getCondition`)
|
||||
- 添加 ABI 编码/解码工具方法(`EthereumUtils.decodeConditionResult`)
|
||||
- 优化代码结构,减少代码重复,提高可维护性
|
||||
|
||||
---
|
||||
|
||||
# v1.1.0
|
||||
|
||||
## 🚀 主要功能
|
||||
|
||||
### 🔗 链上 WebSocket 实时监听
|
||||
- 实现通过 Polygon RPC `eth_subscribe` 实时监听链上交易
|
||||
- 支持监听 USDC Transfer 和 ERC1155 Transfer 事件
|
||||
- 实现并行监控策略:链上 WebSocket 和轮询同时运行,哪个数据先返回用哪个
|
||||
- 支持通过 `eth_unsubscribe` 取消单个 Leader 的订阅,无需重新连接
|
||||
- 优化 WebSocket 连接管理:只创建一个连接,没有跟单配置时自动取消
|
||||
- 跟单配置生效/失效时及时更新 WebSocket 订阅
|
||||
- 使用 Gson 替换所有 JSON 解析,提高解析稳定性
|
||||
- 添加 Mutex 保证线程安全,防止并发处理导致的数据重复
|
||||
|
||||
### 📊 RPC 节点管理
|
||||
- 实现 RPC 节点管理功能,支持添加、编辑、删除自定义 RPC 节点
|
||||
- 支持 RPC 节点启用/禁用功能,禁用的节点会被自动忽略
|
||||
- 前端添加启用/禁用开关,支持实时切换节点状态
|
||||
- 健康检查只检查启用的节点,提高检查效率
|
||||
- 节点选择时自动过滤禁用的节点
|
||||
|
||||
### 💰 卖出订单价格轮询更新
|
||||
- 添加 `price_updated` 字段到 `sell_match_record` 表,用于标记价格是否已更新
|
||||
- 创建 `OrderStatusUpdateService` 定时任务服务,每 5 秒轮询一次:
|
||||
- 更新卖出订单的实际成交价(通过 orderId 查询订单详情)
|
||||
- 清理已删除账户的订单记录
|
||||
- 支持加权平均价格计算,处理部分成交的订单
|
||||
- 添加 orderId 格式验证:非 0x 开头的直接标记为已更新,0x 开头的等待定时任务更新
|
||||
- 下单完成后不再立即查询价格,直接保存,等待定时任务更新
|
||||
|
||||
## 🐛 Bug 修复
|
||||
|
||||
### 修复跟单卖出订单的 API 凭证解密问题
|
||||
- 修复 `processSellTrade` 中 API 凭证未解密的问题,与 `processBuyTrade` 保持一致
|
||||
- 确保卖出订单能够正常使用 API 凭证进行认证
|
||||
|
||||
### 修复 SELL 订单精度问题
|
||||
- 修复 SELL 订单的 `makerAmount` 和 `takerAmount` 精度问题:
|
||||
- `makerAmount` (shares) 最多 2 位小数(符合 API 要求)
|
||||
- `takerAmount` (USDC) 最多 4 位小数(符合 API 要求)
|
||||
- 确保订单能够正常提交到 Polymarket API
|
||||
|
||||
## 📚 文档更新
|
||||
|
||||
- 添加 Docker 版本更新说明(中英文)
|
||||
- 添加链上 WebSocket 监听策略文档
|
||||
- 添加跟单逻辑总结文档
|
||||
- 更新部署文档,包含详细的版本更新步骤
|
||||
|
||||
## 🔧 技术改进
|
||||
|
||||
- 使用 Gson 替换 ObjectMapper,提高 JSON 解析稳定性
|
||||
- `JsonRpcResponse.result` 使用 `JsonElement` 类型,支持灵活的 JSON 结构
|
||||
- 优化 WebSocket 连接管理,减少不必要的连接
|
||||
- 添加线程安全机制,使用 Kotlin Coroutines Mutex
|
||||
- 启用 Spring 定时任务功能(`@EnableScheduling`)
|
||||
|
||||
## 📦 数据库变更
|
||||
|
||||
- 新增 `price_updated` 字段到 `sell_match_record` 表(Migration: V13)
|
||||
|
||||
## 🔗 相关链接
|
||||
|
||||
- **GitHub Release**: https://github.com/WrBug/PolyHermes/releases/tag/v1.1.1
|
||||
- **完整更新日志**: https://github.com/WrBug/PolyHermes/compare/v1.1.0...v1.1.1
|
||||
- **Docker Hub**: https://hub.docker.com/r/wrbug/polyhermes
|
||||
|
||||
## 📊 统计信息
|
||||
|
||||
- **文件变更**: 32 个文件
|
||||
- **代码变更**: +1872 行 / -1503 行
|
||||
- **主要提交**: 7 个提交
|
||||
|
||||
## ⚠️ 重要提醒
|
||||
|
||||
**请务必使用官方 Docker 镜像源,避免财产损失!**
|
||||
|
||||
### ✅ 官方 Docker Hub 镜像
|
||||
|
||||
**官方镜像地址**:`wrbug/polyhermes`
|
||||
|
||||
```bash
|
||||
# ✅ 正确:使用官方镜像
|
||||
docker pull wrbug/polyhermes:v1.1.1
|
||||
|
||||
# ❌ 错误:不要使用其他来源的镜像
|
||||
# 任何非官方来源的镜像都可能包含恶意代码,导致您的私钥和资产被盗
|
||||
```
|
||||
|
||||
### 🔗 官方渠道
|
||||
|
||||
请通过以下**唯一官方渠道**获取 PolyHermes:
|
||||
|
||||
* **GitHub 仓库**:https://github.com/WrBug/PolyHermes
|
||||
* **Twitter**:@polyhermes
|
||||
* **Telegram 群组**:https://t.me/polyhermes
|
||||
|
||||
---
|
||||
|
||||
**⭐ 如果这个项目对您有帮助,请给个 Star 支持一下!**
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
## 版本信息
|
||||
- **版本号**: v1.1.15
|
||||
- **发布日期**: 2026-01-19
|
||||
- **基础版本**: v1.1.14
|
||||
|
||||
## 改动摘要
|
||||
本次版本优化了订单详情处理逻辑,提升了系统稳定性和开发体验。
|
||||
|
||||
## 主要改动
|
||||
|
||||
### 🐛 Bug 修复
|
||||
|
||||
#### 1. 优化订单详情为 null 时的处理逻辑
|
||||
- **提交**: 7385eff
|
||||
- **文件**: OrderStatusUpdateService.kt
|
||||
- **问题**:
|
||||
- 订单详情为 null 且已发送通知超过 60 秒时,订单被直接删除
|
||||
- 导致已经正确处理并发送 TG 通知的订单被意外删除
|
||||
- **修复**:
|
||||
- 当订单详情为 null 且 notificationSent = true 超过 60 秒时,将订单状态改为 fully_matched
|
||||
- fully_matched 状态的订单会被自动过滤,不再查询详情
|
||||
- 避免已处理的订单被误删除
|
||||
|
||||
### 🧹 日志清理
|
||||
|
||||
#### 2. 清理 MarketPollingService 中多余的 debug 日志
|
||||
- **提交**: d768da7, 07b4d65
|
||||
- **文件**: MarketPollingService.kt
|
||||
- **改进**:
|
||||
- 删除多余的 debug 日志输出
|
||||
- 减少冗余日志,提升日志可读性
|
||||
- 优化性能(减少日志 I/O)
|
||||
|
||||
### ✨ 新增功能
|
||||
|
||||
#### 3. 添加订单详情查询工具脚本
|
||||
- **提交**: b658270
|
||||
- **新增文件**:
|
||||
- scripts/get-order-detail.js - 订单详情查询脚本
|
||||
- scripts/package.json - 依赖配置文件
|
||||
- **功能**:
|
||||
- 快速查询 Polymarket 订单详情
|
||||
- 支持自动创建 API Key
|
||||
- 完善的错误处理和参数验证
|
||||
- 详细的订单信息输出
|
||||
|
||||
## 文件变更统计
|
||||
- **修改文件数**: 3
|
||||
- **新增文件数**: 2
|
||||
- **新增行数**: 192
|
||||
- **删除行数**: 6
|
||||
|
||||
## 技术细节
|
||||
|
||||
### 订单状态管理优化
|
||||
- 使用 fully_matched 状态标记已处理订单
|
||||
- 通过数据库查询条件自动过滤,无需额外缓存
|
||||
- 保持数据一致性和可追溯性
|
||||
|
||||
### 工具脚本特性
|
||||
- 基于 Polymarket CLOB Client v5.2.1
|
||||
- 支持 derive/create API Key 自动处理
|
||||
- 完整的参数验证和错误提示
|
||||
- 友好的命令行交互体验
|
||||
|
||||
## 升级建议
|
||||
- 无需特殊操作,直接部署即可
|
||||
- 建议验证订单处理逻辑是否正常工作
|
||||
- 可以使用新增的工具脚本进行调试
|
||||
|
||||
## 完整提交列表
|
||||
- 7385eff - 优化订单详情为null时的处理逻辑
|
||||
- d768da7 - 清理 MarketPollingService 中多余的 debug 日志
|
||||
- b658270 - 添加订单详情查询脚本
|
||||
- 07b4d65 - 清理 MarketPollingService 调试日志
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -130,7 +130,7 @@ export PROXY_PORT=8888
|
||||
- 代理配置错误
|
||||
|
||||
**排查步骤**:
|
||||
1. 检查 `polymarket.rtds.ws-url` 配置是否正确
|
||||
1. 检查 Polymarket RTDS WebSocket URL(现在使用代码常量 `PolymarketConstants.RTDS_WS_URL`)
|
||||
2. 检查网络连接
|
||||
3. 查看详细错误日志
|
||||
|
||||
|
||||
@@ -68,6 +68,9 @@ dependencies {
|
||||
// Logging
|
||||
implementation("org.slf4j:slf4j-api")
|
||||
|
||||
// Caffeine Cache (LRU)
|
||||
implementation("com.github.ben-manes.caffeine:caffeine:3.1.8")
|
||||
|
||||
// Test
|
||||
testImplementation("org.springframework.boot:spring-boot-starter-test")
|
||||
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test")
|
||||
|
||||
@@ -9,6 +9,7 @@ services:
|
||||
ports:
|
||||
- "${SERVER_PORT:-8000}:8000"
|
||||
environment:
|
||||
- TZ=${TZ:-Asia/Shanghai}
|
||||
- SPRING_PROFILES_ACTIVE=${SPRING_PROFILES_ACTIVE:-prod}
|
||||
- DB_URL=${DB_URL:-jdbc:mysql://mysql:3306/polyhermes?useSSL=false&serverTimezone=UTC&characterEncoding=utf8&allowPublicKeyRetrieval=true}
|
||||
- DB_USERNAME=${DB_USERNAME:-root}
|
||||
@@ -16,6 +17,8 @@ services:
|
||||
- SERVER_PORT=8000
|
||||
- JWT_SECRET=${JWT_SECRET:-change-me-in-production}
|
||||
- ADMIN_RESET_PASSWORD_KEY=${ADMIN_RESET_PASSWORD_KEY:-change-me-in-production}
|
||||
volumes:
|
||||
- /etc/localtime:/etc/localtime:ro
|
||||
depends_on:
|
||||
mysql:
|
||||
condition: service_healthy
|
||||
@@ -29,12 +32,14 @@ services:
|
||||
ports:
|
||||
- "${MYSQL_PORT:-3306}:3306"
|
||||
environment:
|
||||
- TZ=${TZ:-Asia/Shanghai}
|
||||
- MYSQL_ROOT_PASSWORD=${DB_PASSWORD:-rootpassword}
|
||||
- MYSQL_DATABASE=polyhermes
|
||||
- MYSQL_CHARACTER_SET_SERVER=utf8mb4
|
||||
- MYSQL_COLLATION_SERVER=utf8mb4_unicode_ci
|
||||
volumes:
|
||||
- mysql-data:/var/lib/mysql
|
||||
- /etc/localtime:/etc/localtime:ro
|
||||
healthcheck:
|
||||
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${DB_PASSWORD:-rootpassword}"]
|
||||
interval: 10s
|
||||
|
||||
Executable
+59
@@ -0,0 +1,59 @@
|
||||
#!/bin/bash
|
||||
# 清理 Flyway V29 失败记录的脚本
|
||||
|
||||
echo "=== 清理 Flyway V29 失败记录 ==="
|
||||
echo ""
|
||||
echo "请确保 MySQL 正在运行,然后输入数据库密码"
|
||||
echo ""
|
||||
|
||||
# 数据库配置
|
||||
DB_HOST="localhost"
|
||||
DB_PORT="3306"
|
||||
DB_NAME="polymarket_bot"
|
||||
DB_USER="root"
|
||||
|
||||
# 检查 MySQL 命令是否可用
|
||||
if ! command -v mysql &> /dev/null; then
|
||||
echo "❌ 错误: 未找到 mysql 命令"
|
||||
echo ""
|
||||
echo "请使用数据库客户端(如 Navicat、DataGrip 等)执行以下 SQL:"
|
||||
echo ""
|
||||
echo "-- 1. 查看 Flyway 历史记录"
|
||||
echo "SELECT version, description, installed_on, success "
|
||||
echo "FROM flyway_schema_history "
|
||||
echo "WHERE version >= 28"
|
||||
echo "ORDER BY installed_rank;"
|
||||
echo ""
|
||||
echo "-- 2. 删除 V29 的失败记录"
|
||||
echo "DELETE FROM flyway_schema_history WHERE version = '29';"
|
||||
echo ""
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 执行清理
|
||||
echo "正在连接数据库..."
|
||||
mysql -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p "$DB_NAME" << 'EOF'
|
||||
-- 查看当前状态
|
||||
SELECT '=== 当前 Flyway 历史记录 ===' as '';
|
||||
SELECT version, description, installed_on, success
|
||||
FROM flyway_schema_history
|
||||
WHERE version >= 28
|
||||
ORDER BY installed_rank;
|
||||
|
||||
-- 删除 V29 失败记录
|
||||
SELECT '=== 删除 V29 记录 ===' as '';
|
||||
DELETE FROM flyway_schema_history WHERE version = '29';
|
||||
|
||||
-- 确认删除结果
|
||||
SELECT CONCAT('已删除 ', ROW_COUNT(), ' 条记录') as result;
|
||||
|
||||
-- 再次查看状态
|
||||
SELECT '=== 清理后的 Flyway 历史记录 ===' as '';
|
||||
SELECT version, description, installed_on, success
|
||||
FROM flyway_schema_history
|
||||
WHERE version >= 28
|
||||
ORDER BY installed_rank;
|
||||
EOF
|
||||
|
||||
echo ""
|
||||
echo "✅ 清理完成!现在可以重启应用了"
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,26 @@
|
||||
package com.wrbug.polymarketbot.api
|
||||
|
||||
import retrofit2.Call
|
||||
import retrofit2.http.GET
|
||||
import retrofit2.http.Query
|
||||
|
||||
/**
|
||||
* 币安现货公开 API(K 线等)
|
||||
* Base URL: https://api.binance.com
|
||||
* 文档: https://developers.binance.com/docs/binance-spot-api-docs/rest-api
|
||||
*/
|
||||
interface BinanceApi {
|
||||
|
||||
/**
|
||||
* K 线数据
|
||||
* 返回每根 K 线: [openTime, open, high, low, close, volume, closeTime, ...]
|
||||
*/
|
||||
@GET("/api/v3/klines")
|
||||
fun getKlines(
|
||||
@Query("symbol") symbol: String,
|
||||
@Query("interval") interval: String,
|
||||
@Query("limit") limit: Int = 30,
|
||||
@Query("startTime") startTime: Long? = null,
|
||||
@Query("endTime") endTime: Long? = null
|
||||
): Call<List<List<Any>>>
|
||||
}
|
||||
@@ -41,6 +41,17 @@ interface BuilderRelayerApi {
|
||||
@Query("address") address: String,
|
||||
@Query("type") type: String
|
||||
): Response<NoncePayload>
|
||||
|
||||
/**
|
||||
* 获取 Relay Payload(PROXY 类型执行时使用)
|
||||
* GET /relay-payload?address={address}&type=PROXY
|
||||
* 参考: builder-relayer-client endpoints GET_RELAY_PAYLOAD
|
||||
*/
|
||||
@GET("/relay-payload")
|
||||
suspend fun getRelayPayload(
|
||||
@Query("address") address: String,
|
||||
@Query("type") type: String
|
||||
): Response<RelayPayload>
|
||||
|
||||
/**
|
||||
* 获取交易状态
|
||||
@@ -81,7 +92,7 @@ interface BuilderRelayerApi {
|
||||
val data: String, // 调用数据(十六进制字符串,带 0x 前缀)
|
||||
|
||||
@SerializedName("nonce")
|
||||
val nonce: String, // Safe nonce(字符串)
|
||||
val nonce: String? = null, // Safe nonce(SAFE 必填,SAFE-CREATE 不传)
|
||||
|
||||
@SerializedName("signature")
|
||||
val signature: String, // Safe 签名(packed signature,十六进制字符串,带 0x 前缀)
|
||||
@@ -96,6 +107,7 @@ interface BuilderRelayerApi {
|
||||
/**
|
||||
* 签名参数
|
||||
* 参考: builder-relayer-client/src/types.ts 的 SignatureParams
|
||||
* Safe 使用 operation/safeTxnGas/baseGas 等,PROXY 使用 relayHub/relay/relayerFee 等
|
||||
*/
|
||||
data class SignatureParams(
|
||||
@SerializedName("gasPrice")
|
||||
@@ -114,7 +126,29 @@ interface BuilderRelayerApi {
|
||||
val gasToken: String? = null,
|
||||
|
||||
@SerializedName("refundReceiver")
|
||||
val refundReceiver: String? = null
|
||||
val refundReceiver: String? = null,
|
||||
|
||||
@SerializedName("relayerFee")
|
||||
val relayerFee: String? = null,
|
||||
|
||||
@SerializedName("gasLimit")
|
||||
val gasLimit: String? = null,
|
||||
|
||||
@SerializedName("relayHub")
|
||||
val relayHub: String? = null,
|
||||
|
||||
@SerializedName("relay")
|
||||
val relay: String? = null,
|
||||
|
||||
/** SAFE-CREATE 签名参数 */
|
||||
@SerializedName("paymentToken")
|
||||
val paymentToken: String? = null,
|
||||
|
||||
@SerializedName("payment")
|
||||
val payment: String? = null,
|
||||
|
||||
@SerializedName("paymentReceiver")
|
||||
val paymentReceiver: String? = null
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -142,6 +176,17 @@ interface BuilderRelayerApi {
|
||||
@SerializedName("nonce")
|
||||
val nonce: String
|
||||
)
|
||||
|
||||
/**
|
||||
* Relay Payload(PROXY 执行时获取 relay 地址与 nonce)
|
||||
* 参考: builder-relayer-client types RelayPayload
|
||||
*/
|
||||
data class RelayPayload(
|
||||
@SerializedName("address")
|
||||
val address: String,
|
||||
@SerializedName("nonce")
|
||||
val nonce: String
|
||||
)
|
||||
|
||||
/**
|
||||
* Relayer 交易详情
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.wrbug.polymarketbot.api
|
||||
|
||||
import com.google.gson.annotations.SerializedName
|
||||
import okhttp3.ResponseBody
|
||||
import retrofit2.Response
|
||||
import retrofit2.http.*
|
||||
|
||||
@@ -72,7 +73,7 @@ interface PolymarketClobApi {
|
||||
*/
|
||||
@POST("/orders/batch")
|
||||
suspend fun createOrdersBatch(
|
||||
@Body request: CreateOrdersBatchRequest
|
||||
@Body request: List<NewOrderRequest>
|
||||
): Response<List<OrderResponse>>
|
||||
|
||||
/**
|
||||
@@ -164,31 +165,34 @@ interface PolymarketClobApi {
|
||||
|
||||
/**
|
||||
* 获取服务器时间
|
||||
* 端点: /time
|
||||
* 端点: /time 返回纯数字(Unix 时间戳),非 JSON
|
||||
*/
|
||||
@GET("/time")
|
||||
suspend fun getServerTime(): Response<ServerTimeResponse>
|
||||
suspend fun getServerTime(): Response<ResponseBody>
|
||||
}
|
||||
|
||||
// 请求和响应数据类
|
||||
|
||||
/**
|
||||
* 签名的订单对象(根据官方文档)
|
||||
* 参考: https://docs.polymarket.com/developers/CLOB/orders/create-order
|
||||
* V2 签名的订单对象
|
||||
* EIP-712 签名字段: salt, maker, signer, tokenId, makerAmount, takerAmount, side, signatureType, timestamp, metadata, builder
|
||||
* API payload 额外字段: taker, expiration (不在 EIP-712 签名中,但 API 请求需要)
|
||||
* 参考: clob-client-v2/src/types/ordersV2.ts NewOrderV2
|
||||
*/
|
||||
data class SignedOrderObject(
|
||||
val salt: Long, // random salt used to create unique order
|
||||
val maker: String, // maker address (funder)
|
||||
val signer: String, // signing address
|
||||
val taker: String, // taker address (operator)
|
||||
val taker: String, // taker address (zero address for public orders, NOT in EIP-712 signing)
|
||||
val tokenId: String, // ERC1155 token ID of conditional token being traded
|
||||
val makerAmount: String, // maximum amount maker is willing to spend
|
||||
val takerAmount: String, // minimum amount taker will pay the maker in return
|
||||
val expiration: String, // unix expiration timestamp
|
||||
val nonce: String, // maker's exchange nonce of the order is associated
|
||||
val feeRateBps: String, // fee rate basis points as required by the operator
|
||||
val side: String, // buy or sell enum index ("BUY" or "SELL")
|
||||
val signatureType: Int, // signature type enum index
|
||||
val timestamp: String, // order creation time in milliseconds (V2)
|
||||
val expiration: String, // expiration timestamp unix seconds, "0" = no expiration (NOT in EIP-712 signing)
|
||||
val metadata: String, // bytes32 metadata (V2)
|
||||
val builder: String, // bytes32 builder code (V2)
|
||||
val signature: String // hex encoded signature
|
||||
)
|
||||
|
||||
@@ -197,10 +201,11 @@ data class SignedOrderObject(
|
||||
* 参考: https://docs.polymarket.com/developers/CLOB/orders/create-order
|
||||
*/
|
||||
data class NewOrderRequest(
|
||||
val order: SignedOrderObject, // signed object
|
||||
val order: SignedOrderObject, // V2 signed object
|
||||
val owner: String, // api key of order owner
|
||||
val orderType: String, // order type ("FOK", "GTC", "GTD", "FAK")
|
||||
val deferExec: Boolean = false // defer execution flag
|
||||
val deferExec: Boolean = false, // defer execution
|
||||
val postOnly: Boolean = false // post only (maker-only)
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -211,6 +216,7 @@ data class NewOrderResponse(
|
||||
val success: Boolean, // boolean indicating if server-side error
|
||||
@SerializedName("errorMsg")
|
||||
val errorMsg: String? = null, // error message in case of unsuccessful placement
|
||||
val error: String? = null, // error message (alternative field, e.g. "Trading restricted in your region...")
|
||||
@SerializedName("orderID")
|
||||
val orderId: String? = null, // id of order(API 返回字段名为 orderID)
|
||||
@SerializedName("transactionsHashes")
|
||||
@@ -221,27 +227,17 @@ data class NewOrderResponse(
|
||||
val takingAmount: String? = null, // taking amount
|
||||
@SerializedName("makingAmount")
|
||||
val makingAmount: String? = null // making amount
|
||||
)
|
||||
|
||||
/**
|
||||
* 旧的订单请求格式(已废弃,保留用于兼容)
|
||||
* @deprecated 使用 NewOrderRequest 代替
|
||||
*/
|
||||
@Deprecated("使用 NewOrderRequest 代替,需要签名的订单对象")
|
||||
data class CreateOrderRequest(
|
||||
val market: String? = null, // condition ID(可选,如果提供tokenId则不需要)
|
||||
val token_id: String? = null, // token ID(可选,如果提供market则不需要)
|
||||
val side: String, // "BUY" or "SELL"
|
||||
val price: String,
|
||||
val size: String,
|
||||
val type: String = "LIMIT",
|
||||
val expiration: Long? = null
|
||||
)
|
||||
|
||||
@Deprecated("使用 NewOrderRequest 代替")
|
||||
data class CreateOrdersBatchRequest(
|
||||
val orders: List<NewOrderRequest>
|
||||
)
|
||||
) {
|
||||
/**
|
||||
* 获取错误信息的便捷方法
|
||||
* 优先返回 errorMsg,其次返回 error,最后返回默认消息
|
||||
*/
|
||||
fun getErrorMessage(): String {
|
||||
return errorMsg?.takeIf { it.isNotBlank() }
|
||||
?: error?.takeIf { it.isNotBlank() }
|
||||
?: "创建订单失败"
|
||||
}
|
||||
}
|
||||
|
||||
data class CancelOrdersBatchRequest(
|
||||
val orderIds: List<String>
|
||||
@@ -334,7 +330,8 @@ data class TradeResponse(
|
||||
val timestamp: String, // ISO 8601 格式字符串或时间戳
|
||||
val user: String?,
|
||||
val outcomeIndex: Int? = null, // 结果索引(0=YES, 1=NO)
|
||||
val outcome: String? = null // 结果名称(如 "Up", "Down")
|
||||
val outcome: String? = null, // 结果名称(如 "Up", "Down")
|
||||
val tokenId: String? = null // CLOB tokenId(链上解析时从 ERC1155 取得,与 Gamma clobTokenIds 一致,用于下单)
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -363,13 +360,6 @@ data class ApiKeyResponse(
|
||||
val passphrase: String
|
||||
)
|
||||
|
||||
/**
|
||||
* 服务器时间响应
|
||||
*/
|
||||
data class ServerTimeResponse(
|
||||
val timestamp: Long
|
||||
)
|
||||
|
||||
/**
|
||||
* 费率响应
|
||||
* 文档: https://docs.polymarket.com/developers/market-makers/maker-rebates-program#1-fetch-the-fee-rate
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.wrbug.polymarketbot.api
|
||||
|
||||
import retrofit2.Response
|
||||
import retrofit2.http.GET
|
||||
import retrofit2.http.Path
|
||||
import retrofit2.http.Query
|
||||
|
||||
/**
|
||||
@@ -26,8 +27,58 @@ interface PolymarketGammaApi {
|
||||
@Query("clob_token_ids") clobTokenIds: List<String>? = null,
|
||||
@Query("include_tag") includeTag: Boolean? = null
|
||||
): Response<List<MarketResponse>>
|
||||
|
||||
/**
|
||||
* 根据 slug 获取事件(用于 5/15 分钟加密市场)
|
||||
* GET /events/slug/{slug},如 btc-updown-5m-1771007400
|
||||
* 返回事件含 markets(conditionId、endDate、clobTokenIds 等)
|
||||
*/
|
||||
@GET("/events/slug/{slug}")
|
||||
suspend fun getEventBySlug(@Path("slug") slug: String): Response<GammaEventBySlugResponse>
|
||||
}
|
||||
|
||||
/**
|
||||
* Gamma 按 slug 返回的事件结构
|
||||
*/
|
||||
data class GammaEventBySlugResponse(
|
||||
val id: String? = null,
|
||||
val slug: String? = null,
|
||||
val title: String? = null,
|
||||
val startDate: String? = null,
|
||||
val endDate: String? = null,
|
||||
val markets: List<GammaEventMarketItem>? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 事件下的市场项(5/15 分钟市场为二元,通常两个 outcome)
|
||||
*/
|
||||
data class GammaEventMarketItem(
|
||||
val conditionId: String? = null,
|
||||
val question: String? = null,
|
||||
val endDate: String? = null,
|
||||
val startDate: String? = null,
|
||||
val clobTokenIds: String? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 事件响应(从 MarketResponse.events 解析)
|
||||
* Gamma API Event 含 negRisk,用于判断是否使用 Neg Risk Exchange 签约
|
||||
*/
|
||||
data class EventResponse(
|
||||
val id: String? = null,
|
||||
val ticker: String? = null,
|
||||
val slug: String? = null,
|
||||
val title: String? = null,
|
||||
val category: String? = null,
|
||||
val active: Boolean? = null,
|
||||
val closed: Boolean? = null,
|
||||
val archived: Boolean? = null,
|
||||
val startDate: String? = null,
|
||||
val endDate: String? = null,
|
||||
val createdAt: String? = null,
|
||||
val negRisk: Boolean? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 市场响应(根据 Gamma API 文档)
|
||||
*/
|
||||
@@ -54,8 +105,11 @@ data class MarketResponse(
|
||||
val lastTradePrice: Double? = null,
|
||||
val bestBid: Double? = null,
|
||||
val bestAsk: Double? = null,
|
||||
val events: List<EventResponse>? = null, // 事件列表(从 events[0] 获取 slug)
|
||||
// 以下字段可能存在于响应中,但不在标准文档中
|
||||
val clobTokenIds: String? = null, // CLOB token IDs(可能是 JSON 字符串或数组)
|
||||
val clob_token_ids: String? = null // 下划线格式(兼容不同 API 版本)
|
||||
val clob_token_ids: String? = null, // 下划线格式(兼容不同 API 版本)
|
||||
val negRisk: Boolean? = null, // 事件级 neg risk(部分 API 直接返回在 market)
|
||||
val negRiskOther: Boolean? = null // Market 级 neg risk 标记
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.wrbug.polymarketbot.config
|
||||
|
||||
import com.wrbug.polymarketbot.service.common.WebSocketSubscriptionService
|
||||
import com.wrbug.polymarketbot.service.cryptotail.CryptoTailMonitorService
|
||||
import jakarta.annotation.PostConstruct
|
||||
import org.springframework.context.annotation.Configuration
|
||||
|
||||
/**
|
||||
* 加密价差策略监控服务配置
|
||||
* 处理 WebSocketSubscriptionService 和 CryptoTailMonitorService 之间的循环依赖
|
||||
*/
|
||||
@Configuration
|
||||
class MonitorServiceConfig(
|
||||
private val webSocketSubscriptionService: WebSocketSubscriptionService,
|
||||
private val cryptoTailMonitorService: CryptoTailMonitorService
|
||||
) {
|
||||
|
||||
@PostConstruct
|
||||
fun init() {
|
||||
// 在所有 Bean 初始化后设置引用
|
||||
webSocketSubscriptionService.setCryptoTailMonitorService(cryptoTailMonitorService)
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,8 @@ package com.wrbug.polymarketbot.config
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.wrbug.polymarketbot.api.PolymarketClobApi
|
||||
import com.wrbug.polymarketbot.constants.PolymarketConstants
|
||||
import com.wrbug.polymarketbot.util.createClient
|
||||
import org.springframework.beans.factory.annotation.Value
|
||||
import org.springframework.context.annotation.Bean
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import retrofit2.Retrofit
|
||||
@@ -23,9 +23,6 @@ class RetrofitConfig(
|
||||
private val gson: Gson
|
||||
) {
|
||||
|
||||
@Value("\${polymarket.clob.base-url}")
|
||||
private lateinit var clobBaseUrl: String
|
||||
|
||||
/**
|
||||
* 创建 CLOB API 客户端
|
||||
* 用于跟单系统的订单操作和交易查询
|
||||
@@ -38,7 +35,7 @@ class RetrofitConfig(
|
||||
val okHttpClient = createClient().build()
|
||||
|
||||
return Retrofit.Builder()
|
||||
.baseUrl(clobBaseUrl)
|
||||
.baseUrl(PolymarketConstants.CLOB_BASE_URL)
|
||||
.client(okHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.wrbug.polymarketbot.constants
|
||||
|
||||
/**
|
||||
* Polymarket API 常量
|
||||
* 集中管理所有 Polymarket API 的 URL 配置
|
||||
*/
|
||||
object PolymarketConstants {
|
||||
|
||||
/**
|
||||
* Polymarket CLOB API 基础 URL
|
||||
*/
|
||||
const val CLOB_BASE_URL = "https://clob.polymarket.com"
|
||||
|
||||
/**
|
||||
* Polymarket RTDS WebSocket URL
|
||||
* 用于订单推送服务
|
||||
*/
|
||||
const val RTDS_WS_URL = "wss://ws-subscriptions-clob.polymarket.com"
|
||||
|
||||
/**
|
||||
* Polymarket User Channel WebSocket URL
|
||||
* 用于跟单服务(订阅 Leader 交易)
|
||||
*/
|
||||
const val USER_WS_URL = "wss://ws-live-data.polymarket.com"
|
||||
|
||||
/**
|
||||
* Polymarket Activity WebSocket URL
|
||||
* 用于 Activity 全局交易流监听
|
||||
*/
|
||||
const val ACTIVITY_WS_URL = "wss://ws-live-data.polymarket.com"
|
||||
|
||||
/**
|
||||
* Polymarket Data API 基础 URL
|
||||
*/
|
||||
const val DATA_API_BASE_URL = "https://data-api.polymarket.com"
|
||||
|
||||
/**
|
||||
* Polymarket Gamma API 基础 URL
|
||||
*/
|
||||
const val GAMMA_BASE_URL = "https://gamma-api.polymarket.com"
|
||||
|
||||
/**
|
||||
* Builder Relayer API URL
|
||||
* 用于 Gasless 交易
|
||||
*/
|
||||
const val BUILDER_RELAYER_URL = "https://relayer-v2.polymarket.com/"
|
||||
|
||||
/**
|
||||
* Polymarket Safe 代理工厂合约地址(Polygon 主网)
|
||||
* 用于 Safe 类型账户的代理部署(SAFE-CREATE)
|
||||
*/
|
||||
const val SAFE_PROXY_FACTORY_ADDRESS = "0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b"
|
||||
|
||||
/** SafeCreate 用 EIP-712 domain name,与 builder-relayer-client 一致 */
|
||||
const val SAFE_FACTORY_EIP712_NAME = "Polymarket Contract Proxy Factory"
|
||||
}
|
||||
|
||||
+178
-7
@@ -23,6 +23,50 @@ class AccountController(
|
||||
|
||||
private val logger = LoggerFactory.getLogger(AccountController::class.java)
|
||||
|
||||
/**
|
||||
* 检查代理地址选项(用于导入前选择代理类型)
|
||||
*/
|
||||
@PostMapping("/check-proxy-options")
|
||||
fun checkProxyOptions(@RequestBody request: CheckProxyOptionsRequest): ResponseEntity<ApiResponse<CheckProxyOptionsResponse>> {
|
||||
return try {
|
||||
if (request.walletAddress.isBlank()) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_WALLET_ADDRESS_EMPTY, messageSource = messageSource))
|
||||
}
|
||||
if (request.privateKey.isNullOrBlank() && request.mnemonic.isNullOrBlank()) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_ERROR, "必须提供私钥或助记词", messageSource))
|
||||
}
|
||||
|
||||
val result = runBlocking { accountService.checkProxyOptions(request) }
|
||||
result.fold(
|
||||
onSuccess = { response ->
|
||||
ResponseEntity.ok(ApiResponse.success(response))
|
||||
},
|
||||
onFailure = { e ->
|
||||
logger.error("检查代理地址选项失败: ${e.message}", e)
|
||||
when (e) {
|
||||
is IllegalArgumentException -> ResponseEntity.ok(
|
||||
ApiResponse.error(
|
||||
ErrorCode.PARAM_ERROR,
|
||||
e.message,
|
||||
messageSource
|
||||
)
|
||||
)
|
||||
else -> ResponseEntity.ok(
|
||||
ApiResponse.error(
|
||||
ErrorCode.SERVER_ERROR,
|
||||
e.message,
|
||||
messageSource
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("检查代理地址选项异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过私钥导入账户
|
||||
*/
|
||||
@@ -45,14 +89,17 @@ class AccountController(
|
||||
onFailure = { e ->
|
||||
logger.error("导入账户失败: ${e.message}", e)
|
||||
when (e) {
|
||||
is IllegalArgumentException -> ResponseEntity.ok(
|
||||
ApiResponse.error(
|
||||
ErrorCode.PARAM_ERROR,
|
||||
e.message,
|
||||
messageSource
|
||||
is IllegalArgumentException -> if (e.message == "ACCOUNT_ALREADY_EXISTS") {
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.ACCOUNT_ALREADY_EXISTS, messageSource = messageSource))
|
||||
} else {
|
||||
ResponseEntity.ok(
|
||||
ApiResponse.error(
|
||||
ErrorCode.PARAM_ERROR,
|
||||
e.message,
|
||||
messageSource
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
}
|
||||
else -> ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ACCOUNT_IMPORT_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
@@ -157,6 +204,82 @@ class AccountController(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查账户设置状态(代理部署、交易启用、代币批准)
|
||||
*/
|
||||
@PostMapping("/check-setup-status")
|
||||
fun checkSetupStatus(@RequestBody request: AccountDetailRequest): ResponseEntity<ApiResponse<AccountSetupStatusDto>> {
|
||||
return try {
|
||||
if (request.accountId == null || request.accountId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_ACCOUNT_ID_INVALID, messageSource = messageSource))
|
||||
}
|
||||
val result = runBlocking { accountService.checkAccountSetupStatus(request.accountId) }
|
||||
result.fold(
|
||||
onSuccess = { status ->
|
||||
ResponseEntity.ok(ApiResponse.success(status))
|
||||
},
|
||||
onFailure = { e ->
|
||||
logger.error("检查账户设置状态失败: ${e.message}", e)
|
||||
when (e) {
|
||||
is IllegalArgumentException -> ResponseEntity.ok(
|
||||
ApiResponse.error(
|
||||
ErrorCode.PARAM_ERROR,
|
||||
e.message,
|
||||
messageSource
|
||||
)
|
||||
)
|
||||
else -> ResponseEntity.ok(
|
||||
ApiResponse.error(
|
||||
ErrorCode.SERVER_ERROR,
|
||||
e.message,
|
||||
messageSource
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("检查账户设置状态异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行设置步骤(步骤1 返回跳转 URL,步骤2/3 由后端执行)
|
||||
*/
|
||||
@PostMapping("/execute-setup-step")
|
||||
fun executeSetupStep(@RequestBody request: ExecuteSetupStepRequest): ResponseEntity<ApiResponse<ExecuteSetupStepResponse>> {
|
||||
return try {
|
||||
if (request.accountId == null || request.accountId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_ACCOUNT_ID_INVALID, messageSource = messageSource))
|
||||
}
|
||||
val step = request.step ?: 0
|
||||
if (step !in 1..3) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_ERROR, "步骤必须为 1、2 或 3", messageSource))
|
||||
}
|
||||
val result = runBlocking { accountService.executeSetupStep(request.accountId, step) }
|
||||
result.fold(
|
||||
onSuccess = { response ->
|
||||
ResponseEntity.ok(ApiResponse.success(response))
|
||||
},
|
||||
onFailure = { e ->
|
||||
logger.error("执行设置步骤失败: ${e.message}", e)
|
||||
when (e) {
|
||||
is IllegalArgumentException -> ResponseEntity.ok(
|
||||
ApiResponse.error(ErrorCode.PARAM_ERROR, e.message, messageSource)
|
||||
)
|
||||
else -> ResponseEntity.ok(
|
||||
ApiResponse.error(ErrorCode.SERVER_ERROR, e.message, messageSource)
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("执行设置步骤异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询账户详情
|
||||
*/
|
||||
@@ -449,5 +572,53 @@ class AccountController(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 USDC.e wrap 为 pUSD(V2 迁移)
|
||||
*/
|
||||
@PostMapping("/wrap-to-pusd")
|
||||
fun wrapToPusd(@RequestBody request: Map<String, Any>): ResponseEntity<ApiResponse<Map<String, String?>>> {
|
||||
return try {
|
||||
val accountId = (request["accountId"] as? Number)?.toLong()
|
||||
?: return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_ACCOUNT_ID_INVALID, messageSource = messageSource))
|
||||
val result = runBlocking { accountService.wrapUsdcToPusd(accountId) }
|
||||
result.fold(
|
||||
onSuccess = { txHash ->
|
||||
ResponseEntity.ok(ApiResponse.success(mapOf("transactionHash" to txHash)))
|
||||
},
|
||||
onFailure = { e ->
|
||||
logger.error("USDC.e → pUSD wrap 失败: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, e.message, messageSource))
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("USDC.e → pUSD wrap 异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询 USDC.e 余额(V2 迁移用)
|
||||
*/
|
||||
@PostMapping("/usdce-balance")
|
||||
fun getUsdceBalance(@RequestBody request: Map<String, Any>): ResponseEntity<ApiResponse<Map<String, String>>> {
|
||||
return try {
|
||||
val accountId = (request["accountId"] as? Number)?.toLong()
|
||||
?: return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_ACCOUNT_ID_INVALID, messageSource = messageSource))
|
||||
val result = runBlocking { accountService.getUsdceBalance(accountId) }
|
||||
result.fold(
|
||||
onSuccess = { balance ->
|
||||
ResponseEntity.ok(ApiResponse.success(mapOf("balance" to balance.toPlainString())))
|
||||
},
|
||||
onFailure = { e ->
|
||||
logger.error("查询 USDC.e 余额失败: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, e.message, messageSource))
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("查询 USDC.e 余额异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.wrbug.polymarketbot.controller.auth
|
||||
|
||||
import com.wrbug.polymarketbot.dto.*
|
||||
import com.wrbug.polymarketbot.enums.ErrorCode
|
||||
import com.wrbug.polymarketbot.repository.UserRepository
|
||||
import com.wrbug.polymarketbot.service.auth.AuthService
|
||||
import com.wrbug.polymarketbot.service.auth.WebSocketTicketService
|
||||
import jakarta.servlet.http.HttpServletRequest
|
||||
@@ -18,7 +19,8 @@ import org.springframework.web.bind.annotation.*
|
||||
class AuthController(
|
||||
private val authService: AuthService,
|
||||
private val messageSource: MessageSource,
|
||||
private val webSocketTicketService: WebSocketTicketService
|
||||
private val webSocketTicketService: WebSocketTicketService,
|
||||
private val userRepository: UserRepository
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(AuthController::class.java)
|
||||
@@ -184,5 +186,32 @@ class AuthController(
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, "获取票据失败", messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证当前用户权限
|
||||
* 用于动态更新服务验证管理员权限
|
||||
* 管理员权限判断:是否为默认账户(isDefault == true)
|
||||
*/
|
||||
@GetMapping("/verify")
|
||||
fun verify(httpRequest: HttpServletRequest): ResponseEntity<ApiResponse<Unit>> {
|
||||
return try {
|
||||
// 从请求属性中获取用户名(由 JWT 拦截器设置)
|
||||
val username = httpRequest.getAttribute("username") as? String
|
||||
if (username == null) {
|
||||
return ResponseEntity.status(401).body(ApiResponse.error(ErrorCode.AUTH_ERROR, "未认证", messageSource))
|
||||
}
|
||||
|
||||
// 检查是否为默认账户(管理员)
|
||||
val user = userRepository.findByUsername(username)
|
||||
if (user == null || !user.isDefault) {
|
||||
return ResponseEntity.status(403).body(ApiResponse.error(ErrorCode.AUTH_ERROR, "需要管理员权限", messageSource))
|
||||
}
|
||||
|
||||
ResponseEntity.ok(ApiResponse.success(Unit))
|
||||
} catch (e: Exception) {
|
||||
logger.error("验证权限异常: ${e.message}", e)
|
||||
ResponseEntity.status(500).body(ApiResponse.error(ErrorCode.SERVER_ERROR, "验证失败", messageSource))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
package com.wrbug.polymarketbot.controller.backtest
|
||||
|
||||
import com.wrbug.polymarketbot.dto.*
|
||||
import com.wrbug.polymarketbot.enums.ErrorCode
|
||||
import com.wrbug.polymarketbot.service.backtest.BacktestService
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.context.MessageSource
|
||||
import org.springframework.http.ResponseEntity
|
||||
import org.springframework.web.bind.annotation.*
|
||||
|
||||
/**
|
||||
* 回测管理控制器
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/backtest")
|
||||
class BacktestController(
|
||||
private val backtestService: BacktestService,
|
||||
private val messageSource: MessageSource
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(BacktestController::class.java)
|
||||
|
||||
/**
|
||||
* 创建回测任务
|
||||
*/
|
||||
@PostMapping("/tasks")
|
||||
fun createBacktestTask(@RequestBody request: BacktestCreateRequest): ResponseEntity<ApiResponse<BacktestTaskDto>> {
|
||||
return try {
|
||||
logger.info("创建回测任务: taskName=${request.taskName}, leaderId=${request.leaderId}")
|
||||
|
||||
val result = runBlocking {
|
||||
backtestService.createBacktestTask(request)
|
||||
}
|
||||
|
||||
result.fold(
|
||||
onSuccess = { dto ->
|
||||
logger.info("回测任务创建成功: taskId=${dto.id}")
|
||||
ResponseEntity.ok(ApiResponse.success(dto))
|
||||
},
|
||||
onFailure = { e ->
|
||||
logger.error("创建回测任务失败", e)
|
||||
val errorCode = when (e) {
|
||||
is IllegalArgumentException -> ErrorCode.PARAM_ERROR
|
||||
else -> ErrorCode.SERVER_BACKTEST_CREATE_FAILED
|
||||
}
|
||||
ResponseEntity.ok(ApiResponse.error(errorCode, e.message, messageSource))
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("创建回测任务异常", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_BACKTEST_CREATE_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询回测任务列表
|
||||
*/
|
||||
@PostMapping("/tasks/list")
|
||||
fun getBacktestTaskList(@RequestBody request: BacktestListRequest): ResponseEntity<ApiResponse<BacktestListResponse>> {
|
||||
return try {
|
||||
val result = backtestService.getBacktestTaskList(request)
|
||||
|
||||
result.fold(
|
||||
onSuccess = { response ->
|
||||
logger.info("查询回测任务列表成功: total=${response.total}")
|
||||
ResponseEntity.ok(ApiResponse.success(response))
|
||||
},
|
||||
onFailure = { e ->
|
||||
logger.error("查询回测任务列表失败", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_BACKTEST_LIST_FETCH_FAILED, e.message, messageSource))
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("查询回测任务列表异常", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_BACKTEST_LIST_FETCH_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询回测任务详情
|
||||
*/
|
||||
@PostMapping("/tasks/detail")
|
||||
fun getBacktestTaskDetail(@RequestBody request: BacktestDetailRequest): ResponseEntity<ApiResponse<BacktestDetailResponse>> {
|
||||
return try {
|
||||
val result = backtestService.getBacktestTaskDetail(request)
|
||||
|
||||
result.fold(
|
||||
onSuccess = { response ->
|
||||
logger.info("查询回测任务详情成功: taskId=${request.id}")
|
||||
ResponseEntity.ok(ApiResponse.success(response))
|
||||
},
|
||||
onFailure = { e ->
|
||||
logger.error("查询回测任务详情失败", e)
|
||||
val errorCode = when (e) {
|
||||
is IllegalArgumentException -> ErrorCode.BACKTEST_TASK_NOT_FOUND
|
||||
else -> ErrorCode.SERVER_BACKTEST_DETAIL_FETCH_FAILED
|
||||
}
|
||||
ResponseEntity.ok(ApiResponse.error(errorCode, e.message, messageSource))
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("查询回测任务详情异常", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_BACKTEST_DETAIL_FETCH_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询回测交易记录
|
||||
*/
|
||||
@PostMapping("/tasks/trades")
|
||||
fun getBacktestTrades(@RequestBody request: BacktestTradeListRequest): ResponseEntity<ApiResponse<BacktestTradeListResponse>> {
|
||||
return try {
|
||||
val result = backtestService.getBacktestTrades(request)
|
||||
|
||||
result.fold(
|
||||
onSuccess = { response ->
|
||||
logger.info("查询回测交易记录成功: taskId=${request.taskId}")
|
||||
ResponseEntity.ok(ApiResponse.success(response))
|
||||
},
|
||||
onFailure = { e ->
|
||||
logger.error("查询回测交易记录失败", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_BACKTEST_TRADES_FETCH_FAILED, e.message, messageSource))
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("查询回测交易记录异常", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_BACKTEST_TRADES_FETCH_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除回测任务
|
||||
*/
|
||||
@PostMapping("/tasks/delete")
|
||||
fun deleteBacktestTask(@RequestBody request: BacktestDeleteRequest): ResponseEntity<ApiResponse<Unit>> {
|
||||
return try {
|
||||
logger.info("删除回测任务: taskId=${request.id}")
|
||||
|
||||
val result = backtestService.deleteBacktestTask(request)
|
||||
|
||||
result.fold(
|
||||
onSuccess = {
|
||||
logger.info("回测任务删除成功: taskId=${request.id}")
|
||||
ResponseEntity.ok(ApiResponse.success(Unit))
|
||||
},
|
||||
onFailure = { e ->
|
||||
logger.error("删除回测任务失败", e)
|
||||
val errorCode = when (e) {
|
||||
is IllegalArgumentException -> ErrorCode.BACKTEST_TASK_NOT_FOUND
|
||||
is IllegalStateException -> ErrorCode.BACKTEST_TASK_RUNNING
|
||||
else -> ErrorCode.SERVER_BACKTEST_DELETE_FAILED
|
||||
}
|
||||
ResponseEntity.ok(ApiResponse.error(errorCode, e.message, messageSource))
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("删除回测任务异常", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_BACKTEST_DELETE_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止回测任务
|
||||
*/
|
||||
@PostMapping("/tasks/stop")
|
||||
fun stopBacktestTask(@RequestBody request: BacktestStopRequest): ResponseEntity<ApiResponse<Unit>> {
|
||||
return try {
|
||||
logger.info("停止回测任务: taskId=${request.id}")
|
||||
|
||||
val result = backtestService.stopBacktestTask(request)
|
||||
|
||||
result.fold(
|
||||
onSuccess = {
|
||||
logger.info("回测任务停止成功: taskId=${request.id}")
|
||||
ResponseEntity.ok(ApiResponse.success(Unit))
|
||||
},
|
||||
onFailure = { e ->
|
||||
logger.error("停止回测任务失败", e)
|
||||
val errorCode = when (e) {
|
||||
is IllegalArgumentException -> ErrorCode.BACKTEST_TASK_NOT_FOUND
|
||||
is IllegalStateException -> ErrorCode.BACKTEST_TASK_RUNNING
|
||||
else -> ErrorCode.SERVER_BACKTEST_STOP_FAILED
|
||||
}
|
||||
ResponseEntity.ok(ApiResponse.error(errorCode, e.message, messageSource))
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("停止回测任务异常", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_BACKTEST_STOP_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重试回测任务
|
||||
*/
|
||||
@PostMapping("/tasks/retry")
|
||||
fun retryBacktestTask(@RequestBody request: BacktestRetryRequest): ResponseEntity<ApiResponse<Unit>> {
|
||||
return try {
|
||||
logger.info("重试回测任务: taskId=${request.id}")
|
||||
|
||||
val result = backtestService.retryBacktestTask(request)
|
||||
|
||||
result.fold(
|
||||
onSuccess = {
|
||||
logger.info("回测任务重试成功: taskId=${request.id}")
|
||||
ResponseEntity.ok(ApiResponse.success(Unit))
|
||||
},
|
||||
onFailure = { e ->
|
||||
logger.error("重试回测任务失败", e)
|
||||
val errorCode = when (e) {
|
||||
is IllegalArgumentException -> ErrorCode.BACKTEST_TASK_NOT_FOUND
|
||||
is IllegalStateException -> ErrorCode.BACKTEST_TASK_RUNNING
|
||||
else -> ErrorCode.SERVER_BACKTEST_RETRY_FAILED
|
||||
}
|
||||
ResponseEntity.ok(ApiResponse.error(errorCode, e.message, messageSource))
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("重试回测任务异常", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_BACKTEST_RETRY_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按当前配置重新测试:基于已完成的回测任务创建相同配置的新任务(仅支持已完成任务)
|
||||
*/
|
||||
@PostMapping("/tasks/rerun")
|
||||
fun rerunBacktestTask(@RequestBody request: BacktestRerunRequest): ResponseEntity<ApiResponse<BacktestTaskDto>> {
|
||||
return try {
|
||||
logger.info("按配置重新测试: sourceTaskId=${request.id}, newTaskName=${request.taskName}")
|
||||
|
||||
val result = backtestService.rerunBacktestTask(request)
|
||||
|
||||
result.fold(
|
||||
onSuccess = { dto ->
|
||||
logger.info("重新测试任务创建成功: newTaskId=${dto.id}")
|
||||
ResponseEntity.ok(ApiResponse.success(dto))
|
||||
},
|
||||
onFailure = { e ->
|
||||
logger.error("按配置重新测试失败", e)
|
||||
val errorCode = when (e) {
|
||||
is IllegalArgumentException -> ErrorCode.BACKTEST_TASK_NOT_FOUND
|
||||
is IllegalStateException -> ErrorCode.BACKTEST_TASK_NOT_COMPLETED
|
||||
else -> ErrorCode.SERVER_BACKTEST_RERUN_FAILED
|
||||
}
|
||||
ResponseEntity.ok(ApiResponse.error(errorCode, e.message, messageSource))
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("按配置重新测试异常", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_BACKTEST_RERUN_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+37
-1
@@ -112,6 +112,43 @@ class CopyTradingController(
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_COPY_TRADING_UPDATE_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用诊断建议的保守风控配置。
|
||||
*/
|
||||
@PostMapping("/apply-conservative-config")
|
||||
fun applyConservativeConfig(@RequestBody request: ApplyConservativeConfigRequest): ResponseEntity<ApiResponse<CopyTradingDto>> {
|
||||
return try {
|
||||
if (request.copyTradingId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_COPY_TRADING_ID_INVALID, messageSource = messageSource))
|
||||
}
|
||||
|
||||
val result = copyTradingService.applyConservativeConfig(request)
|
||||
result.fold(
|
||||
onSuccess = { copyTrading ->
|
||||
ResponseEntity.ok(ApiResponse.success(copyTrading))
|
||||
},
|
||||
onFailure = { e ->
|
||||
logger.error("应用保守配置失败: ${e.message}", e)
|
||||
when (e) {
|
||||
is IllegalArgumentException -> {
|
||||
val errorCode = if (e.message == "跟单配置不存在") {
|
||||
ErrorCode.COPY_TRADING_NOT_FOUND
|
||||
} else {
|
||||
ErrorCode.PARAM_ERROR
|
||||
}
|
||||
ResponseEntity.ok(ApiResponse.error(errorCode, e.message, messageSource))
|
||||
}
|
||||
is IllegalStateException -> ResponseEntity.ok(ApiResponse.error(ErrorCode.BUSINESS_ERROR, e.message, messageSource))
|
||||
else -> ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_COPY_TRADING_UPDATE_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("应用保守配置异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_COPY_TRADING_UPDATE_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新跟单状态(兼容旧接口)
|
||||
@@ -219,4 +256,3 @@ class CopyTradingController(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
package com.wrbug.polymarketbot.controller.copytrading.leaderpool
|
||||
|
||||
import com.wrbug.polymarketbot.dto.*
|
||||
import com.wrbug.polymarketbot.enums.ErrorCode
|
||||
import com.wrbug.polymarketbot.service.copytrading.leaderpool.LeaderPoolAlreadyExistsException
|
||||
import com.wrbug.polymarketbot.service.copytrading.leaderpool.LeaderPoolConfirmRequiredException
|
||||
import com.wrbug.polymarketbot.service.copytrading.leaderpool.LeaderPoolDuplicateTrialConfigException
|
||||
import com.wrbug.polymarketbot.service.copytrading.leaderpool.LeaderPoolNotFoundException
|
||||
import com.wrbug.polymarketbot.service.copytrading.leaderpool.LeaderPoolResearchCandidateNotReadyException
|
||||
import com.wrbug.polymarketbot.service.copytrading.leaderpool.LeaderPoolService
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.context.MessageSource
|
||||
import org.springframework.http.ResponseEntity
|
||||
import org.springframework.web.bind.annotation.PostMapping
|
||||
import org.springframework.web.bind.annotation.RequestBody
|
||||
import org.springframework.web.bind.annotation.RequestMapping
|
||||
import org.springframework.web.bind.annotation.RestController
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/copy-trading/leader-pool")
|
||||
class LeaderPoolController(
|
||||
private val leaderPoolService: LeaderPoolService,
|
||||
private val messageSource: MessageSource
|
||||
) {
|
||||
private val logger = LoggerFactory.getLogger(LeaderPoolController::class.java)
|
||||
|
||||
@PostMapping("/list")
|
||||
fun list(@RequestBody request: LeaderPoolListRequest): ResponseEntity<ApiResponse<LeaderPoolListResponse>> {
|
||||
return try {
|
||||
leaderPoolService.getPoolList(request).fold(
|
||||
onSuccess = { ResponseEntity.ok(ApiResponse.success(it)) },
|
||||
onFailure = { e ->
|
||||
logger.error("查询 Leader 池失败: ${e.message}", e)
|
||||
errorResponse(e, ErrorCode.SERVER_LEADER_POOL_LIST_FETCH_FAILED)
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("查询 Leader 池异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_LEADER_POOL_LIST_FETCH_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/add")
|
||||
fun add(@RequestBody request: LeaderPoolAddRequest): ResponseEntity<ApiResponse<LeaderPoolItemDto>> {
|
||||
return try {
|
||||
if (request.leaderId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_LEADER_ID_INVALID, messageSource = messageSource))
|
||||
}
|
||||
leaderPoolService.addToPool(request).fold(
|
||||
onSuccess = { ResponseEntity.ok(ApiResponse.success(it)) },
|
||||
onFailure = { e ->
|
||||
logger.error("加入 Leader 池失败: ${e.message}", e)
|
||||
errorResponse(e, ErrorCode.SERVER_LEADER_POOL_SAVE_FAILED)
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("加入 Leader 池异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_LEADER_POOL_SAVE_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/update-status")
|
||||
fun updateStatus(@RequestBody request: LeaderPoolUpdateStatusRequest): ResponseEntity<ApiResponse<LeaderPoolItemDto>> {
|
||||
return try {
|
||||
if (request.poolId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_INVALID, "poolId 无效", messageSource))
|
||||
}
|
||||
if (request.status.isBlank()) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_EMPTY, "status 不能为空", messageSource))
|
||||
}
|
||||
leaderPoolService.updateStatus(request).fold(
|
||||
onSuccess = { ResponseEntity.ok(ApiResponse.success(it)) },
|
||||
onFailure = { e ->
|
||||
logger.error("更新 Leader 池状态失败: ${e.message}", e)
|
||||
errorResponse(e, ErrorCode.SERVER_LEADER_POOL_SAVE_FAILED)
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("更新 Leader 池状态异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_LEADER_POOL_SAVE_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/update-plan")
|
||||
fun updatePlan(@RequestBody request: LeaderPoolUpdatePlanRequest): ResponseEntity<ApiResponse<LeaderPoolItemDto>> {
|
||||
return try {
|
||||
if (request.poolId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_INVALID, "poolId 无效", messageSource))
|
||||
}
|
||||
leaderPoolService.updatePlan(request).fold(
|
||||
onSuccess = { ResponseEntity.ok(ApiResponse.success(it)) },
|
||||
onFailure = { e ->
|
||||
logger.error("更新 Leader 池建议配置失败: ${e.message}", e)
|
||||
errorResponse(e, ErrorCode.SERVER_LEADER_POOL_SAVE_FAILED)
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("更新 Leader 池建议配置异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_LEADER_POOL_SAVE_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/create-trial-config")
|
||||
fun createTrialConfig(@RequestBody request: LeaderPoolCreateTrialConfigRequest): ResponseEntity<ApiResponse<CopyTradingDto>> {
|
||||
return try {
|
||||
if (request.poolId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_INVALID, "poolId 无效", messageSource))
|
||||
}
|
||||
if (request.accountId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_ACCOUNT_ID_INVALID, messageSource = messageSource))
|
||||
}
|
||||
leaderPoolService.createTrialConfig(request).fold(
|
||||
onSuccess = { ResponseEntity.ok(ApiResponse.success(it)) },
|
||||
onFailure = { e ->
|
||||
logger.error("创建 Leader 池试跟配置失败: ${e.message}", e)
|
||||
errorResponse(e, ErrorCode.SERVER_LEADER_POOL_CREATE_TRIAL_FAILED)
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("创建 Leader 池试跟配置异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_LEADER_POOL_CREATE_TRIAL_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/remove")
|
||||
fun remove(@RequestBody request: LeaderPoolRemoveRequest): ResponseEntity<ApiResponse<Unit>> {
|
||||
return try {
|
||||
if (request.poolId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_INVALID, "poolId 无效", messageSource))
|
||||
}
|
||||
leaderPoolService.remove(request).fold(
|
||||
onSuccess = { ResponseEntity.ok(ApiResponse.success(Unit)) },
|
||||
onFailure = { e ->
|
||||
logger.error("移除 Leader 池项失败: ${e.message}", e)
|
||||
errorResponse(e, ErrorCode.SERVER_LEADER_POOL_SAVE_FAILED)
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("移除 Leader 池项异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_LEADER_POOL_SAVE_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
private fun mapErrorCode(e: Throwable, fallback: ErrorCode): ErrorCode {
|
||||
return when (e) {
|
||||
is LeaderPoolNotFoundException -> ErrorCode.LEADER_POOL_NOT_FOUND
|
||||
is LeaderPoolAlreadyExistsException -> ErrorCode.LEADER_POOL_ALREADY_EXISTS
|
||||
is LeaderPoolDuplicateTrialConfigException -> ErrorCode.LEADER_POOL_DUPLICATE_TRIAL_CONFIG
|
||||
is LeaderPoolConfirmRequiredException -> ErrorCode.LEADER_POOL_CONFIRM_REQUIRED
|
||||
is LeaderPoolResearchCandidateNotReadyException -> ErrorCode.LEADER_RESEARCH_CANDIDATE_NOT_READY
|
||||
is IllegalArgumentException -> when (e.message) {
|
||||
"账户不存在" -> ErrorCode.ACCOUNT_NOT_FOUND
|
||||
"Leader 不存在" -> ErrorCode.LEADER_NOT_FOUND
|
||||
else -> ErrorCode.PARAM_ERROR
|
||||
}
|
||||
else -> fallback
|
||||
}
|
||||
}
|
||||
|
||||
private fun <T> errorResponse(e: Throwable, fallback: ErrorCode): ResponseEntity<ApiResponse<T>> {
|
||||
val errorCode = mapErrorCode(e, fallback)
|
||||
val customMsg = if (usesI18nMessage(errorCode)) null else e.message
|
||||
return ResponseEntity.ok(ApiResponse.error(errorCode, customMsg, messageSource))
|
||||
}
|
||||
|
||||
private fun usesI18nMessage(errorCode: ErrorCode): Boolean {
|
||||
return errorCode == ErrorCode.LEADER_POOL_NOT_FOUND ||
|
||||
errorCode == ErrorCode.LEADER_POOL_ALREADY_EXISTS ||
|
||||
errorCode == ErrorCode.LEADER_POOL_DUPLICATE_TRIAL_CONFIG ||
|
||||
errorCode == ErrorCode.LEADER_POOL_CONFIRM_REQUIRED ||
|
||||
errorCode == ErrorCode.LEADER_RESEARCH_CANDIDATE_NOT_READY ||
|
||||
errorCode == ErrorCode.ACCOUNT_NOT_FOUND ||
|
||||
errorCode == ErrorCode.LEADER_NOT_FOUND
|
||||
}
|
||||
}
|
||||
+31
-1
@@ -140,7 +140,7 @@ class LeaderController(
|
||||
if (request.leaderId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_LEADER_ID_INVALID, messageSource = messageSource))
|
||||
}
|
||||
|
||||
|
||||
val result = leaderService.getLeaderDetail(request.leaderId)
|
||||
result.fold(
|
||||
onSuccess = { leader ->
|
||||
@@ -159,6 +159,36 @@ class LeaderController(
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_LEADER_DETAIL_FETCH_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询被跟单者余额
|
||||
*/
|
||||
@PostMapping("/balance")
|
||||
fun getLeaderBalance(@RequestBody request: LeaderBalanceRequest): ResponseEntity<ApiResponse<LeaderBalanceResponse>> {
|
||||
return try {
|
||||
if (request.leaderId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_LEADER_ID_INVALID, messageSource = messageSource))
|
||||
}
|
||||
|
||||
val result = leaderService.getLeaderBalance(request.leaderId)
|
||||
result.fold(
|
||||
onSuccess = { balance ->
|
||||
ResponseEntity.ok(ApiResponse.success(balance))
|
||||
},
|
||||
onFailure = { e ->
|
||||
logger.error("查询 Leader 余额失败: ${e.message}", e)
|
||||
when (e) {
|
||||
is IllegalArgumentException -> ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_ERROR, e.message, messageSource))
|
||||
is IllegalStateException -> ResponseEntity.ok(ApiResponse.error(ErrorCode.BUSINESS_ERROR, e.message, messageSource))
|
||||
else -> ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("查询 Leader 余额异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
package com.wrbug.polymarketbot.controller.copytrading.research
|
||||
|
||||
import com.wrbug.polymarketbot.dto.ApiResponse
|
||||
import com.wrbug.polymarketbot.dto.LeaderResearchApprovalRequest
|
||||
import com.wrbug.polymarketbot.dto.LeaderResearchApprovalResponse
|
||||
import com.wrbug.polymarketbot.dto.LeaderResearchCandidateDetailDto
|
||||
import com.wrbug.polymarketbot.dto.LeaderResearchCandidateListRequest
|
||||
import com.wrbug.polymarketbot.dto.LeaderResearchCandidateListResponse
|
||||
import com.wrbug.polymarketbot.dto.LeaderResearchEventDto
|
||||
import com.wrbug.polymarketbot.dto.LeaderPaperSessionDto
|
||||
import com.wrbug.polymarketbot.dto.LeaderResearchRunDto
|
||||
import com.wrbug.polymarketbot.dto.LeaderResearchRunRequest
|
||||
import com.wrbug.polymarketbot.dto.LeaderResearchSourceStateDto
|
||||
import com.wrbug.polymarketbot.dto.LeaderResearchSummaryDto
|
||||
import com.wrbug.polymarketbot.enums.ErrorCode
|
||||
import com.wrbug.polymarketbot.enums.LeaderResearchTriggerType
|
||||
import com.wrbug.polymarketbot.service.copytrading.research.LeaderResearchApprovalConfirmRequiredException
|
||||
import com.wrbug.polymarketbot.service.copytrading.research.LeaderResearchApprovalService
|
||||
import com.wrbug.polymarketbot.service.copytrading.research.LeaderResearchCandidateNotReadyException
|
||||
import com.wrbug.polymarketbot.service.copytrading.research.LeaderResearchCandidateLockedException
|
||||
import com.wrbug.polymarketbot.service.copytrading.research.LeaderResearchDuplicateTrialConfigException
|
||||
import com.wrbug.polymarketbot.service.copytrading.research.LeaderResearchJobService
|
||||
import com.wrbug.polymarketbot.service.copytrading.research.LeaderResearchMapper
|
||||
import com.wrbug.polymarketbot.service.copytrading.research.LeaderResearchRealMoneyForbiddenException
|
||||
import com.wrbug.polymarketbot.service.copytrading.research.LeaderResearchService
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.context.MessageSource
|
||||
import org.springframework.http.ResponseEntity
|
||||
import org.springframework.web.bind.annotation.PostMapping
|
||||
import org.springframework.web.bind.annotation.RequestBody
|
||||
import org.springframework.web.bind.annotation.RequestMapping
|
||||
import org.springframework.web.bind.annotation.RestController
|
||||
|
||||
data class LeaderResearchDetailRequest(val candidateId: Long)
|
||||
data class LeaderResearchEventsRequest(val page: Int = 0, val size: Int = 50)
|
||||
data class LeaderResearchPaperSessionsRequest(val candidateId: Long)
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/copy-trading/leader-research")
|
||||
class LeaderResearchController(
|
||||
private val jobService: LeaderResearchJobService,
|
||||
private val researchService: LeaderResearchService,
|
||||
private val approvalService: LeaderResearchApprovalService,
|
||||
private val mapper: LeaderResearchMapper,
|
||||
private val messageSource: MessageSource
|
||||
) {
|
||||
private val logger = LoggerFactory.getLogger(LeaderResearchController::class.java)
|
||||
|
||||
@PostMapping("/run")
|
||||
fun run(@RequestBody request: LeaderResearchRunRequest): ResponseEntity<ApiResponse<LeaderResearchRunDto>> {
|
||||
return try {
|
||||
val trigger = runCatching { LeaderResearchTriggerType.valueOf(request.triggerType.uppercase()) }
|
||||
.getOrDefault(LeaderResearchTriggerType.MANUAL)
|
||||
val run = if (request.dryRun || trigger == LeaderResearchTriggerType.PREVIEW) {
|
||||
jobService.runOnce(request.dryRun, trigger)
|
||||
} else {
|
||||
jobService.startAsync(request.dryRun, trigger)
|
||||
}
|
||||
ResponseEntity.ok(ApiResponse.success(mapper.runDto(run)))
|
||||
} catch (e: Exception) {
|
||||
logger.error("Leader research run failed", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_LEADER_RESEARCH_RUN_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/summary")
|
||||
fun summary(): ResponseEntity<ApiResponse<LeaderResearchSummaryDto>> {
|
||||
return safe(ErrorCode.SERVER_LEADER_RESEARCH_FETCH_FAILED) { researchService.summary() }
|
||||
}
|
||||
|
||||
@PostMapping("/candidates/list")
|
||||
fun list(@RequestBody request: LeaderResearchCandidateListRequest): ResponseEntity<ApiResponse<LeaderResearchCandidateListResponse>> {
|
||||
return safe(ErrorCode.SERVER_LEADER_RESEARCH_FETCH_FAILED) { researchService.listCandidates(request) }
|
||||
}
|
||||
|
||||
@PostMapping("/candidates/detail")
|
||||
fun detail(@RequestBody request: LeaderResearchDetailRequest): ResponseEntity<ApiResponse<LeaderResearchCandidateDetailDto>> {
|
||||
if (request.candidateId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_INVALID, "candidateId 无效", messageSource))
|
||||
}
|
||||
return safe(ErrorCode.SERVER_LEADER_RESEARCH_FETCH_FAILED) { researchService.detail(request.candidateId) }
|
||||
}
|
||||
|
||||
@PostMapping("/paper-sessions")
|
||||
fun paperSessions(@RequestBody request: LeaderResearchPaperSessionsRequest): ResponseEntity<ApiResponse<List<LeaderPaperSessionDto>>> {
|
||||
if (request.candidateId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_INVALID, "candidateId 无效", messageSource))
|
||||
}
|
||||
return safe(ErrorCode.SERVER_LEADER_RESEARCH_FETCH_FAILED) { researchService.paperSessions(request.candidateId) }
|
||||
}
|
||||
|
||||
@PostMapping("/source-health")
|
||||
fun sourceHealth(): ResponseEntity<ApiResponse<List<LeaderResearchSourceStateDto>>> {
|
||||
return safe(ErrorCode.SERVER_LEADER_RESEARCH_FETCH_FAILED) { researchService.sourceHealth() }
|
||||
}
|
||||
|
||||
@PostMapping("/events/list")
|
||||
fun events(@RequestBody request: LeaderResearchEventsRequest): ResponseEntity<ApiResponse<List<LeaderResearchEventDto>>> {
|
||||
return safe(ErrorCode.SERVER_LEADER_RESEARCH_FETCH_FAILED) { researchService.events(request.page, request.size) }
|
||||
}
|
||||
|
||||
@PostMapping("/approval/create-disabled-trial-config")
|
||||
fun approve(@RequestBody request: LeaderResearchApprovalRequest): ResponseEntity<ApiResponse<LeaderResearchApprovalResponse>> {
|
||||
if (request.candidateId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_INVALID, "candidateId 无效", messageSource))
|
||||
}
|
||||
if (request.accountId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_ACCOUNT_ID_INVALID, messageSource = messageSource))
|
||||
}
|
||||
return try {
|
||||
approvalService.createDisabledTrialConfig(request).fold(
|
||||
onSuccess = { ResponseEntity.ok(ApiResponse.success(it)) },
|
||||
onFailure = { e -> errorResponse(e, ErrorCode.SERVER_LEADER_RESEARCH_APPROVAL_FAILED) }
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("Leader research approval failed", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_LEADER_RESEARCH_APPROVAL_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
private fun <T> safe(errorCode: ErrorCode, block: () -> T): ResponseEntity<ApiResponse<T>> {
|
||||
return try {
|
||||
ResponseEntity.ok(ApiResponse.success(block()))
|
||||
} catch (e: Exception) {
|
||||
logger.error("Leader research request failed", e)
|
||||
ResponseEntity.ok(ApiResponse.error(errorCode, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
private fun <T> errorResponse(e: Throwable, fallback: ErrorCode): ResponseEntity<ApiResponse<T>> {
|
||||
val errorCode = when (e) {
|
||||
is LeaderResearchCandidateNotReadyException -> ErrorCode.LEADER_RESEARCH_CANDIDATE_NOT_READY
|
||||
is LeaderResearchApprovalConfirmRequiredException -> ErrorCode.LEADER_RESEARCH_APPROVAL_CONFIRM_REQUIRED
|
||||
is LeaderResearchDuplicateTrialConfigException -> ErrorCode.LEADER_RESEARCH_DUPLICATE_TRIAL_CONFIG
|
||||
is LeaderResearchRealMoneyForbiddenException -> ErrorCode.LEADER_RESEARCH_REAL_MONEY_FORBIDDEN
|
||||
is LeaderResearchCandidateLockedException -> ErrorCode.LEADER_RESEARCH_CANDIDATE_LOCKED
|
||||
is IllegalArgumentException -> when (e.message) {
|
||||
"账户不存在" -> ErrorCode.ACCOUNT_NOT_FOUND
|
||||
"候选不存在" -> ErrorCode.LEADER_RESEARCH_CANDIDATE_NOT_FOUND
|
||||
else -> ErrorCode.PARAM_ERROR
|
||||
}
|
||||
else -> fallback
|
||||
}
|
||||
return ResponseEntity.ok(ApiResponse.error(errorCode, null, messageSource))
|
||||
}
|
||||
}
|
||||
+46
@@ -200,5 +200,51 @@ class CopyOrderTrackingController(
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ORDER_TRACKING_LIST_FETCH_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询按市场分组的订单列表(买入/卖出)
|
||||
* POST /api/copy-trading/orders/grouped-by-market
|
||||
*/
|
||||
@PostMapping("/grouped-by-market")
|
||||
fun getOrderListGroupedByMarket(@RequestBody request: MarketGroupedOrdersRequest): ResponseEntity<ApiResponse<MarketGroupedOrdersResponse>> {
|
||||
return try {
|
||||
if (request.copyTradingId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_COPY_TRADING_ID_INVALID, messageSource = messageSource))
|
||||
}
|
||||
|
||||
if (request.type.isBlank()) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_EMPTY, "订单类型不能为空", messageSource))
|
||||
}
|
||||
|
||||
val validTypes = listOf("buy", "sell")
|
||||
if (!validTypes.contains(request.type.lowercase())) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_ERROR, "订单类型必须是 buy 或 sell", messageSource))
|
||||
}
|
||||
|
||||
val result: Result<MarketGroupedOrdersResponse> = runBlocking {
|
||||
when (request.type.lowercase()) {
|
||||
"buy" -> statisticsService.getBuyOrderListGroupedByMarket(request)
|
||||
"sell" -> statisticsService.getSellOrderListGroupedByMarket(request)
|
||||
else -> Result.failure(IllegalArgumentException("不支持的订单类型: ${request.type}"))
|
||||
}
|
||||
}
|
||||
|
||||
result.fold(
|
||||
onSuccess = { response: MarketGroupedOrdersResponse ->
|
||||
ResponseEntity.ok(ApiResponse.success(response))
|
||||
},
|
||||
onFailure = { e: Throwable ->
|
||||
logger.error("查询按市场分组的订单列表失败: copyTradingId=${request.copyTradingId}, type=${request.type}", e)
|
||||
when (e) {
|
||||
is IllegalArgumentException -> ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_ERROR, e.message, messageSource))
|
||||
else -> ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ORDER_TRACKING_LIST_FETCH_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("查询按市场分组的订单列表异常: copyTradingId=${request.copyTradingId}, type=${request.type}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ORDER_TRACKING_LIST_FETCH_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
package com.wrbug.polymarketbot.controller.cryptotail
|
||||
|
||||
import com.wrbug.polymarketbot.dto.ApiResponse
|
||||
import com.wrbug.polymarketbot.dto.CryptoTailStrategyCreateRequest
|
||||
import com.wrbug.polymarketbot.dto.CryptoTailStrategyDeleteRequest
|
||||
import com.wrbug.polymarketbot.dto.CryptoTailStrategyDto
|
||||
import com.wrbug.polymarketbot.dto.CryptoTailStrategyListRequest
|
||||
import com.wrbug.polymarketbot.dto.CryptoTailStrategyListResponse
|
||||
import com.wrbug.polymarketbot.dto.CryptoTailStrategyTriggerListRequest
|
||||
import com.wrbug.polymarketbot.dto.CryptoTailStrategyTriggerListResponse
|
||||
import com.wrbug.polymarketbot.dto.CryptoTailStrategyUpdateRequest
|
||||
import com.wrbug.polymarketbot.dto.CryptoTailMarketOptionDto
|
||||
import com.wrbug.polymarketbot.dto.CryptoTailAutoMinSpreadResponse
|
||||
import com.wrbug.polymarketbot.dto.CryptoTailMonitorInitRequest
|
||||
import com.wrbug.polymarketbot.dto.CryptoTailMonitorInitResponse
|
||||
import com.wrbug.polymarketbot.dto.CryptoTailManualOrderRequest
|
||||
import com.wrbug.polymarketbot.dto.CryptoTailManualOrderResponse
|
||||
import com.wrbug.polymarketbot.dto.CryptoTailPnlCurveRequest
|
||||
import com.wrbug.polymarketbot.dto.CryptoTailPnlCurveResponse
|
||||
import com.wrbug.polymarketbot.enums.ErrorCode
|
||||
import com.wrbug.polymarketbot.service.binance.BinanceKlineAutoSpreadService
|
||||
import com.wrbug.polymarketbot.service.cryptotail.CryptoTailStrategyService
|
||||
import com.wrbug.polymarketbot.service.cryptotail.CryptoTailMonitorService
|
||||
import com.wrbug.polymarketbot.service.cryptotail.CryptoTailStrategyExecutionService
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.context.MessageSource
|
||||
import org.springframework.http.ResponseEntity
|
||||
import org.springframework.web.bind.annotation.PostMapping
|
||||
import org.springframework.web.bind.annotation.RequestBody
|
||||
import org.springframework.web.bind.annotation.RequestMapping
|
||||
import org.springframework.web.bind.annotation.RestController
|
||||
import kotlinx.coroutines.runBlocking
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/crypto-tail-strategy")
|
||||
class CryptoTailStrategyController(
|
||||
private val cryptoTailStrategyService: CryptoTailStrategyService,
|
||||
private val cryptoTailMonitorService: CryptoTailMonitorService,
|
||||
private val cryptoTailStrategyExecutionService: CryptoTailStrategyExecutionService,
|
||||
private val binanceKlineAutoSpreadService: BinanceKlineAutoSpreadService,
|
||||
private val messageSource: MessageSource
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(CryptoTailStrategyController::class.java)
|
||||
|
||||
@PostMapping("/list")
|
||||
fun list(@RequestBody request: CryptoTailStrategyListRequest): ResponseEntity<ApiResponse<CryptoTailStrategyListResponse>> {
|
||||
return try {
|
||||
val result = cryptoTailStrategyService.list(request)
|
||||
result.fold(
|
||||
onSuccess = { ResponseEntity.ok(ApiResponse.success(it)) },
|
||||
onFailure = { e ->
|
||||
logger.error("查询加密价差策略列表失败: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_CRYPTO_TAIL_STRATEGY_LIST_FETCH_FAILED, e.message, messageSource))
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("查询加密价差策略列表异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_CRYPTO_TAIL_STRATEGY_LIST_FETCH_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/create")
|
||||
fun create(@RequestBody request: CryptoTailStrategyCreateRequest): ResponseEntity<ApiResponse<CryptoTailStrategyDto>> {
|
||||
return try {
|
||||
val result = cryptoTailStrategyService.create(request)
|
||||
result.fold(
|
||||
onSuccess = { ResponseEntity.ok(ApiResponse.success(it)) },
|
||||
onFailure = { e ->
|
||||
logger.error("创建加密价差策略失败: ${e.message}", e)
|
||||
val code = when (e.message) {
|
||||
ErrorCode.CRYPTO_TAIL_STRATEGY_WINDOW_INVALID.messageKey -> ErrorCode.CRYPTO_TAIL_STRATEGY_WINDOW_INVALID
|
||||
ErrorCode.CRYPTO_TAIL_STRATEGY_WINDOW_EXCEED.messageKey -> ErrorCode.CRYPTO_TAIL_STRATEGY_WINDOW_EXCEED
|
||||
ErrorCode.CRYPTO_TAIL_STRATEGY_INTERVAL_INVALID.messageKey -> ErrorCode.CRYPTO_TAIL_STRATEGY_INTERVAL_INVALID
|
||||
ErrorCode.CRYPTO_TAIL_STRATEGY_AMOUNT_MODE_INVALID.messageKey -> ErrorCode.CRYPTO_TAIL_STRATEGY_AMOUNT_MODE_INVALID
|
||||
else -> ErrorCode.SERVER_CRYPTO_TAIL_STRATEGY_CREATE_FAILED
|
||||
}
|
||||
ResponseEntity.ok(ApiResponse.error(code, messageSource = messageSource))
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("创建加密价差策略异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_CRYPTO_TAIL_STRATEGY_CREATE_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/update")
|
||||
fun update(@RequestBody request: CryptoTailStrategyUpdateRequest): ResponseEntity<ApiResponse<CryptoTailStrategyDto>> {
|
||||
return try {
|
||||
if (request.strategyId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.CRYPTO_TAIL_STRATEGY_NOT_FOUND, messageSource = messageSource))
|
||||
}
|
||||
val result = cryptoTailStrategyService.update(request)
|
||||
result.fold(
|
||||
onSuccess = { ResponseEntity.ok(ApiResponse.success(it)) },
|
||||
onFailure = { e ->
|
||||
logger.error("更新加密价差策略失败: ${e.message}", e)
|
||||
val code = when (e.message) {
|
||||
ErrorCode.CRYPTO_TAIL_STRATEGY_NOT_FOUND.messageKey -> ErrorCode.CRYPTO_TAIL_STRATEGY_NOT_FOUND
|
||||
ErrorCode.CRYPTO_TAIL_STRATEGY_WINDOW_INVALID.messageKey -> ErrorCode.CRYPTO_TAIL_STRATEGY_WINDOW_INVALID
|
||||
ErrorCode.CRYPTO_TAIL_STRATEGY_WINDOW_EXCEED.messageKey -> ErrorCode.CRYPTO_TAIL_STRATEGY_WINDOW_EXCEED
|
||||
ErrorCode.CRYPTO_TAIL_STRATEGY_AMOUNT_MODE_INVALID.messageKey -> ErrorCode.CRYPTO_TAIL_STRATEGY_AMOUNT_MODE_INVALID
|
||||
else -> ErrorCode.SERVER_CRYPTO_TAIL_STRATEGY_UPDATE_FAILED
|
||||
}
|
||||
ResponseEntity.ok(ApiResponse.error(code, messageSource = messageSource))
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("更新加密价差策略异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_CRYPTO_TAIL_STRATEGY_UPDATE_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/delete")
|
||||
fun delete(@RequestBody request: CryptoTailStrategyDeleteRequest): ResponseEntity<ApiResponse<Unit>> {
|
||||
return try {
|
||||
val strategyId = request.strategyId
|
||||
if (strategyId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.CRYPTO_TAIL_STRATEGY_NOT_FOUND, messageSource = messageSource))
|
||||
}
|
||||
val result = cryptoTailStrategyService.delete(strategyId)
|
||||
result.fold(
|
||||
onSuccess = { ResponseEntity.ok(ApiResponse.success(Unit)) },
|
||||
onFailure = { e ->
|
||||
logger.error("删除加密价差策略失败: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_CRYPTO_TAIL_STRATEGY_DELETE_FAILED, e.message, messageSource))
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("删除加密价差策略异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_CRYPTO_TAIL_STRATEGY_DELETE_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/pnl-curve")
|
||||
fun getPnlCurve(@RequestBody request: CryptoTailPnlCurveRequest): ResponseEntity<ApiResponse<CryptoTailPnlCurveResponse>> {
|
||||
return try {
|
||||
if (request.strategyId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.CRYPTO_TAIL_STRATEGY_NOT_FOUND, messageSource = messageSource))
|
||||
}
|
||||
val result = cryptoTailStrategyService.getPnlCurve(request)
|
||||
result.fold(
|
||||
onSuccess = { ResponseEntity.ok(ApiResponse.success(it)) },
|
||||
onFailure = { e ->
|
||||
logger.error("查询收益曲线失败: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_CRYPTO_TAIL_STRATEGY_TRIGGERS_FETCH_FAILED, e.message, messageSource))
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("查询收益曲线异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_CRYPTO_TAIL_STRATEGY_TRIGGERS_FETCH_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/triggers")
|
||||
fun getTriggerRecords(@RequestBody request: CryptoTailStrategyTriggerListRequest): ResponseEntity<ApiResponse<CryptoTailStrategyTriggerListResponse>> {
|
||||
return try {
|
||||
if (request.strategyId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.CRYPTO_TAIL_STRATEGY_NOT_FOUND, messageSource = messageSource))
|
||||
}
|
||||
val result = cryptoTailStrategyService.getTriggerRecords(request)
|
||||
result.fold(
|
||||
onSuccess = { ResponseEntity.ok(ApiResponse.success(it)) },
|
||||
onFailure = { e ->
|
||||
logger.error("查询触发记录失败: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_CRYPTO_TAIL_STRATEGY_TRIGGERS_FETCH_FAILED, e.message, messageSource))
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("查询触发记录异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_CRYPTO_TAIL_STRATEGY_TRIGGERS_FETCH_FAILED, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/market-options")
|
||||
fun getMarketOptions(): ResponseEntity<ApiResponse<List<CryptoTailMarketOptionDto>>> {
|
||||
return try {
|
||||
val options = listOf(
|
||||
CryptoTailMarketOptionDto(slug = "btc-updown-5m", title = "Bitcoin Up or Down - 5 minute", intervalSeconds = 300, periodStartUnix = 0L, endDate = null),
|
||||
CryptoTailMarketOptionDto(slug = "btc-updown-15m", title = "Bitcoin Up or Down - 15 minute", intervalSeconds = 900, periodStartUnix = 0L, endDate = null),
|
||||
CryptoTailMarketOptionDto(slug = "eth-updown-5m", title = "Ethereum Up or Down - 5 minute", intervalSeconds = 300, periodStartUnix = 0L, endDate = null),
|
||||
CryptoTailMarketOptionDto(slug = "eth-updown-15m", title = "Ethereum Up or Down - 15 minute", intervalSeconds = 900, periodStartUnix = 0L, endDate = null),
|
||||
CryptoTailMarketOptionDto(slug = "sol-updown-5m", title = "Solana Up or Down - 5 minute", intervalSeconds = 300, periodStartUnix = 0L, endDate = null),
|
||||
CryptoTailMarketOptionDto(slug = "sol-updown-15m", title = "Solana Up or Down - 15 minute", intervalSeconds = 900, periodStartUnix = 0L, endDate = null),
|
||||
CryptoTailMarketOptionDto(slug = "xrp-updown-5m", title = "XRP Up or Down - 5 minute", intervalSeconds = 300, periodStartUnix = 0L, endDate = null),
|
||||
CryptoTailMarketOptionDto(slug = "xrp-updown-15m", title = "XRP Up or Down - 15 minute", intervalSeconds = 900, periodStartUnix = 0L, endDate = null)
|
||||
)
|
||||
ResponseEntity.ok(ApiResponse.success(options))
|
||||
} catch (e: Exception) {
|
||||
logger.error("获取市场选项异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动最小价差预览:按「当前周期」计算一次并返回,仅用于前端展示参考。
|
||||
* 实际触发时按每个周期在需要时计算,不依赖此接口。
|
||||
*/
|
||||
@PostMapping("/auto-min-spread")
|
||||
fun getAutoMinSpread(@RequestBody request: java.util.Map<String, Any>): ResponseEntity<ApiResponse<CryptoTailAutoMinSpreadResponse>> {
|
||||
return try {
|
||||
val intervalSeconds = (request["intervalSeconds"] as? Number)?.toInt() ?: 300
|
||||
if (intervalSeconds != 300 && intervalSeconds != 900) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_ERROR, messageSource = messageSource))
|
||||
}
|
||||
val periodStartUnix = (request["periodStartUnix"] as? Number)?.toLong()
|
||||
?: ((System.currentTimeMillis() / 1000 / intervalSeconds) * intervalSeconds)
|
||||
// 默认使用 BTC 市场(向后兼容)
|
||||
val marketSlugPrefix = (request["marketSlugPrefix"] as? String) ?: "btc-updown"
|
||||
val pair = binanceKlineAutoSpreadService.computeAndCache(marketSlugPrefix, intervalSeconds, periodStartUnix)
|
||||
?: return ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, "fetch_failed", messageSource))
|
||||
val body = CryptoTailAutoMinSpreadResponse(
|
||||
minSpreadUp = pair.first.toPlainString(),
|
||||
minSpreadDown = pair.second.toPlainString()
|
||||
)
|
||||
ResponseEntity.ok(ApiResponse.success(body))
|
||||
} catch (e: Exception) {
|
||||
logger.error("计算自动最小价差异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化加密价差策略监控
|
||||
* 返回策略信息、开盘价、tokenIds等初始化数据
|
||||
*/
|
||||
@PostMapping("/monitor/init")
|
||||
fun initMonitor(@RequestBody request: CryptoTailMonitorInitRequest): ResponseEntity<ApiResponse<CryptoTailMonitorInitResponse>> {
|
||||
return try {
|
||||
if (request.strategyId <= 0) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.CRYPTO_TAIL_STRATEGY_NOT_FOUND, messageSource = messageSource))
|
||||
}
|
||||
val result = cryptoTailMonitorService.initMonitor(request)
|
||||
result.fold(
|
||||
onSuccess = { ResponseEntity.ok(ApiResponse.success(it)) },
|
||||
onFailure = { e ->
|
||||
logger.error("初始化加密价差策略监控失败: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, e.message, messageSource))
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("初始化加密价差策略监控异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动下单
|
||||
* 用户主动触发下单,不检查任何条件,仅检查当前周期是否已下单
|
||||
*/
|
||||
@PostMapping("/manual-order")
|
||||
fun manualOrder(@RequestBody request: CryptoTailManualOrderRequest): ResponseEntity<ApiResponse<CryptoTailManualOrderResponse>> {
|
||||
return runBlocking {
|
||||
try {
|
||||
if (request.strategyId <= 0) {
|
||||
return@runBlocking ResponseEntity.ok(
|
||||
ApiResponse.error(ErrorCode.CRYPTO_TAIL_STRATEGY_NOT_FOUND, messageSource = messageSource)
|
||||
)
|
||||
}
|
||||
val result = cryptoTailStrategyExecutionService.manualOrder(request)
|
||||
result.fold(
|
||||
onSuccess = { ResponseEntity.ok(ApiResponse.success(it)) },
|
||||
onFailure = { e ->
|
||||
logger.error("手动下单失败: ${e.message}", e)
|
||||
val code = when (e.message) {
|
||||
"策略不存在" -> ErrorCode.CRYPTO_TAIL_STRATEGY_NOT_FOUND
|
||||
"当前周期已下单" -> ErrorCode.PARAM_ERROR
|
||||
"价格必须在 0~1 之间" -> ErrorCode.PARAM_ERROR
|
||||
"数量不能少于 1" -> ErrorCode.PARAM_ERROR
|
||||
"总金额不能少于 $1" -> ErrorCode.PARAM_ERROR
|
||||
"总金额超过策略配置的投入金额" -> ErrorCode.PARAM_ERROR
|
||||
else -> ErrorCode.SERVER_ERROR
|
||||
}
|
||||
ResponseEntity.ok(ApiResponse.error(code, e.message, messageSource))
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("手动下单异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+166
@@ -3,6 +3,7 @@ package com.wrbug.polymarketbot.controller.system
|
||||
import com.wrbug.polymarketbot.dto.*
|
||||
import com.wrbug.polymarketbot.enums.ErrorCode
|
||||
import com.wrbug.polymarketbot.service.system.NotificationConfigService
|
||||
import com.wrbug.polymarketbot.service.system.NotificationTemplateService
|
||||
import com.wrbug.polymarketbot.service.system.TelegramNotificationService
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.slf4j.LoggerFactory
|
||||
@@ -18,6 +19,7 @@ import org.springframework.web.bind.annotation.*
|
||||
class NotificationController(
|
||||
private val notificationConfigService: NotificationConfigService,
|
||||
private val telegramNotificationService: TelegramNotificationService,
|
||||
private val notificationTemplateService: NotificationTemplateService,
|
||||
private val messageSource: MessageSource
|
||||
) {
|
||||
|
||||
@@ -335,6 +337,155 @@ class NotificationController(
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 模板相关 API ====================
|
||||
|
||||
/**
|
||||
* 获取所有模板类型
|
||||
*/
|
||||
@PostMapping("/templates/types")
|
||||
fun getTemplateTypes(): ResponseEntity<ApiResponse<List<TemplateTypeInfoDto>>> {
|
||||
return try {
|
||||
val types = notificationTemplateService.getTemplateTypes()
|
||||
ResponseEntity.ok(ApiResponse.success(types))
|
||||
} catch (e: Exception) {
|
||||
logger.error("获取模板类型失败: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, messageSource = messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有模板
|
||||
*/
|
||||
@PostMapping("/templates/list")
|
||||
fun getTemplates(): ResponseEntity<ApiResponse<List<NotificationTemplateDto>>> {
|
||||
return try {
|
||||
val templates = notificationTemplateService.getAllTemplates()
|
||||
ResponseEntity.ok(ApiResponse.success(templates))
|
||||
} catch (e: Exception) {
|
||||
logger.error("获取模板列表失败: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, messageSource = messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取单个模板
|
||||
*/
|
||||
@PostMapping("/templates/detail")
|
||||
fun getTemplateDetail(@RequestBody request: TemplateDetailRequest): ResponseEntity<ApiResponse<NotificationTemplateDto>> {
|
||||
return try {
|
||||
if (request.templateType.isBlank()) {
|
||||
return ResponseEntity.ok(ApiResponse.paramError("模板类型不能为空"))
|
||||
}
|
||||
|
||||
val template = notificationTemplateService.getTemplate(request.templateType)
|
||||
if (template == null) {
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.NOT_FOUND, messageSource = messageSource))
|
||||
} else {
|
||||
ResponseEntity.ok(ApiResponse.success(template))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("获取模板详情失败: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, messageSource = messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取模板可用变量
|
||||
*/
|
||||
@PostMapping("/templates/variables")
|
||||
fun getTemplateVariables(@RequestBody request: TemplateDetailRequest): ResponseEntity<ApiResponse<TemplateVariablesResponse>> {
|
||||
return try {
|
||||
if (request.templateType.isBlank()) {
|
||||
return ResponseEntity.ok(ApiResponse.paramError("模板类型不能为空"))
|
||||
}
|
||||
|
||||
val variables = notificationTemplateService.getTemplateVariables(request.templateType)
|
||||
if (variables == null) {
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.NOT_FOUND, messageSource = messageSource))
|
||||
} else {
|
||||
ResponseEntity.ok(ApiResponse.success(variables))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("获取模板变量失败: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, messageSource = messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新模板
|
||||
*/
|
||||
@PostMapping("/templates/update")
|
||||
fun updateTemplate(@RequestBody request: UpdateTemplateRequestWithId): ResponseEntity<ApiResponse<NotificationTemplateDto>> {
|
||||
return try {
|
||||
if (request.templateType.isBlank()) {
|
||||
return ResponseEntity.ok(ApiResponse.paramError("模板类型不能为空"))
|
||||
}
|
||||
if (request.templateContent.isBlank()) {
|
||||
return ResponseEntity.ok(ApiResponse.paramError("模板内容不能为空"))
|
||||
}
|
||||
|
||||
val template = notificationTemplateService.updateTemplate(request.templateType, request.templateContent)
|
||||
ResponseEntity.ok(ApiResponse.success(template))
|
||||
} catch (e: Exception) {
|
||||
logger.error("更新模板失败: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, messageSource = messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置模板为默认
|
||||
*/
|
||||
@PostMapping("/templates/reset")
|
||||
fun resetTemplate(@RequestBody request: TemplateDetailRequest): ResponseEntity<ApiResponse<NotificationTemplateDto>> {
|
||||
return try {
|
||||
if (request.templateType.isBlank()) {
|
||||
return ResponseEntity.ok(ApiResponse.paramError("模板类型不能为空"))
|
||||
}
|
||||
|
||||
val template = notificationTemplateService.resetTemplate(request.templateType)
|
||||
if (template == null) {
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.NOT_FOUND, messageSource = messageSource))
|
||||
} else {
|
||||
ResponseEntity.ok(ApiResponse.success(template))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("重置模板失败: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, messageSource = messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送模板测试消息
|
||||
*/
|
||||
@PostMapping("/templates/test")
|
||||
fun testTemplate(@RequestBody request: TestTemplateRequest): ResponseEntity<ApiResponse<Boolean>> {
|
||||
return try {
|
||||
if (request.templateType.isBlank()) {
|
||||
return ResponseEntity.ok(ApiResponse.paramError("模板类型不能为空"))
|
||||
}
|
||||
|
||||
val success = runBlocking {
|
||||
notificationTemplateService.sendTestMessage(request.templateType, request.templateContent)
|
||||
}
|
||||
|
||||
if (success) {
|
||||
ResponseEntity.ok(ApiResponse.success(true))
|
||||
} else {
|
||||
ResponseEntity.ok(ApiResponse.error(
|
||||
ErrorCode.NOTIFICATION_TEST_FAILED,
|
||||
messageSource = messageSource
|
||||
))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("发送模板测试消息失败: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(
|
||||
ErrorCode.NOTIFICATION_TEST_FAILED,
|
||||
customMsg = "发送测试消息失败:${e.message}",
|
||||
messageSource = messageSource
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -384,3 +535,18 @@ data class NotificationConfigDeleteRequest(
|
||||
val id: Long
|
||||
)
|
||||
|
||||
/**
|
||||
* 模板详情请求
|
||||
*/
|
||||
data class TemplateDetailRequest(
|
||||
val templateType: String
|
||||
)
|
||||
|
||||
/**
|
||||
* 更新模板请求(带类型)
|
||||
*/
|
||||
data class UpdateTemplateRequestWithId(
|
||||
val templateType: String,
|
||||
val templateContent: String
|
||||
)
|
||||
|
||||
|
||||
@@ -11,6 +11,37 @@ data class AccountImportRequest(
|
||||
val walletType: String = "magic" // 钱包类型:magic(邮箱/OAuth登录)或 safe(MetaMask浏览器钱包)
|
||||
)
|
||||
|
||||
/**
|
||||
* 检查代理地址选项请求
|
||||
*/
|
||||
data class CheckProxyOptionsRequest(
|
||||
val walletAddress: String, // EOA 地址(必需)
|
||||
val privateKey: String? = null, // 私钥(加密,私钥导入时提供)
|
||||
val mnemonic: String? = null // 助记词(加密,助记词导入时提供)
|
||||
)
|
||||
|
||||
/**
|
||||
* 代理地址选项信息
|
||||
*/
|
||||
data class ProxyOptionDto(
|
||||
val walletType: String, // "magic" 或 "safe"
|
||||
val proxyAddress: String, // 代理地址
|
||||
val descriptionKey: String, // 说明文案的多语言 key(如 "accountImport.proxyOption.magic.description")
|
||||
val availableBalance: String, // 可用余额
|
||||
val positionBalance: String, // 仓位余额
|
||||
val totalBalance: String, // 总余额
|
||||
val positionCount: Int, // 持仓数量
|
||||
val hasAssets: Boolean, // 是否有资产(余额>0 或持仓>0)
|
||||
val error: String? = null // 获取失败时的错误信息(可选)
|
||||
)
|
||||
|
||||
/**
|
||||
* 检查代理地址选项响应
|
||||
*/
|
||||
data class CheckProxyOptionsResponse(
|
||||
val options: List<ProxyOptionDto> // 代理地址选项列表(私钥导入返回2个,助记词返回1个)
|
||||
)
|
||||
|
||||
/**
|
||||
* 账户更新请求
|
||||
*/
|
||||
@@ -37,9 +68,9 @@ data class SystemConfigDto(
|
||||
val builderApiKeyConfigured: Boolean, // Builder API Key 是否已配置
|
||||
val builderSecretConfigured: Boolean, // Builder Secret 是否已配置
|
||||
val builderPassphraseConfigured: Boolean, // Builder Passphrase 是否已配置
|
||||
val builderApiKeyDisplay: String? = null, // Builder API Key 显示值(部分显示,用于前端展示)
|
||||
val builderSecretDisplay: String? = null, // Builder Secret 显示值(部分显示,用于前端展示)
|
||||
val builderPassphraseDisplay: String? = null, // Builder Passphrase 显示值(部分显示,用于前端展示)
|
||||
val builderApiKeyDisplay: String? = null, // Builder API Key 显示值(完整,用于前端展示)
|
||||
val builderSecretDisplay: String? = null, // Builder Secret 显示值(完整,用于前端展示)
|
||||
val builderPassphraseDisplay: String? = null, // Builder Passphrase 显示值(完整,用于前端展示)
|
||||
val autoRedeemEnabled: Boolean = true // 自动赎回(系统级别配置,默认开启)
|
||||
)
|
||||
|
||||
@@ -93,6 +124,16 @@ data class AccountListResponse(
|
||||
val total: Long
|
||||
)
|
||||
|
||||
/**
|
||||
* 钱包余额响应(通用类,用于 Account 和 Leader)
|
||||
*/
|
||||
data class WalletBalanceResponse(
|
||||
val availableBalance: String, // 可用余额(RPC 查询的 USDC 余额)
|
||||
val positionBalance: String, // 仓位余额(持仓总价值)
|
||||
val totalBalance: String, // 总余额 = 可用余额 + 仓位余额
|
||||
val positions: List<PositionDto> = emptyList()
|
||||
)
|
||||
|
||||
/**
|
||||
* 账户余额响应
|
||||
*/
|
||||
@@ -108,6 +149,7 @@ data class AccountBalanceResponse(
|
||||
*/
|
||||
data class PositionDto(
|
||||
val marketId: String,
|
||||
val title: String?, // 市场名称
|
||||
val side: String, // YES 或 NO
|
||||
val quantity: String,
|
||||
val avgPrice: String,
|
||||
@@ -125,7 +167,8 @@ data class AccountPositionDto(
|
||||
val proxyAddress: String,
|
||||
val marketId: String,
|
||||
val marketTitle: String?,
|
||||
val marketSlug: String?,
|
||||
val marketSlug: String?, // 显示用的 slug
|
||||
val eventSlug: String? = null, // 跳转用的 slug(从 events[0].slug 获取)
|
||||
val marketIcon: String?, // 市场图标 URL
|
||||
val side: String, // 结果名称(如 "YES", "NO", "Pakistan" 等)
|
||||
val outcomeIndex: Int? = null, // 结果索引(0, 1, 2...),用于计算 tokenId
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.wrbug.polymarketbot.dto
|
||||
|
||||
/**
|
||||
* 账户设置状态检查结果
|
||||
*/
|
||||
data class AccountSetupStatusDto(
|
||||
/**
|
||||
* 步骤1:代理钱包是否已部署
|
||||
*/
|
||||
val proxyDeployed: Boolean,
|
||||
|
||||
/**
|
||||
* 步骤2:交易是否已启用(API Key 是否已配置)
|
||||
*/
|
||||
val tradingEnabled: Boolean,
|
||||
|
||||
/**
|
||||
* 步骤3:代币是否已批准
|
||||
*/
|
||||
val tokensApproved: Boolean,
|
||||
|
||||
/**
|
||||
* 代币批准详情(各合约的授权额度)
|
||||
* Key: 合约名称(CTF_CONTRACT, CTF_EXCHANGE, NEG_RISK_EXCHANGE, NEG_RISK_ADAPTER)
|
||||
* Value: 授权额度(USDC,6位小数)
|
||||
*/
|
||||
val approvalDetails: Map<String, String>? = null,
|
||||
|
||||
/**
|
||||
* 检查错误信息(如果有)
|
||||
*/
|
||||
val error: String? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 执行设置步骤请求
|
||||
*/
|
||||
data class ExecuteSetupStepRequest(
|
||||
/** 账户 ID */
|
||||
val accountId: Long? = null,
|
||||
/** 步骤:1=部署代理, 2=启用交易, 3=批准代币 */
|
||||
val step: Int? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 执行设置步骤响应
|
||||
*/
|
||||
data class ExecuteSetupStepResponse(
|
||||
/** 是否由后端执行成功(步骤1 仅返回跳转链接,为 false) */
|
||||
val success: Boolean = false,
|
||||
/** 需跳转时由后端提供的 URL(步骤1 使用) */
|
||||
val redirectUrl: String? = null,
|
||||
/** 链上交易哈希(步骤3 批准代币成功时返回) */
|
||||
val transactionHash: String? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 账户导入响应(扩展,包含设置状态)
|
||||
*/
|
||||
data class AccountImportResponse(
|
||||
val account: AccountDto,
|
||||
val setupStatus: AccountSetupStatusDto? = null // 设置状态检查结果(可选)
|
||||
)
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.wrbug.polymarketbot.dto
|
||||
|
||||
import com.google.gson.annotations.SerializedName
|
||||
|
||||
/**
|
||||
* Activity WebSocket 交易消息 DTO
|
||||
* 根据 Polymarket RTDS Activity WebSocket API 格式定义
|
||||
*/
|
||||
data class ActivityTradeMessage(
|
||||
val topic: String = "", // "activity"
|
||||
val type: String = "", // "trades"
|
||||
val timestamp: Long? = null, // 消息时间戳(可选)
|
||||
@SerializedName("connection_id")
|
||||
val connectionId: String? = null, // 连接 ID(可选,由服务器返回)
|
||||
val payload: ActivityTradePayload = ActivityTradePayload() // 交易数据
|
||||
)
|
||||
|
||||
/**
|
||||
* Activity Trade Payload
|
||||
*/
|
||||
data class ActivityTradePayload(
|
||||
val asset: String = "", // Token ID (用于下单)
|
||||
|
||||
@SerializedName("conditionId")
|
||||
val conditionId: String = "", // Market condition ID
|
||||
|
||||
@SerializedName("eventSlug")
|
||||
val eventSlug: String? = null, // 事件 slug
|
||||
|
||||
val slug: String? = null, // 市场 slug
|
||||
|
||||
val outcome: String? = null, // 结果方向 (Yes/No/Up/Down)
|
||||
|
||||
@SerializedName("outcomeIndex")
|
||||
val outcomeIndex: Int? = null, // 结果索引 (0=Yes/Up, 1=No/Down) - 优先使用此字段
|
||||
|
||||
val side: String = "", // 交易方向 (BUY/SELL)
|
||||
|
||||
// price 和 size 可能是数字或字符串,使用 Any 类型,后续转换为 String
|
||||
val price: Any? = null, // 交易价格
|
||||
|
||||
val size: Any? = null, // 交易数量 (shares)
|
||||
|
||||
val timestamp: Any? = null, // Unix 时间戳(可能是秒或毫秒,可能是数字或字符串)
|
||||
|
||||
@SerializedName("transactionHash")
|
||||
val transactionHash: String? = null, // 交易哈希
|
||||
|
||||
val trader: ActivityTrader? = null, // 交易者信息对象(优先)
|
||||
|
||||
@SerializedName("proxyWallet")
|
||||
val proxyWallet: String? = null, // 交易者地址(fallback,如果 trader 不存在)
|
||||
|
||||
val name: String? = null // 交易者名称(fallback,如果 trader 不存在)
|
||||
)
|
||||
|
||||
/**
|
||||
* Activity Trader 信息
|
||||
*/
|
||||
data class ActivityTrader(
|
||||
val name: String? = null, // 交易者用户名(可选)
|
||||
val address: String? = null // 交易者钱包地址 ⭐ 关键字段
|
||||
)
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
package com.wrbug.polymarketbot.dto
|
||||
|
||||
import java.math.BigDecimal
|
||||
|
||||
/**
|
||||
* 回测任务创建请求
|
||||
*/
|
||||
data class BacktestCreateRequest(
|
||||
val taskName: String, // 回测任务名称
|
||||
val leaderId: Long, // Leader ID
|
||||
val initialBalance: String, // 初始资金
|
||||
val backtestDays: Int, // 回测天数 (1-30)
|
||||
// 跟单配置(与 CopyTrading 一致,但不包含 max_position_count)
|
||||
val copyMode: String? = null, // "RATIO" 或 "FIXED"
|
||||
val copyRatio: String? = null, // 仅在 copyMode="RATIO" 时生效
|
||||
val fixedAmount: String? = null, // 仅在 copyMode="FIXED" 时生效
|
||||
val maxOrderSize: String? = null,
|
||||
val minOrderSize: String? = null,
|
||||
val maxDailyLoss: String? = null,
|
||||
val maxDailyOrders: Int? = null,
|
||||
val supportSell: Boolean? = null,
|
||||
val keywordFilterMode: String? = null, // 关键字过滤模式:DISABLED(不启用)、WHITELIST(白名单)、BLACKLIST(黑名单)
|
||||
val keywords: List<String>? = null, // 关键字列表
|
||||
val maxPositionValue: String? = null, // 最大仓位金额(USDC),NULL表示不启用
|
||||
val minPrice: String? = null, // 最低价格(可选),NULL表示不限制最低价
|
||||
val maxPrice: String? = null, // 最高价格(可选),NULL表示不限制最高价
|
||||
val pageForResume: Int? = null // 用于恢复中断任务,从指定页码开始获取历史数据(从1开始)
|
||||
)
|
||||
|
||||
/**
|
||||
* 回测任务列表请求
|
||||
*/
|
||||
data class BacktestListRequest(
|
||||
val leaderId: Long? = null, // Leader ID(可选)
|
||||
val status: String? = null, // PENDING/RUNNING/COMPLETED/STOPPED/FAILED
|
||||
val sortBy: String? = null, // profitAmount / profitRate / createdAt
|
||||
val sortOrder: String? = null, // asc / desc
|
||||
val page: Int = 1, // 页码,从1开始
|
||||
val size: Int = 20 // 每页数量
|
||||
)
|
||||
|
||||
/**
|
||||
* 回测任务详情请求
|
||||
*/
|
||||
data class BacktestDetailRequest(
|
||||
val id: Long // 回测任务ID
|
||||
)
|
||||
|
||||
/**
|
||||
* 回测交易记录请求
|
||||
*/
|
||||
data class BacktestTradeListRequest(
|
||||
val taskId: Long, // 回测任务ID
|
||||
val page: Int = 1, // 页码,从1开始
|
||||
val size: Int = 20 // 每页数量
|
||||
)
|
||||
|
||||
/**
|
||||
* 回测进度查询请求
|
||||
*/
|
||||
data class BacktestProgressRequest(
|
||||
val id: Long // 回测任务ID
|
||||
)
|
||||
|
||||
/**
|
||||
* 回测任务停止请求
|
||||
*/
|
||||
data class BacktestStopRequest(
|
||||
val id: Long // 回测任务ID
|
||||
)
|
||||
|
||||
/**
|
||||
* 回测任务删除请求
|
||||
*/
|
||||
data class BacktestDeleteRequest(
|
||||
val id: Long // 回测任务ID
|
||||
)
|
||||
|
||||
/**
|
||||
* 回测任务重试请求
|
||||
*/
|
||||
data class BacktestRetryRequest(
|
||||
val id: Long // 回测任务ID
|
||||
)
|
||||
|
||||
/**
|
||||
* 按当前配置重新测试请求(仅支持已完成任务)
|
||||
*/
|
||||
data class BacktestRerunRequest(
|
||||
val id: Long, // 源回测任务ID
|
||||
val taskName: String? = null // 新任务名称,为空时使用「原名称 (副本)」
|
||||
)
|
||||
|
||||
/**
|
||||
* 回测任务列表响应
|
||||
*/
|
||||
data class BacktestListResponse(
|
||||
val list: List<BacktestTaskDto>,
|
||||
val total: Long,
|
||||
val page: Int,
|
||||
val size: Int
|
||||
)
|
||||
|
||||
/**
|
||||
* 回测任务详情响应
|
||||
*/
|
||||
data class BacktestDetailResponse(
|
||||
val task: BacktestTaskDto,
|
||||
val config: BacktestConfigDto,
|
||||
val statistics: BacktestStatisticsDto
|
||||
)
|
||||
|
||||
/**
|
||||
* 回测交易记录列表响应
|
||||
*/
|
||||
data class BacktestTradeListResponse(
|
||||
val list: List<BacktestTradeDto>,
|
||||
val total: Long,
|
||||
val page: Int,
|
||||
val size: Int
|
||||
)
|
||||
|
||||
/**
|
||||
* 回测进度响应
|
||||
*/
|
||||
data class BacktestProgressResponse(
|
||||
val progress: Int, // 执行进度 (0-100)
|
||||
val currentBalance: String, // 当前余额
|
||||
val totalTrades: Int, // 总交易笔数
|
||||
val status: String // 任务状态
|
||||
)
|
||||
|
||||
/**
|
||||
* 回测任务 DTO
|
||||
*/
|
||||
data class BacktestTaskDto(
|
||||
val id: Long,
|
||||
val taskName: String,
|
||||
val leaderId: Long,
|
||||
val leaderName: String?,
|
||||
val leaderAddress: String?,
|
||||
val initialBalance: String,
|
||||
val finalBalance: String?,
|
||||
val profitAmount: String?,
|
||||
val profitRate: String?,
|
||||
val backtestDays: Int,
|
||||
val startTime: Long,
|
||||
val endTime: Long?,
|
||||
val status: String, // PENDING/RUNNING/COMPLETED/STOPPED/FAILED
|
||||
val progress: Int,
|
||||
val totalTrades: Int,
|
||||
val createdAt: Long,
|
||||
val executionStartedAt: Long?,
|
||||
val executionFinishedAt: Long?
|
||||
)
|
||||
|
||||
/**
|
||||
* 回测配置 DTO
|
||||
*/
|
||||
data class BacktestConfigDto(
|
||||
val copyMode: String,
|
||||
val copyRatio: String,
|
||||
val fixedAmount: String?,
|
||||
val maxOrderSize: String,
|
||||
val minOrderSize: String,
|
||||
val maxDailyLoss: String,
|
||||
val maxDailyOrders: Int,
|
||||
val supportSell: Boolean,
|
||||
val keywordFilterMode: String?,
|
||||
val keywords: List<String>?,
|
||||
val maxPositionValue: String?,
|
||||
val minPrice: String?, // 最低价格(可选),NULL表示不限制最低价
|
||||
val maxPrice: String? // 最高价格(可选),NULL表示不限制最高价
|
||||
)
|
||||
|
||||
/**
|
||||
* 回测统计信息 DTO
|
||||
*/
|
||||
data class BacktestStatisticsDto(
|
||||
val totalTrades: Int, // 总交易笔数
|
||||
val buyTrades: Int, // 买入笔数
|
||||
val sellTrades: Int, // 卖出笔数
|
||||
val winTrades: Int, // 盈利交易笔数
|
||||
val lossTrades: Int, // 亏损交易笔数
|
||||
val winRate: String, // 胜率(%)
|
||||
val maxProfit: String, // 最大单笔盈利
|
||||
val maxLoss: String, // 最大单笔亏损
|
||||
val maxDrawdown: String, // 最大回撤
|
||||
val avgHoldingTime: Long? // 平均持仓时间(毫秒)
|
||||
)
|
||||
|
||||
/**
|
||||
* 回测交易记录 DTO
|
||||
*/
|
||||
data class BacktestTradeDto(
|
||||
val id: Long,
|
||||
val tradeTime: Long,
|
||||
val marketId: String,
|
||||
val marketTitle: String?,
|
||||
val side: String, // BUY/SELL/SETTLEMENT
|
||||
val outcome: String,
|
||||
val outcomeIndex: Int?,
|
||||
val quantity: String,
|
||||
val price: String,
|
||||
val amount: String,
|
||||
val fee: String,
|
||||
val profitLoss: String?,
|
||||
val balanceAfter: String,
|
||||
val leaderTradeId: String?
|
||||
)
|
||||
|
||||
@@ -36,10 +36,14 @@ data class CopyTradingCreateRequest(
|
||||
val maxPrice: String? = null, // 最高价格(可选),NULL表示不限制最高价
|
||||
// 最大仓位配置
|
||||
val maxPositionValue: String? = null, // 最大仓位金额(USDC),NULL表示不启用
|
||||
val maxPositionCount: Int? = null, // 最大仓位数量,NULL表示不启用
|
||||
// 关键字过滤配置
|
||||
val keywordFilterMode: String? = null, // 关键字过滤模式:DISABLED(不启用)、WHITELIST(白名单)、BLACKLIST(黑名单)
|
||||
val keywords: List<String>? = null, // 关键字列表,当keywordFilterMode为DISABLED时为null
|
||||
// 新增配置字段
|
||||
val configName: String? = null, // 配置名(可选)
|
||||
val pushFailedOrders: Boolean? = null // 推送失败订单(可选)
|
||||
val pushFailedOrders: Boolean? = null, // 推送失败订单(可选)
|
||||
val pushFilteredOrders: Boolean? = null, // 推送已过滤订单(可选)
|
||||
val maxMarketEndDate: Long? = null // 市场截止时间限制(毫秒时间戳),仅跟单截止时间小于此时间的订单,NULL表示不启用
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -70,10 +74,32 @@ data class CopyTradingUpdateRequest(
|
||||
val maxPrice: String? = null, // 最高价格(可选),NULL表示不限制最高价
|
||||
// 最大仓位配置
|
||||
val maxPositionValue: String? = null, // 最大仓位金额(USDC),NULL表示不启用
|
||||
val maxPositionCount: Int? = null, // 最大仓位数量,NULL表示不启用
|
||||
// 关键字过滤配置
|
||||
val keywordFilterMode: String? = null, // 关键字过滤模式:DISABLED(不启用)、WHITELIST(白名单)、BLACKLIST(黑名单)
|
||||
val keywords: List<String>? = null, // 关键字列表,当keywordFilterMode为DISABLED时为null
|
||||
// 新增配置字段
|
||||
val configName: String? = null, // 配置名(可选,但提供时必须非空)
|
||||
val pushFailedOrders: Boolean? = null // 推送失败订单(可选)
|
||||
val pushFailedOrders: Boolean? = null, // 推送失败订单(可选)
|
||||
val pushFilteredOrders: Boolean? = null, // 推送已过滤订单(可选)
|
||||
val maxMarketEndDate: Long? = null // 市场截止时间限制(毫秒时间戳),仅跟单截止时间小于此时间的订单,NULL表示不启用
|
||||
)
|
||||
|
||||
/**
|
||||
* 应用保守风控配置请求。
|
||||
*
|
||||
* 只暴露安全带允许修改的白名单字段,避免误改 leader、启用状态、金额模式等真实交易行为。
|
||||
*/
|
||||
data class ApplyConservativeConfigRequest(
|
||||
val copyTradingId: Long,
|
||||
val confirm: Boolean = false,
|
||||
val maxDailyOrders: Int? = null,
|
||||
val maxDailyLoss: String? = null,
|
||||
val minPrice: String? = null,
|
||||
val maxPrice: String? = null,
|
||||
val maxPositionValue: String? = null,
|
||||
val minOrderDepth: String? = null,
|
||||
val maxSpread: String? = null,
|
||||
val priceTolerance: String? = null
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -141,10 +167,14 @@ data class CopyTradingDto(
|
||||
val maxPrice: String?, // 最高价格(可选),NULL表示不限制最高价
|
||||
// 最大仓位配置
|
||||
val maxPositionValue: String? = null, // 最大仓位金额(USDC),NULL表示不启用
|
||||
val maxPositionCount: Int? = null, // 最大仓位数量,NULL表示不启用
|
||||
// 关键字过滤配置
|
||||
val keywordFilterMode: String? = null, // 关键字过滤模式:DISABLED(不启用)、WHITELIST(白名单)、BLACKLIST(黑名单)
|
||||
val keywords: List<String>? = null, // 关键字列表,当keywordFilterMode为DISABLED时为null
|
||||
// 新增配置字段
|
||||
val configName: String? = null, // 配置名(可选)
|
||||
val pushFailedOrders: Boolean = false, // 推送失败订单(默认关闭)
|
||||
val pushFilteredOrders: Boolean = false, // 推送已过滤订单(默认关闭)
|
||||
val maxMarketEndDate: Long? = null, // 市场截止时间限制(毫秒时间戳),仅跟单截止时间小于此时间的订单,NULL表示不启用
|
||||
val createdAt: Long,
|
||||
val updatedAt: Long
|
||||
)
|
||||
@@ -177,4 +207,3 @@ data class AccountTemplatesResponse(
|
||||
val list: List<AccountTemplateDto>,
|
||||
val total: Long
|
||||
)
|
||||
|
||||
|
||||
@@ -24,7 +24,16 @@ data class CopyTradingStatisticsResponse(
|
||||
|
||||
// 持仓统计
|
||||
val currentPositionQuantity: String,
|
||||
val currentPositionCost: String,
|
||||
val currentPositionValue: String,
|
||||
val zeroValuePositionCost: String = "0",
|
||||
val confirmedZeroValuePositionCost: String = "0",
|
||||
val quoteOverallStatus: String = "AVAILABLE",
|
||||
val quoteAvailableCount: Int = 0,
|
||||
val quoteNoMatchCount: Int = 0,
|
||||
val quoteUnavailableCount: Int = 0,
|
||||
val quoteIncomplete: Boolean = false,
|
||||
val riskDiagnosis: CopyTradingRiskDiagnosisDto? = null,
|
||||
|
||||
// 盈亏统计
|
||||
val totalRealizedPnl: String,
|
||||
@@ -33,6 +42,49 @@ data class CopyTradingStatisticsResponse(
|
||||
val totalPnlPercent: String
|
||||
)
|
||||
|
||||
data class CopyTradingRiskDiagnosisDto(
|
||||
val copyTradingId: Long,
|
||||
val totalRealizedPnl: String,
|
||||
val totalUnrealizedPnl: String,
|
||||
val totalPnl: String,
|
||||
val currentPositionCost: String,
|
||||
val currentPositionValue: String,
|
||||
val zeroValuePositionCost: String,
|
||||
val confirmedZeroValuePositionCost: String,
|
||||
val zeroSellLoss: String,
|
||||
val openPositionQuantity: String,
|
||||
val totalBuyOrders: Int,
|
||||
val totalSellRecords: Int,
|
||||
val totalMatchDetails: Int,
|
||||
val filteredOrderCount: Long,
|
||||
val sampleSize: Int,
|
||||
val lowConfidence: Boolean,
|
||||
val confidenceReason: String,
|
||||
val quoteOverallStatus: String,
|
||||
val quoteAvailableCount: Int,
|
||||
val quoteNoMatchCount: Int,
|
||||
val quoteUnavailableCount: Int,
|
||||
val dataIncomplete: Boolean,
|
||||
val missingSources: List<String>,
|
||||
val topLosingMarkets: List<TopLosingMarketDto>,
|
||||
val riskWarnings: List<RiskWarningDto>,
|
||||
val generatedAt: Long
|
||||
)
|
||||
|
||||
data class TopLosingMarketDto(
|
||||
val marketId: String,
|
||||
val realizedPnl: String,
|
||||
val matchedOrders: Int
|
||||
)
|
||||
|
||||
data class RiskWarningDto(
|
||||
val field: String,
|
||||
val currentValue: String?,
|
||||
val suggestedValue: String,
|
||||
val severity: String,
|
||||
val reason: String
|
||||
)
|
||||
|
||||
/**
|
||||
* 买入订单信息
|
||||
*/
|
||||
@@ -40,6 +92,10 @@ data class BuyOrderInfo(
|
||||
val orderId: String,
|
||||
val leaderTradeId: String,
|
||||
val marketId: String,
|
||||
val marketTitle: String? = null, // 市场名称
|
||||
val marketSlug: String? = null, // 市场 slug(用于显示)
|
||||
val eventSlug: String? = null, // 跳转用的 slug(从 events[0].slug 获取)
|
||||
val marketCategory: String? = null, // 市场分类(sports, crypto 等)
|
||||
val side: String,
|
||||
val quantity: String,
|
||||
val price: String,
|
||||
@@ -57,6 +113,10 @@ data class SellOrderInfo(
|
||||
val orderId: String,
|
||||
val leaderTradeId: String,
|
||||
val marketId: String,
|
||||
val marketTitle: String? = null, // 市场名称
|
||||
val marketSlug: String? = null, // 市场 slug(用于显示)
|
||||
val eventSlug: String? = null, // 跳转用的 slug(从 events[0].slug 获取)
|
||||
val marketCategory: String? = null, // 市场分类(sports, crypto 等)
|
||||
val side: String,
|
||||
val quantity: String,
|
||||
val price: String,
|
||||
@@ -71,6 +131,11 @@ data class SellOrderInfo(
|
||||
data class MatchedOrderInfo(
|
||||
val sellOrderId: String,
|
||||
val buyOrderId: String,
|
||||
val marketId: String? = null, // 市场ID(从买入订单获取)
|
||||
val marketTitle: String? = null, // 市场名称
|
||||
val marketSlug: String? = null, // 市场 slug(用于显示)
|
||||
val eventSlug: String? = null, // 跳转用的 slug(从 events[0].slug 获取)
|
||||
val marketCategory: String? = null, // 市场分类(sports, crypto 等)
|
||||
val matchedQuantity: String,
|
||||
val buyPrice: String,
|
||||
val sellPrice: String,
|
||||
@@ -97,12 +162,60 @@ data class OrderTrackingRequest(
|
||||
val page: Int? = 1,
|
||||
val limit: Int? = 20,
|
||||
val marketId: String? = null,
|
||||
val side: String? = null,
|
||||
val marketTitle: String? = null, // 市场标题关键字筛选
|
||||
val status: String? = null,
|
||||
val sellOrderId: String? = null,
|
||||
val buyOrderId: String? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 按市场分组的订单查询请求
|
||||
*/
|
||||
data class MarketGroupedOrdersRequest(
|
||||
val copyTradingId: Long,
|
||||
val type: String, // buy, sell, matched
|
||||
val page: Int? = 1,
|
||||
val limit: Int? = 20,
|
||||
val marketId: String? = null,
|
||||
val marketTitle: String? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 单个市场的订单统计信息
|
||||
*/
|
||||
data class MarketOrderStats(
|
||||
val count: Long,
|
||||
val totalAmount: String, // 总金额
|
||||
val totalPnl: String?, // 总盈亏(买入订单未实现盈亏,此字段为空)
|
||||
val fullyMatched: Boolean, // 是否全部成交
|
||||
val fullyMatchedCount: Long, // 完全成交的订单数
|
||||
val partiallyMatchedCount: Long, // 部分成交的订单数
|
||||
val filledCount: Long // 未成交的订单数
|
||||
)
|
||||
|
||||
/**
|
||||
* 单个市场分组的响应数据
|
||||
*/
|
||||
data class MarketOrderGroup(
|
||||
val marketId: String,
|
||||
val marketTitle: String?,
|
||||
val marketSlug: String?, // 显示用的 slug
|
||||
val eventSlug: String? = null, // 跳转用的 slug(从 events[0].slug 获取)
|
||||
val marketCategory: String?,
|
||||
val stats: MarketOrderStats,
|
||||
val orders: List<Any> // BuyOrderInfo, SellOrderInfo 或 MatchedOrderInfo 的列表
|
||||
)
|
||||
|
||||
/**
|
||||
* 按市场分组的订单列表响应
|
||||
*/
|
||||
data class MarketGroupedOrdersResponse(
|
||||
val list: List<MarketOrderGroup>,
|
||||
val total: Long, // 市场总数
|
||||
val page: Int,
|
||||
val limit: Int
|
||||
)
|
||||
|
||||
/**
|
||||
* 统计查询请求
|
||||
*/
|
||||
@@ -147,4 +260,3 @@ data class StatisticsResponse(
|
||||
val maxProfit: String,
|
||||
val maxLoss: String
|
||||
)
|
||||
|
||||
|
||||
@@ -23,7 +23,8 @@ data class TemplateCreateRequest(
|
||||
val minOrderDepth: String? = null, // 最小订单深度(USDC金额),NULL表示不启用
|
||||
val maxSpread: String? = null, // 最大价差(绝对价格),NULL表示不启用
|
||||
val minPrice: String? = null, // 最低价格(可选),NULL表示不限制最低价
|
||||
val maxPrice: String? = null // 最高价格(可选),NULL表示不限制最高价
|
||||
val maxPrice: String? = null, // 最高价格(可选),NULL表示不限制最高价
|
||||
val pushFilteredOrders: Boolean? = null // 推送已过滤订单(默认关闭)
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -50,7 +51,8 @@ data class TemplateUpdateRequest(
|
||||
val minOrderDepth: String? = null, // 最小订单深度(USDC金额),NULL表示不启用
|
||||
val maxSpread: String? = null, // 最大价差(绝对价格),NULL表示不启用
|
||||
val minPrice: String? = null, // 最低价格(可选),NULL表示不限制最低价
|
||||
val maxPrice: String? = null // 最高价格(可选),NULL表示不限制最高价
|
||||
val maxPrice: String? = null, // 最高价格(可选),NULL表示不限制最高价
|
||||
val pushFilteredOrders: Boolean? = null // 推送已过滤订单(默认关闭)
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -84,7 +86,8 @@ data class TemplateCopyRequest(
|
||||
val minOrderDepth: String? = null, // 最小订单深度(USDC金额),NULL表示不启用
|
||||
val maxSpread: String? = null, // 最大价差(绝对价格),NULL表示不启用
|
||||
val minPrice: String? = null, // 最低价格(可选),NULL表示不限制最低价
|
||||
val maxPrice: String? = null // 最高价格(可选),NULL表示不限制最高价
|
||||
val maxPrice: String? = null, // 最高价格(可选),NULL表示不限制最高价
|
||||
val pushFilteredOrders: Boolean? = null // 推送已过滤订单(默认关闭)
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -119,6 +122,7 @@ data class TemplateDto(
|
||||
val maxSpread: String?,
|
||||
val minPrice: String?, // 最低价格(可选),NULL表示不限制最低价
|
||||
val maxPrice: String?, // 最高价格(可选),NULL表示不限制最高价
|
||||
val pushFilteredOrders: Boolean, // 推送已过滤订单(默认关闭)
|
||||
val createdAt: Long,
|
||||
val updatedAt: Long
|
||||
)
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.wrbug.polymarketbot.dto
|
||||
|
||||
/**
|
||||
* 加密价差策略手动下单请求
|
||||
*/
|
||||
data class CryptoTailManualOrderRequest(
|
||||
/** 策略ID */
|
||||
val strategyId: Long = 0L,
|
||||
/** 当前周期开始时间 (Unix 秒) */
|
||||
val periodStartUnix: Long = 0L,
|
||||
/** 下单方向: UP or DOWN */
|
||||
val direction: String = "UP",
|
||||
/** 下单价格 */
|
||||
val price: String = "0",
|
||||
/** 下单数量 */
|
||||
val size: String = "1",
|
||||
/** 市场标题(用于记录) */
|
||||
val marketTitle: String = "",
|
||||
/** Token IDs */
|
||||
val tokenIds: List<String> = emptyList()
|
||||
)
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.wrbug.polymarketbot.dto
|
||||
|
||||
/**
|
||||
* 加密价差策略手动下单响应
|
||||
*/
|
||||
data class CryptoTailManualOrderResponse(
|
||||
/** 是否成功 */
|
||||
val success: Boolean = false,
|
||||
/** 订单ID */
|
||||
val orderId: String? = null,
|
||||
/** 提示消息 */
|
||||
val message: String = "",
|
||||
/** 下单详情 */
|
||||
val orderDetails: ManualOrderDetails? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 手动下单详情
|
||||
*/
|
||||
data class ManualOrderDetails(
|
||||
/** 策略ID */
|
||||
val strategyId: Long = 0L,
|
||||
/** 方向 */
|
||||
val direction: String = "",
|
||||
/** 下单价格 */
|
||||
val price: String = "",
|
||||
/** 下单数量 */
|
||||
val size: String = "",
|
||||
/** 总金额 */
|
||||
val totalAmount: String = ""
|
||||
)
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.wrbug.polymarketbot.dto
|
||||
|
||||
/**
|
||||
* 加密价差策略监控初始化请求
|
||||
*/
|
||||
data class CryptoTailMonitorInitRequest(
|
||||
/** 策略ID */
|
||||
val strategyId: Long = 0L,
|
||||
/** 指定周期开始时间 (Unix 秒),不传则用服务器当前周期 */
|
||||
val periodStartUnix: Long? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 加密价差策略监控初始化响应
|
||||
*/
|
||||
data class CryptoTailMonitorInitResponse(
|
||||
/** 策略ID */
|
||||
val strategyId: Long = 0L,
|
||||
/** 策略名称 */
|
||||
val name: String = "",
|
||||
/** 账户ID */
|
||||
val accountId: Long = 0L,
|
||||
/** 账户名称 */
|
||||
val accountName: String = "",
|
||||
/** 市场 slug 前缀 */
|
||||
val marketSlugPrefix: String = "",
|
||||
/** 市场标题 */
|
||||
val marketTitle: String = "",
|
||||
/** 周期秒数 (300=5m, 900=15m) */
|
||||
val intervalSeconds: Int = 300,
|
||||
/** 当前周期开始时间 (Unix 秒) */
|
||||
val periodStartUnix: Long = 0L,
|
||||
/** 时间窗口开始秒数 */
|
||||
val windowStartSeconds: Int = 0,
|
||||
/** 时间窗口结束秒数 */
|
||||
val windowEndSeconds: Int = 0,
|
||||
/** 最低价格 */
|
||||
val minPrice: String = "0",
|
||||
/** 最高价格 */
|
||||
val maxPrice: String = "1",
|
||||
/** 最小价差模式: NONE, FIXED, AUTO */
|
||||
val minSpreadMode: String = "NONE",
|
||||
/** 价差方向: MIN(显示周期内最小价差), MAX(显示周期内最大价差) */
|
||||
val spreadDirection: String = "MIN",
|
||||
/** 最小价差数值 (FIXED 时有值) */
|
||||
val minSpreadValue: String? = null,
|
||||
/** 自动计算的最小价差 (Up方向) */
|
||||
val autoMinSpreadUp: String? = null,
|
||||
/** 自动计算的最小价差 (Down方向) */
|
||||
val autoMinSpreadDown: String? = null,
|
||||
/** BTC 开盘价 USDC(来自币安 K 线 open) */
|
||||
val openPriceBtc: String? = null,
|
||||
/** Up tokenId */
|
||||
val tokenIdUp: String? = null,
|
||||
/** Down tokenId */
|
||||
val tokenIdDown: String? = null,
|
||||
/** 当前时间 (毫秒时间戳) */
|
||||
val currentTimestamp: Long = System.currentTimeMillis(),
|
||||
/** 是否启用 */
|
||||
val enabled: Boolean = true,
|
||||
/** 投入金额模式: FIXED or RATIO */
|
||||
val amountMode: String? = null,
|
||||
/** 投入金额数值 */
|
||||
val amountValue: String? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 加密价差策略监控实时推送数据
|
||||
*/
|
||||
data class CryptoTailMonitorPushData(
|
||||
/** 策略ID */
|
||||
val strategyId: Long = 0L,
|
||||
/** 推送时间 (毫秒时间戳) */
|
||||
val timestamp: Long = System.currentTimeMillis(),
|
||||
/** 当前周期开始时间 (Unix 秒) */
|
||||
val periodStartUnix: Long = 0L,
|
||||
/** 当前周期市场标题(周期切换时更新) */
|
||||
val marketTitle: String = "",
|
||||
/** 当前价格 (Up方向,来自订单簿) */
|
||||
val currentPriceUp: String? = null,
|
||||
/** 当前价格 (Down方向,来自订单簿) */
|
||||
val currentPriceDown: String? = null,
|
||||
/** 当前价差 (Up方向: 1 - currentPriceUp) */
|
||||
val spreadUp: String? = null,
|
||||
/** 当前价差 (Down方向: currentPriceUp) */
|
||||
val spreadDown: String? = null,
|
||||
/** 最小价差线 (Up方向) */
|
||||
val minSpreadLineUp: String? = null,
|
||||
/** 最小价差线 (Down方向,USDC 价差) */
|
||||
val minSpreadLineDown: String? = null,
|
||||
/** BTC 开盘价 USDC(币安 K 线 open) */
|
||||
val openPriceBtc: String? = null,
|
||||
/** BTC 最新价 USDC(币安 K 线 close,当前周期实时) */
|
||||
val currentPriceBtc: String? = null,
|
||||
/** BTC 价差 USDC(currentPriceBtc - openPriceBtc) */
|
||||
val spreadBtc: String? = null,
|
||||
/** 周期剩余秒数 */
|
||||
val remainingSeconds: Int = 0,
|
||||
/** 是否在时间窗口内 */
|
||||
val inTimeWindow: Boolean = false,
|
||||
/** 是否在价格区间内 (Up方向) */
|
||||
val inPriceRangeUp: Boolean = false,
|
||||
/** 是否在价格区间内 (Down方向) */
|
||||
val inPriceRangeDown: Boolean = false,
|
||||
/** 是否已触发 */
|
||||
val triggered: Boolean = false,
|
||||
/** 触发方向: UP, DOWN, null */
|
||||
val triggerDirection: String? = null,
|
||||
/** 周期是否已结束 */
|
||||
val periodEnded: Boolean = false
|
||||
)
|
||||
@@ -0,0 +1,211 @@
|
||||
package com.wrbug.polymarketbot.dto
|
||||
|
||||
/**
|
||||
* 加密价差策略创建请求
|
||||
* 金额与价格使用 String,后端转为 BigDecimal
|
||||
*/
|
||||
data class CryptoTailStrategyCreateRequest(
|
||||
val accountId: Long = 0L,
|
||||
val name: String? = null,
|
||||
val marketSlugPrefix: String = "",
|
||||
val intervalSeconds: Int = 300,
|
||||
val windowStartSeconds: Int = 0,
|
||||
val windowEndSeconds: Int = 0,
|
||||
val minPrice: String = "0",
|
||||
val maxPrice: String? = null,
|
||||
val amountMode: String = "RATIO",
|
||||
val amountValue: String = "0",
|
||||
/** 价差模式: NONE, FIXED, AUTO */
|
||||
val spreadMode: String = "NONE",
|
||||
/** 价差数值 */
|
||||
val spreadValue: String? = null,
|
||||
/** 价差方向: MIN=最小价差, MAX=最大价差 */
|
||||
val spreadDirection: String = "MIN",
|
||||
val enabled: Boolean = true
|
||||
)
|
||||
|
||||
/**
|
||||
* 加密价差策略更新请求
|
||||
*/
|
||||
data class CryptoTailStrategyUpdateRequest(
|
||||
val strategyId: Long = 0L,
|
||||
val name: String? = null,
|
||||
val windowStartSeconds: Int? = null,
|
||||
val windowEndSeconds: Int? = null,
|
||||
val minPrice: String? = null,
|
||||
val maxPrice: String? = null,
|
||||
val amountMode: String? = null,
|
||||
val amountValue: String? = null,
|
||||
/** 价差模式: NONE, FIXED, AUTO */
|
||||
val spreadMode: String? = null,
|
||||
/** 价差数值 */
|
||||
val spreadValue: String? = null,
|
||||
/** 价差方向: MIN=最小价差, MAX=最大价差 */
|
||||
val spreadDirection: String? = null,
|
||||
val enabled: Boolean? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 加密价差策略列表请求
|
||||
*/
|
||||
data class CryptoTailStrategyListRequest(
|
||||
val accountId: Long? = null,
|
||||
val enabled: Boolean? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 加密价差策略 DTO(列表与详情)
|
||||
*/
|
||||
data class CryptoTailStrategyDto(
|
||||
val id: Long = 0L,
|
||||
val accountId: Long = 0L,
|
||||
val name: String? = null,
|
||||
val marketSlugPrefix: String = "",
|
||||
val marketTitle: String? = null,
|
||||
val intervalSeconds: Int = 0,
|
||||
val windowStartSeconds: Int = 0,
|
||||
val windowEndSeconds: Int = 0,
|
||||
val minPrice: String = "0",
|
||||
val maxPrice: String = "1",
|
||||
val amountMode: String = "RATIO",
|
||||
val amountValue: String = "0",
|
||||
/** 价差模式: NONE, FIXED, AUTO */
|
||||
val spreadMode: String = "NONE",
|
||||
/** 价差数值 */
|
||||
val spreadValue: String? = null,
|
||||
/** 价差方向: MIN=最小价差(价差>=配置值触发), MAX=最大价差(价差<=配置值触发) */
|
||||
val spreadDirection: String = "MIN",
|
||||
val enabled: Boolean = true,
|
||||
val lastTriggerAt: Long? = null,
|
||||
/** 已实现总收益 USDC(已结算订单的 realizedPnl 之和) */
|
||||
val totalRealizedPnl: String? = null,
|
||||
/** 已结算笔数(用于胜率分母) */
|
||||
val settledCount: Long = 0L,
|
||||
/** 已结算中赢的笔数(用于胜率分子) */
|
||||
val winCount: Long = 0L,
|
||||
/** 胜率 0~1(已结算时 = winCount/settledCount,无结算为 null) */
|
||||
val winRate: String? = null,
|
||||
val createdAt: Long = 0L,
|
||||
val updatedAt: Long = 0L
|
||||
)
|
||||
|
||||
/**
|
||||
* 加密价差策略列表响应
|
||||
*/
|
||||
data class CryptoTailStrategyListResponse(
|
||||
val list: List<CryptoTailStrategyDto> = emptyList()
|
||||
)
|
||||
|
||||
/**
|
||||
* 加密价差策略删除请求
|
||||
*/
|
||||
data class CryptoTailStrategyDeleteRequest(
|
||||
val strategyId: Long = 0L
|
||||
)
|
||||
|
||||
/**
|
||||
* 触发记录列表请求
|
||||
* @param startDate 开始日期(当天 00:00:00.000 的时间戳毫秒),为 null 表示不限制
|
||||
* @param endDate 结束日期(当天 23:59:59.999 的时间戳毫秒),为 null 表示不限制
|
||||
*/
|
||||
data class CryptoTailStrategyTriggerListRequest(
|
||||
val strategyId: Long = 0L,
|
||||
val page: Int = 1,
|
||||
val pageSize: Int = 20,
|
||||
val status: String? = null,
|
||||
val startDate: Long? = null,
|
||||
val endDate: Long? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 触发记录 DTO
|
||||
*/
|
||||
data class CryptoTailStrategyTriggerDto(
|
||||
val id: Long = 0L,
|
||||
val strategyId: Long = 0L,
|
||||
val periodStartUnix: Long = 0L,
|
||||
val marketTitle: String? = null,
|
||||
val outcomeIndex: Int = 0,
|
||||
val triggerPrice: String = "0",
|
||||
val amountUsdc: String = "0",
|
||||
val orderId: String? = null,
|
||||
val status: String = "success",
|
||||
val failReason: String? = null,
|
||||
/** 是否已结算 */
|
||||
val resolved: Boolean = false,
|
||||
/** 已实现盈亏 USDC(结算后有值) */
|
||||
val realizedPnl: String? = null,
|
||||
/** 市场赢家 outcome 索引(结算后有值) */
|
||||
val winnerOutcomeIndex: Int? = null,
|
||||
val settledAt: Long? = null,
|
||||
val createdAt: Long = 0L
|
||||
)
|
||||
|
||||
/**
|
||||
* 触发记录分页响应
|
||||
*/
|
||||
data class CryptoTailStrategyTriggerListResponse(
|
||||
val list: List<CryptoTailStrategyTriggerDto> = emptyList(),
|
||||
val total: Long = 0L
|
||||
)
|
||||
|
||||
/**
|
||||
* 自动价差计算响应(按 30 根历史 K 线 + IQR 剔除后 × 0.7)
|
||||
*/
|
||||
data class CryptoTailAutoMinSpreadResponse(
|
||||
val minSpreadUp: String = "0",
|
||||
val minSpreadDown: String = "0"
|
||||
)
|
||||
|
||||
/**
|
||||
* 5/15 分钟市场项(供前端选择市场)
|
||||
*/
|
||||
data class CryptoTailMarketOptionDto(
|
||||
val slug: String = "",
|
||||
val title: String = "",
|
||||
val intervalSeconds: Int = 0,
|
||||
val periodStartUnix: Long = 0L,
|
||||
val endDate: String? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 收益曲线请求
|
||||
* @param strategyId 策略ID
|
||||
* @param startDate 开始时间(毫秒时间戳),null 表示不限制
|
||||
* @param endDate 结束时间(毫秒时间戳),null 表示不限制
|
||||
*/
|
||||
data class CryptoTailPnlCurveRequest(
|
||||
val strategyId: Long = 0L,
|
||||
val startDate: Long? = null,
|
||||
val endDate: Long? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 收益曲线单点数据
|
||||
*/
|
||||
data class CryptoTailPnlCurvePoint(
|
||||
/** 时间点(毫秒时间戳,结算时间或创建时间) */
|
||||
val timestamp: Long = 0L,
|
||||
/** 累计收益 USDC */
|
||||
val cumulativePnl: String = "0",
|
||||
/** 当笔收益 USDC */
|
||||
val pointPnl: String = "0",
|
||||
/** 截至该点累计已结算笔数 */
|
||||
val settledCount: Long = 0L
|
||||
)
|
||||
|
||||
/**
|
||||
* 收益曲线响应
|
||||
*/
|
||||
data class CryptoTailPnlCurveResponse(
|
||||
val strategyId: Long = 0L,
|
||||
val strategyName: String = "",
|
||||
/** 筛选范围内总已实现收益 USDC */
|
||||
val totalRealizedPnl: String = "0",
|
||||
val settledCount: Long = 0L,
|
||||
val winCount: Long = 0L,
|
||||
val winRate: String? = null,
|
||||
/** 最大回撤 USDC(正数表示回撤幅度) */
|
||||
val maxDrawdown: String? = null,
|
||||
val curveData: List<CryptoTailPnlCurvePoint> = emptyList()
|
||||
)
|
||||
@@ -36,6 +36,13 @@ data class LeaderListRequest(
|
||||
val category: String? = null // sports 或 crypto
|
||||
)
|
||||
|
||||
/**
|
||||
* Leader 余额请求
|
||||
*/
|
||||
data class LeaderBalanceRequest(
|
||||
val leaderId: Long // LeaderID(必需)
|
||||
)
|
||||
|
||||
/**
|
||||
* Leader 信息响应
|
||||
*/
|
||||
@@ -47,6 +54,7 @@ data class LeaderDto(
|
||||
val remark: String? = null, // Leader 备注(可选)
|
||||
val website: String? = null, // Leader 网站(可选)
|
||||
val copyTradingCount: Long = 0, // 跟单关系数量
|
||||
val backtestCount: Long = 0, // 回测数量
|
||||
val totalOrders: Long? = null, // 总订单数(可选)
|
||||
val totalPnl: String? = null, // 总盈亏(可选)
|
||||
val createdAt: Long,
|
||||
@@ -61,3 +69,16 @@ data class LeaderListResponse(
|
||||
val total: Long
|
||||
)
|
||||
|
||||
/**
|
||||
* Leader 余额响应
|
||||
*/
|
||||
data class LeaderBalanceResponse(
|
||||
val leaderId: Long,
|
||||
val leaderAddress: String,
|
||||
val leaderName: String?,
|
||||
val availableBalance: String, // 可用余额(RPC 查询的 USDC 余额)
|
||||
val positionBalance: String, // 仓位余额(持仓总价值)
|
||||
val totalBalance: String, // 总余额 = 可用余额 + 仓位余额
|
||||
val positions: List<PositionDto> = emptyList()
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.wrbug.polymarketbot.dto
|
||||
|
||||
data class LeaderPoolListRequest(
|
||||
val status: String? = null
|
||||
)
|
||||
|
||||
data class LeaderPoolAddRequest(
|
||||
val leaderId: Long,
|
||||
val source: String? = null,
|
||||
val reason: String? = null,
|
||||
val notes: String? = null
|
||||
)
|
||||
|
||||
data class LeaderPoolUpdateStatusRequest(
|
||||
val poolId: Long,
|
||||
val status: String,
|
||||
val cooldownUntil: Long? = null,
|
||||
val locked: Boolean? = null
|
||||
)
|
||||
|
||||
data class LeaderPoolUpdatePlanRequest(
|
||||
val poolId: Long,
|
||||
val suggestedFixedAmount: String? = null,
|
||||
val suggestedMaxDailyOrders: Int? = null,
|
||||
val suggestedMaxDailyLoss: String? = null,
|
||||
val suggestedMinPrice: String? = null,
|
||||
val suggestedMaxPrice: String? = null,
|
||||
val suggestedMaxPositionValue: String? = null,
|
||||
val reason: String? = null,
|
||||
val notes: String? = null
|
||||
)
|
||||
|
||||
data class LeaderPoolCreateTrialConfigRequest(
|
||||
val poolId: Long,
|
||||
val accountId: Long,
|
||||
val enableImmediately: Boolean = false,
|
||||
val confirm: Boolean = false
|
||||
)
|
||||
|
||||
data class LeaderPoolRemoveRequest(
|
||||
val poolId: Long
|
||||
)
|
||||
|
||||
data class LeaderPoolSummaryDto(
|
||||
val totalCount: Int,
|
||||
val trialCount: Int,
|
||||
val estimatedWorstExposure: String,
|
||||
val pendingRiskCount: Int,
|
||||
val defaultExperimentBudget: String = "50"
|
||||
)
|
||||
|
||||
data class LeaderPoolItemDto(
|
||||
val id: Long,
|
||||
val leaderId: Long,
|
||||
val leaderName: String?,
|
||||
val leaderAddress: String,
|
||||
val category: String?,
|
||||
val profileUrl: String,
|
||||
val status: String,
|
||||
val source: String,
|
||||
val sourceRank: Int?,
|
||||
val score: String?,
|
||||
val reason: String?,
|
||||
val notes: String?,
|
||||
val suggestedFixedAmount: String,
|
||||
val suggestedMaxDailyOrders: Int,
|
||||
val suggestedMaxDailyLoss: String,
|
||||
val suggestedMinPrice: String?,
|
||||
val suggestedMaxPrice: String?,
|
||||
val suggestedMaxPositionValue: String?,
|
||||
val copyTradingCount: Int,
|
||||
val hasEnabledCopyTrading: Boolean,
|
||||
val estimatedWorstExposure: String,
|
||||
val lastReviewedAt: Long?,
|
||||
val lastPromotedAt: Long?,
|
||||
val cooldownUntil: Long?,
|
||||
val locked: Boolean,
|
||||
val researchCandidateId: Long?,
|
||||
val researchState: String?,
|
||||
val researchBadge: String?,
|
||||
val researchSummary: String?,
|
||||
val researchScore: String?,
|
||||
val researchUpdatedAt: Long?,
|
||||
val createdAt: Long,
|
||||
val updatedAt: Long
|
||||
)
|
||||
|
||||
data class LeaderPoolListResponse(
|
||||
val summary: LeaderPoolSummaryDto,
|
||||
val list: List<LeaderPoolItemDto>,
|
||||
val total: Int
|
||||
)
|
||||
@@ -0,0 +1,224 @@
|
||||
package com.wrbug.polymarketbot.dto
|
||||
|
||||
data class LeaderResearchRunRequest(
|
||||
val dryRun: Boolean = false,
|
||||
val triggerType: String = "MANUAL"
|
||||
)
|
||||
|
||||
data class LeaderResearchRunDto(
|
||||
val id: Long,
|
||||
val status: String,
|
||||
val triggerType: String,
|
||||
val dryRun: Boolean,
|
||||
val startedAt: Long,
|
||||
val finishedAt: Long?,
|
||||
val durationMs: Long?,
|
||||
val sourceCountsJson: String?,
|
||||
val candidateCountsJson: String?,
|
||||
val partialFailure: Boolean,
|
||||
val skippedReason: String?,
|
||||
val errorClass: String?,
|
||||
val errorMessage: String?
|
||||
)
|
||||
|
||||
data class LeaderResearchSummaryDto(
|
||||
val discoveredCount: Long,
|
||||
val candidateCount: Long,
|
||||
val paperCount: Long,
|
||||
val trialReadyCount: Long,
|
||||
val cooldownCount: Long,
|
||||
val retiredCount: Long,
|
||||
val activePaperSessions: Long,
|
||||
val pendingRiskCount: Long,
|
||||
val lastRun: LeaderResearchRunDto?,
|
||||
val sourceLimitations: List<String>
|
||||
)
|
||||
|
||||
data class LeaderResearchCandidateListRequest(
|
||||
val page: Int = 0,
|
||||
val size: Int = 20,
|
||||
val state: String? = null,
|
||||
val query: String? = null
|
||||
)
|
||||
|
||||
data class LeaderResearchCandidateListResponse(
|
||||
val list: List<LeaderResearchCandidateDto>,
|
||||
val total: Long,
|
||||
val summary: LeaderResearchSummaryDto
|
||||
)
|
||||
|
||||
data class LeaderResearchCandidateDto(
|
||||
val id: Long,
|
||||
val normalizedWallet: String,
|
||||
val leaderId: Long?,
|
||||
val leaderName: String?,
|
||||
val poolId: Long?,
|
||||
val poolStatus: String?,
|
||||
val suggestedFixedAmount: String?,
|
||||
val suggestedMaxDailyLoss: String?,
|
||||
val suggestedMaxDailyOrders: Int?,
|
||||
val suggestedMinPrice: String?,
|
||||
val suggestedMaxPrice: String?,
|
||||
val suggestedMaxPositionValue: String?,
|
||||
val researchState: String,
|
||||
val source: String,
|
||||
val sourceRank: Int?,
|
||||
val score: String?,
|
||||
val scoreVersion: String?,
|
||||
val reason: String?,
|
||||
val riskFlags: List<String>,
|
||||
val locked: Boolean,
|
||||
val agentOwned: Boolean,
|
||||
val provenance: String,
|
||||
val sourceEvidence: String?,
|
||||
val firstSeenAt: Long,
|
||||
val lastSourceSeenAt: Long?,
|
||||
val lastScoredAt: Long?,
|
||||
val cooldownUntil: Long?,
|
||||
val cooldownCount: Int,
|
||||
val trialReadyAt: Long?,
|
||||
val retiredAt: Long?,
|
||||
val lastPaperSessionId: Long?,
|
||||
val latestPaperSession: LeaderPaperSessionDto?
|
||||
)
|
||||
|
||||
data class LeaderResearchCandidateDetailDto(
|
||||
val candidate: LeaderResearchCandidateDto,
|
||||
val latestScore: LeaderResearchScoreDto?,
|
||||
val paperSessions: List<LeaderPaperSessionDto>,
|
||||
val paperTrades: List<LeaderPaperTradeDto>,
|
||||
val paperPositions: List<LeaderPaperPositionDto>,
|
||||
val events: List<LeaderResearchEventDto>
|
||||
)
|
||||
|
||||
data class LeaderResearchScoreDto(
|
||||
val id: Long,
|
||||
val candidateId: Long,
|
||||
val runId: Long?,
|
||||
val scoreVersion: String,
|
||||
val totalScore: String,
|
||||
val profitSignal: String,
|
||||
val repeatability: String,
|
||||
val liquidityFit: String,
|
||||
val entryPriceFit: String,
|
||||
val slippageRisk: String,
|
||||
val holdingPeriodFit: String,
|
||||
val marketTypeRisk: String,
|
||||
val drawdownRisk: String,
|
||||
val exitLiquidityRisk: String,
|
||||
val dataFreshness: String,
|
||||
val filterPassRate: String,
|
||||
val sampleTradeCount: Int,
|
||||
val reason: String?,
|
||||
val createdAt: Long
|
||||
)
|
||||
|
||||
data class LeaderPaperSessionDto(
|
||||
val id: Long,
|
||||
val candidateId: Long,
|
||||
val status: String,
|
||||
val startedAt: Long,
|
||||
val endedAt: Long?,
|
||||
val tradeCount: Int,
|
||||
val filteredCount: Int,
|
||||
val openExposure: String,
|
||||
val totalRealizedPnl: String,
|
||||
val totalUnrealizedPnl: String,
|
||||
val copyablePnl: String,
|
||||
val maxDrawdown: String,
|
||||
val unknownValuationExposure: String,
|
||||
val confirmedZeroExposure: String,
|
||||
val filteredRatio: String,
|
||||
val lastProcessedEventTime: Long?,
|
||||
val scoreSnapshot: String?
|
||||
)
|
||||
|
||||
data class LeaderPaperTradeDto(
|
||||
val id: Long,
|
||||
val sessionId: Long,
|
||||
val candidateId: Long,
|
||||
val activityEventId: Long?,
|
||||
val leaderTradeId: String,
|
||||
val marketId: String,
|
||||
val marketTitle: String?,
|
||||
val marketSlug: String?,
|
||||
val side: String,
|
||||
val outcome: String?,
|
||||
val outcomeIndex: Int?,
|
||||
val leaderPrice: String?,
|
||||
val leaderSize: String?,
|
||||
val simulatedPrice: String?,
|
||||
val simulatedSize: String?,
|
||||
val simulatedAmount: String?,
|
||||
val fillAssumption: String,
|
||||
val quoteConfidence: String,
|
||||
val quoteSource: String?,
|
||||
val quoteTimestamp: Long?,
|
||||
val filterResult: String,
|
||||
val filterReason: String?,
|
||||
val valuationStatus: String,
|
||||
val realizedPnl: String?,
|
||||
val eventTime: Long,
|
||||
val createdAt: Long
|
||||
)
|
||||
|
||||
data class LeaderPaperPositionDto(
|
||||
val id: Long,
|
||||
val sessionId: Long,
|
||||
val candidateId: Long,
|
||||
val marketId: String,
|
||||
val outcome: String?,
|
||||
val outcomeIndex: Int?,
|
||||
val quantity: String,
|
||||
val cost: String,
|
||||
val avgPrice: String,
|
||||
val currentPrice: String?,
|
||||
val currentValue: String,
|
||||
val realizedPnl: String,
|
||||
val unrealizedPnl: String,
|
||||
val valuationStatus: String,
|
||||
val quoteConfidence: String,
|
||||
val quoteSource: String?,
|
||||
val quoteTimestamp: Long?,
|
||||
val updatedAt: Long
|
||||
)
|
||||
|
||||
data class LeaderResearchSourceStateDto(
|
||||
val sourceType: String,
|
||||
val status: String,
|
||||
val lastSuccessAt: Long?,
|
||||
val lastFailureAt: Long?,
|
||||
val lastRunAt: Long?,
|
||||
val lastCandidateCount: Int,
|
||||
val errorClass: String?,
|
||||
val errorMessage: String?,
|
||||
val stale: Boolean,
|
||||
val disabledReason: String?,
|
||||
val lastCursor: String?,
|
||||
val updatedAt: Long
|
||||
)
|
||||
|
||||
data class LeaderResearchEventDto(
|
||||
val id: Long,
|
||||
val candidateId: Long?,
|
||||
val runId: Long?,
|
||||
val eventType: String,
|
||||
val reason: String?,
|
||||
val payloadSummary: String?,
|
||||
val notificationStatus: String,
|
||||
val notificationError: String?,
|
||||
val dedupeKey: String?,
|
||||
val createdAt: Long,
|
||||
val notifiedAt: Long?
|
||||
)
|
||||
|
||||
data class LeaderResearchApprovalRequest(
|
||||
val candidateId: Long,
|
||||
val accountId: Long,
|
||||
val confirm: Boolean = false
|
||||
)
|
||||
|
||||
data class LeaderResearchApprovalResponse(
|
||||
val copyTrading: CopyTradingDto,
|
||||
val warning: String = "已创建禁用状态的试跟配置;需要你手动启用后才会真钱跟单。"
|
||||
)
|
||||
@@ -25,7 +25,8 @@ data class MarketDto(
|
||||
val liquidityNum: Double?,
|
||||
val bestBid: Double?,
|
||||
val bestAsk: Double?,
|
||||
val lastTradePrice: Double?
|
||||
val lastTradePrice: Double?,
|
||||
val events: List<MarketDto>? = null // 事件列表(从 events[0] 获取 slug)
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -37,9 +38,9 @@ data class OutcomeDto(
|
||||
)
|
||||
|
||||
/**
|
||||
* 事件 DTO
|
||||
* 事件 DTO(用于其他 API 调用)
|
||||
*/
|
||||
data class EventDto(
|
||||
data class EventListDto(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val category: String,
|
||||
@@ -55,7 +56,7 @@ data class SeriesDto(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val category: String,
|
||||
val events: List<EventDto>?,
|
||||
val events: List<EventListDto>?,
|
||||
val createdAt: Long? // 时间戳(毫秒)
|
||||
)
|
||||
|
||||
@@ -70,4 +71,3 @@ data class CommentDto(
|
||||
val createdAt: Long, // 时间戳(毫秒)
|
||||
val user: String?
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.wrbug.polymarketbot.dto
|
||||
|
||||
/**
|
||||
* 消息模板 DTO
|
||||
*/
|
||||
data class NotificationTemplateDto(
|
||||
val id: Long? = null,
|
||||
val templateType: String, // 模板类型
|
||||
val templateContent: String, // 模板内容
|
||||
val isDefault: Boolean = false, // 是否使用默认模板
|
||||
val createdAt: Long? = null,
|
||||
val updatedAt: Long? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 模板变量 DTO
|
||||
*/
|
||||
data class TemplateVariableDto(
|
||||
val key: String, // 变量名,如 account_name
|
||||
val category: String, // 分类:common, order, copy_trading, redeem, error
|
||||
val sortOrder: Int = 0 // 排序顺序
|
||||
)
|
||||
|
||||
/**
|
||||
* 模板变量分类 DTO
|
||||
*/
|
||||
data class TemplateVariableCategoryDto(
|
||||
val key: String, // 分类 key
|
||||
val sortOrder: Int = 0 // 排序顺序
|
||||
)
|
||||
|
||||
/**
|
||||
* 模板变量列表响应
|
||||
*/
|
||||
data class TemplateVariablesResponse(
|
||||
val templateType: String, // 模板类型
|
||||
val categories: List<TemplateVariableCategoryDto>, // 分类列表
|
||||
val variables: List<TemplateVariableDto> // 变量列表
|
||||
)
|
||||
|
||||
/**
|
||||
* 更新模板请求
|
||||
*/
|
||||
data class UpdateTemplateRequest(
|
||||
val templateContent: String // 模板内容
|
||||
)
|
||||
|
||||
/**
|
||||
* 测试模板请求
|
||||
*/
|
||||
data class TestTemplateRequest(
|
||||
val templateType: String, // 模板类型
|
||||
val templateContent: String? = null // 可选,如果不提供则使用已保存的模板
|
||||
)
|
||||
|
||||
/**
|
||||
* 模板类型信息
|
||||
*/
|
||||
data class TemplateTypeInfoDto(
|
||||
val type: String, // 模板类型
|
||||
val name: String, // 类型名称
|
||||
val description: String // 类型描述
|
||||
)
|
||||
@@ -51,18 +51,21 @@ data class OrderPushMessage(
|
||||
|
||||
/**
|
||||
* 订单详情(通过 API 获取)
|
||||
* @param price 订单限价(用户提交的买入/卖出价)
|
||||
* @param avgFilledPrice 实际成交价 = original_size * price / size_matched(有成交时优先用于推送展示)
|
||||
*/
|
||||
data class OrderDetailDto(
|
||||
val id: String, // 订单 ID
|
||||
val market: String, // 市场 ID (condition ID)
|
||||
val side: String, // BUY/SELL
|
||||
val price: String, // 价格
|
||||
val price: String, // 订单限价
|
||||
val size: String, // 订单大小
|
||||
val filled: String, // 已成交数量
|
||||
val status: String, // 订单状态
|
||||
val createdAt: String, // 创建时间(ISO 8601 格式)
|
||||
val marketName: String? = null, // 市场名称(通过 Data API 获取)
|
||||
val marketSlug: String? = null, // 市场 slug
|
||||
val marketIcon: String? = null // 市场图标
|
||||
val marketIcon: String? = null, // 市场图标
|
||||
val avgFilledPrice: String? = null // 实际成交价 = original_size*price/size_matched(有成交时使用)
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.wrbug.polymarketbot.dto
|
||||
|
||||
import java.math.BigDecimal
|
||||
|
||||
/**
|
||||
* 用户交易数据
|
||||
* 用于回测功能,从 Polymarket API 获取的用户交易历史
|
||||
*/
|
||||
data class TradeData(
|
||||
val tradeId: String, // 交易 ID
|
||||
val marketId: String, // 市场 ID
|
||||
val marketTitle: String?, // 市场标题
|
||||
val marketSlug: String?, // 市场 Slug
|
||||
val side: String, // 交易方向: BUY/SELL
|
||||
val outcome: String, // 结果: YES/NO 或 outcomeIndex
|
||||
val outcomeIndex: Int?, // 结果索引
|
||||
val price: BigDecimal, // 成交价格
|
||||
val size: BigDecimal, // 成交数量
|
||||
val amount: BigDecimal, // 成交金额
|
||||
val timestamp: Long // 交易时间戳
|
||||
) {
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
if (other !is TradeData) return false
|
||||
return tradeId == other.tradeId
|
||||
}
|
||||
|
||||
override fun hashCode(): Int {
|
||||
return tradeId.hashCode()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,11 +16,11 @@ data class Account(
|
||||
@Column(name = "private_key", nullable = false, length = 500)
|
||||
val privateKey: String, // 私钥(AES 加密存储)
|
||||
|
||||
@Column(name = "wallet_address", unique = true, nullable = false, length = 42)
|
||||
val walletAddress: String, // 钱包地址(从私钥推导)
|
||||
@Column(name = "wallet_address", nullable = false, length = 42)
|
||||
val walletAddress: String, // 钱包地址(从私钥推导),同一 EOA 可有多个账户(不同代理类型)
|
||||
|
||||
@Column(name = "proxy_address", nullable = false, length = 42)
|
||||
val proxyAddress: String, // Polymarket 代理钱包地址(从合约获取,必须)
|
||||
@Column(name = "proxy_address", unique = true, nullable = false, length = 42)
|
||||
val proxyAddress: String, // Polymarket 代理钱包地址(从合约获取,必须),唯一
|
||||
|
||||
@Column(name = "api_key", length = 500)
|
||||
val apiKey: String? = null, // Polymarket API Key(可选,明文存储)
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
package com.wrbug.polymarketbot.entity
|
||||
|
||||
import jakarta.persistence.*
|
||||
import java.math.BigDecimal
|
||||
import com.wrbug.polymarketbot.util.toSafeBigDecimal
|
||||
|
||||
/**
|
||||
* 回测任务实体
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "backtest_task")
|
||||
data class BacktestTask(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = null,
|
||||
|
||||
@Column(name = "task_name", nullable = false, length = 100)
|
||||
val taskName: String,
|
||||
|
||||
@Column(name = "leader_id", nullable = false)
|
||||
val leaderId: Long,
|
||||
|
||||
// 回测参数
|
||||
@Column(name = "initial_balance", nullable = false, precision = 20, scale = 8)
|
||||
val initialBalance: BigDecimal,
|
||||
|
||||
@Column(name = "final_balance", precision = 20, scale = 8)
|
||||
var finalBalance: BigDecimal? = null,
|
||||
|
||||
@Column(name = "profit_amount", precision = 20, scale = 8)
|
||||
var profitAmount: BigDecimal? = null,
|
||||
|
||||
@Column(name = "profit_rate", precision = 10, scale = 4)
|
||||
var profitRate: BigDecimal? = null, // 收益率(%)
|
||||
|
||||
@Column(name = "backtest_days", nullable = false)
|
||||
val backtestDays: Int,
|
||||
|
||||
@Column(name = "start_time", nullable = false)
|
||||
val startTime: Long, // 回测开始时间(历史时间),创建时计算;执行时以当前时间为基准用局部变量重算窗口
|
||||
|
||||
@Column(name = "end_time")
|
||||
var endTime: Long? = null, // 回测结束时间(历史时间)
|
||||
|
||||
// 跟单配置 (复制CopyTrading表结构,但不包含 max_position_count)
|
||||
@Column(name = "copy_mode", nullable = false, length = 10)
|
||||
val copyMode: String = "RATIO", // "RATIO" 或 "FIXED"
|
||||
|
||||
@Column(name = "copy_ratio", nullable = false, precision = 20, scale = 8)
|
||||
val copyRatio: BigDecimal = BigDecimal.ONE,
|
||||
|
||||
@Column(name = "fixed_amount", precision = 20, scale = 8)
|
||||
val fixedAmount: BigDecimal? = null,
|
||||
|
||||
@Column(name = "max_order_size", nullable = false, precision = 20, scale = 8)
|
||||
val maxOrderSize: BigDecimal = "1000".toSafeBigDecimal(),
|
||||
|
||||
@Column(name = "min_order_size", nullable = false, precision = 20, scale = 8)
|
||||
val minOrderSize: BigDecimal = "1".toSafeBigDecimal(),
|
||||
|
||||
@Column(name = "max_daily_loss", nullable = false, precision = 20, scale = 8)
|
||||
val maxDailyLoss: BigDecimal = "10000".toSafeBigDecimal(),
|
||||
|
||||
@Column(name = "max_daily_orders", nullable = false)
|
||||
val maxDailyOrders: Int = 100,
|
||||
|
||||
@Column(name = "support_sell", nullable = false)
|
||||
val supportSell: Boolean = true,
|
||||
|
||||
@Column(name = "keyword_filter_mode", nullable = false, length = 20)
|
||||
val keywordFilterMode: String = "DISABLED", // DISABLED/WHITELIST/BLACKLIST
|
||||
|
||||
@Column(name = "keywords", columnDefinition = "JSON")
|
||||
val keywords: String? = null,
|
||||
|
||||
@Column(name = "max_position_value", precision = 20, scale = 8)
|
||||
val maxPositionValue: BigDecimal? = null, // 最大仓位金额(USDC),NULL表示不启用
|
||||
|
||||
@Column(name = "min_price", precision = 20, scale = 8)
|
||||
val minPrice: BigDecimal? = null, // 最低价格(可选),NULL表示不限制最低价
|
||||
|
||||
@Column(name = "max_price", precision = 20, scale = 8)
|
||||
val maxPrice: BigDecimal? = null, // 最高价格(可选),NULL表示不限制最高价
|
||||
|
||||
// 统计字段
|
||||
@Column(name = "avg_holding_time")
|
||||
var avgHoldingTime: Long? = null, // 平均持仓时间(毫秒)
|
||||
|
||||
@Column(name = "data_source", length = 50)
|
||||
var dataSource: String = "MIXED", // INTERNAL/API/MIXED
|
||||
|
||||
// 执行状态
|
||||
@Column(name = "status", nullable = false, length = 20)
|
||||
var status: String = "PENDING", // PENDING/RUNNING/COMPLETED/STOPPED/FAILED
|
||||
|
||||
@Column(name = "progress", nullable = false)
|
||||
var progress: Int = 0, // 执行进度(0-100)
|
||||
|
||||
@Column(name = "total_trades", nullable = false)
|
||||
var totalTrades: Int = 0,
|
||||
|
||||
@Column(name = "buy_trades", nullable = false)
|
||||
var buyTrades: Int = 0,
|
||||
|
||||
@Column(name = "sell_trades", nullable = false)
|
||||
var sellTrades: Int = 0,
|
||||
|
||||
@Column(name = "win_trades", nullable = false)
|
||||
var winTrades: Int = 0,
|
||||
|
||||
@Column(name = "loss_trades", nullable = false)
|
||||
var lossTrades: Int = 0,
|
||||
|
||||
@Column(name = "win_rate", precision = 5, scale = 2)
|
||||
var winRate: BigDecimal? = null, // 胜率(%)
|
||||
|
||||
@Column(name = "max_profit", precision = 20, scale = 8)
|
||||
var maxProfit: BigDecimal? = null, // 最大单笔盈利
|
||||
|
||||
@Column(name = "max_loss", precision = 20, scale = 8)
|
||||
var maxLoss: BigDecimal? = null, // 最大单笔亏损
|
||||
|
||||
@Column(name = "max_drawdown", precision = 20, scale = 8)
|
||||
var maxDrawdown: BigDecimal? = null, // 最大回撤
|
||||
|
||||
@Column(name = "error_message", columnDefinition = "TEXT")
|
||||
var errorMessage: String? = null,
|
||||
|
||||
// 时间字段
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
|
||||
@Column(name = "execution_started_at")
|
||||
var executionStartedAt: Long? = null,
|
||||
|
||||
@Column(name = "execution_finished_at")
|
||||
var executionFinishedAt: Long? = null,
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
var updatedAt: Long = System.currentTimeMillis(),
|
||||
|
||||
@Column(name = "last_processed_trade_time")
|
||||
var lastProcessedTradeTime: Long? = null,
|
||||
|
||||
@Column(name = "last_processed_trade_index")
|
||||
var lastProcessedTradeIndex: Int? = null,
|
||||
|
||||
@Column(name = "processed_trade_count")
|
||||
var processedTradeCount: Int = 0
|
||||
)
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.wrbug.polymarketbot.entity
|
||||
|
||||
import jakarta.persistence.*
|
||||
import java.math.BigDecimal
|
||||
|
||||
/**
|
||||
* 回测交易记录实体
|
||||
* 用于记录回测过程中的每笔模拟交易
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "backtest_trade")
|
||||
data class BacktestTrade(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = null,
|
||||
|
||||
@Column(name = "backtest_task_id", nullable = false)
|
||||
val backtestTaskId: Long,
|
||||
|
||||
@Column(name = "trade_time", nullable = false)
|
||||
val tradeTime: Long,
|
||||
|
||||
@Column(name = "market_id", nullable = false, length = 100)
|
||||
val marketId: String,
|
||||
|
||||
@Column(name = "market_title", length = 500)
|
||||
val marketTitle: String? = null,
|
||||
|
||||
@Column(name = "side", nullable = false, length = 20)
|
||||
val side: String, // BUY/SELL/SETTLEMENT
|
||||
|
||||
@Column(name = "outcome", nullable = false, length = 50)
|
||||
val outcome: String, // YES/NO 或 outcomeIndex
|
||||
|
||||
@Column(name = "outcome_index")
|
||||
val outcomeIndex: Int? = null, // 结果索引(0, 1, 2, ...),支持多元市场
|
||||
|
||||
@Column(name = "quantity", nullable = false, precision = 20, scale = 8)
|
||||
val quantity: BigDecimal,
|
||||
|
||||
@Column(name = "price", nullable = false, precision = 20, scale = 8)
|
||||
val price: BigDecimal,
|
||||
|
||||
@Column(name = "amount", nullable = false, precision = 20, scale = 8)
|
||||
val amount: BigDecimal,
|
||||
|
||||
@Column(name = "fee", nullable = false, precision = 20, scale = 8)
|
||||
val fee: BigDecimal = BigDecimal.ZERO, // 手续费(回测不计算,默认为0)
|
||||
|
||||
@Column(name = "profit_loss", precision = 20, scale = 8)
|
||||
val profitLoss: BigDecimal? = null, // 盈亏(仅卖出时)
|
||||
|
||||
@Column(name = "balance_after", nullable = false, precision = 20, scale = 8)
|
||||
val balanceAfter: BigDecimal, // 交易后余额
|
||||
|
||||
@Column(name = "leader_trade_id", length = 100)
|
||||
val leaderTradeId: String? = null, // Leader 原始交易ID
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
@@ -58,7 +58,10 @@ data class CopyOrderTracking(
|
||||
|
||||
@Column(name = "notification_sent", nullable = false)
|
||||
var notificationSent: Boolean = false, // 是否已发送通知(从订单详情获取实际数据后发送)
|
||||
|
||||
|
||||
@Column(name = "source", nullable = false, length = 20)
|
||||
val source: String, // 订单来源:activity-ws(Polymarket WebSocket)、onchain-ws(OnChain WebSocket)
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
|
||||
|
||||
@@ -8,12 +8,7 @@ import com.wrbug.polymarketbot.util.toSafeBigDecimal
|
||||
* 跟单配置实体(独立配置,不再绑定模板)
|
||||
*/
|
||||
@Entity
|
||||
@Table(
|
||||
name = "copy_trading",
|
||||
uniqueConstraints = [
|
||||
UniqueConstraint(columnNames = ["account_id", "leader_id"])
|
||||
]
|
||||
)
|
||||
@Table(name = "copy_trading")
|
||||
data class CopyTrading(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@@ -88,8 +83,12 @@ data class CopyTrading(
|
||||
@Column(name = "max_position_value", precision = 20, scale = 8)
|
||||
val maxPositionValue: BigDecimal? = null, // 最大仓位金额(USDC),NULL表示不启用
|
||||
|
||||
@Column(name = "max_position_count")
|
||||
val maxPositionCount: Int? = null, // 最大仓位数量,NULL表示不启用
|
||||
// 关键字过滤配置
|
||||
@Column(name = "keyword_filter_mode", nullable = false, length = 20)
|
||||
val keywordFilterMode: String = "DISABLED", // 关键字过滤模式:DISABLED(不启用)、WHITELIST(白名单)、BLACKLIST(黑名单)
|
||||
|
||||
@Column(name = "keywords", columnDefinition = "JSON")
|
||||
val keywords: String? = null, // 关键字列表(JSON数组),例如:["NBA", "足球", "NBA总决赛"],当keywordFilterMode为DISABLED时为NULL
|
||||
|
||||
// 新增配置字段
|
||||
@Column(name = "config_name", length = 255)
|
||||
@@ -98,6 +97,12 @@ data class CopyTrading(
|
||||
@Column(name = "push_failed_orders", nullable = false)
|
||||
val pushFailedOrders: Boolean = false, // 推送失败订单(默认关闭)
|
||||
|
||||
@Column(name = "push_filtered_orders", nullable = false)
|
||||
val pushFilteredOrders: Boolean = false, // 推送已过滤订单(默认关闭)
|
||||
|
||||
@Column(name = "max_market_end_date")
|
||||
val maxMarketEndDate: Long? = null, // 市场截止时间限制(毫秒时间戳),仅跟单截止时间小于此时间的订单,NULL表示不启用
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
|
||||
|
||||
@@ -72,6 +72,9 @@ data class CopyTradingTemplate(
|
||||
@Column(name = "max_price", precision = 20, scale = 8)
|
||||
val maxPrice: BigDecimal? = null, // 最高价格(可选),NULL表示不限制最高价
|
||||
|
||||
@Column(name = "push_filtered_orders", nullable = false)
|
||||
val pushFilteredOrders: Boolean = false, // 推送已过滤订单(默认关闭)
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.wrbug.polymarketbot.entity
|
||||
|
||||
import com.wrbug.polymarketbot.enums.SpreadDirection
|
||||
import com.wrbug.polymarketbot.enums.SpreadDirectionConverter
|
||||
import com.wrbug.polymarketbot.enums.SpreadMode
|
||||
import com.wrbug.polymarketbot.enums.SpreadModeConverter
|
||||
import jakarta.persistence.*
|
||||
import java.math.BigDecimal
|
||||
|
||||
/**
|
||||
* 加密价差策略实体
|
||||
* 5/15 分钟 Up or Down 市场,在周期内时间窗口、价格进入区间时市价买入
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "crypto_tail_strategy")
|
||||
data class CryptoTailStrategy(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = null,
|
||||
|
||||
@Column(name = "account_id", nullable = false)
|
||||
val accountId: Long = 0L,
|
||||
|
||||
@Column(name = "name", length = 255)
|
||||
val name: String? = null,
|
||||
|
||||
@Column(name = "market_slug_prefix", nullable = false, length = 64)
|
||||
val marketSlugPrefix: String = "",
|
||||
|
||||
@Column(name = "interval_seconds", nullable = false)
|
||||
val intervalSeconds: Int = 300,
|
||||
|
||||
@Column(name = "window_start_seconds", nullable = false)
|
||||
val windowStartSeconds: Int = 0,
|
||||
|
||||
@Column(name = "window_end_seconds", nullable = false)
|
||||
val windowEndSeconds: Int = 0,
|
||||
|
||||
@Column(name = "min_price", nullable = false, precision = 20, scale = 8)
|
||||
val minPrice: BigDecimal = BigDecimal.ONE,
|
||||
|
||||
@Column(name = "max_price", nullable = false, precision = 20, scale = 8)
|
||||
val maxPrice: BigDecimal = BigDecimal.ONE,
|
||||
|
||||
@Column(name = "amount_mode", nullable = false, length = 10)
|
||||
val amountMode: String = "RATIO",
|
||||
|
||||
@Column(name = "amount_value", nullable = false, precision = 20, scale = 8)
|
||||
val amountValue: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
/** 价差模式: NONE=不校验, FIXED=固定值, AUTO=历史计算 */
|
||||
@Convert(converter = SpreadModeConverter::class)
|
||||
@Column(name = "spread_mode", nullable = false, columnDefinition = "TINYINT")
|
||||
val spreadMode: SpreadMode = SpreadMode.NONE,
|
||||
|
||||
/** 价差数值(FIXED 时必填;AUTO 时可存计算值) */
|
||||
@Column(name = "spread_value", precision = 20, scale = 8)
|
||||
val spreadValue: BigDecimal? = null,
|
||||
|
||||
/** 价差方向: MIN=最小价差(价差>=配置值触发),MAX=最大价差(价差<=配置值触发) */
|
||||
@Convert(converter = SpreadDirectionConverter::class)
|
||||
@Column(name = "spread_direction", nullable = false, columnDefinition = "TINYINT")
|
||||
val spreadDirection: SpreadDirection = SpreadDirection.MIN,
|
||||
|
||||
@Column(name = "enabled", nullable = false)
|
||||
val enabled: Boolean = true,
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
var updatedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.wrbug.polymarketbot.entity
|
||||
|
||||
import jakarta.persistence.*
|
||||
import java.math.BigDecimal
|
||||
import com.wrbug.polymarketbot.util.toSafeBigDecimal
|
||||
|
||||
/**
|
||||
* 加密价差策略触发记录
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "crypto_tail_strategy_trigger")
|
||||
data class CryptoTailStrategyTrigger(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = null,
|
||||
|
||||
@Column(name = "strategy_id", nullable = false)
|
||||
val strategyId: Long = 0L,
|
||||
|
||||
@Column(name = "period_start_unix", nullable = false)
|
||||
val periodStartUnix: Long = 0L,
|
||||
|
||||
@Column(name = "market_title", length = 500)
|
||||
val marketTitle: String? = null,
|
||||
|
||||
@Column(name = "outcome_index", nullable = false)
|
||||
val outcomeIndex: Int = 0,
|
||||
|
||||
@Column(name = "trigger_price", nullable = false, precision = 20, scale = 8)
|
||||
val triggerPrice: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "amount_usdc", nullable = false, precision = 20, scale = 8)
|
||||
val amountUsdc: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "order_id", length = 128)
|
||||
val orderId: String? = null,
|
||||
|
||||
@Column(name = "condition_id", length = 66)
|
||||
val conditionId: String? = null,
|
||||
|
||||
@Column(name = "resolved", nullable = false)
|
||||
val resolved: Boolean = false,
|
||||
|
||||
@Column(name = "winner_outcome_index")
|
||||
val winnerOutcomeIndex: Int? = null,
|
||||
|
||||
@Column(name = "realized_pnl", precision = 20, scale = 8)
|
||||
val realizedPnl: BigDecimal? = null,
|
||||
|
||||
@Column(name = "settled_at")
|
||||
val settledAt: Long? = null,
|
||||
|
||||
@Column(name = "status", nullable = false, length = 20)
|
||||
val status: String = "success",
|
||||
|
||||
@Column(name = "fail_reason", length = 500)
|
||||
val failReason: String? = null,
|
||||
|
||||
@Column(name = "trigger_type", nullable = false, length = 20)
|
||||
val triggerType: String = "AUTO",
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
|
||||
@Column(name = "notification_sent", nullable = false)
|
||||
var notificationSent: Boolean = false
|
||||
)
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.wrbug.polymarketbot.entity
|
||||
|
||||
import com.wrbug.polymarketbot.enums.LeaderPoolStatus
|
||||
import com.wrbug.polymarketbot.enums.LeaderResearchState
|
||||
import jakarta.persistence.*
|
||||
import java.math.BigDecimal
|
||||
|
||||
@Entity
|
||||
@Table(name = "copy_trading_leader_pool")
|
||||
data class LeaderPool(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = null,
|
||||
|
||||
@Column(name = "leader_id", nullable = false)
|
||||
val leaderId: Long,
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "status", nullable = false, length = 20, columnDefinition = "VARCHAR(20)")
|
||||
val status: LeaderPoolStatus = LeaderPoolStatus.CANDIDATE,
|
||||
|
||||
@Column(name = "source", nullable = false, length = 50)
|
||||
val source: String = "MANUAL",
|
||||
|
||||
@Column(name = "source_rank")
|
||||
val sourceRank: Int? = null,
|
||||
|
||||
@Column(name = "score", precision = 20, scale = 8)
|
||||
val score: BigDecimal? = null,
|
||||
|
||||
@Column(name = "reason", columnDefinition = "TEXT")
|
||||
val reason: String? = null,
|
||||
|
||||
@Column(name = "notes", columnDefinition = "TEXT")
|
||||
val notes: String? = null,
|
||||
|
||||
@Column(name = "suggested_fixed_amount", nullable = false, precision = 20, scale = 8)
|
||||
val suggestedFixedAmount: BigDecimal = BigDecimal("1.00000000"),
|
||||
|
||||
@Column(name = "suggested_max_daily_orders", nullable = false)
|
||||
val suggestedMaxDailyOrders: Int = 10,
|
||||
|
||||
@Column(name = "suggested_max_daily_loss", nullable = false, precision = 20, scale = 8)
|
||||
val suggestedMaxDailyLoss: BigDecimal = BigDecimal("5.00000000"),
|
||||
|
||||
@Column(name = "suggested_min_price", precision = 20, scale = 8)
|
||||
val suggestedMinPrice: BigDecimal? = BigDecimal("0.10000000"),
|
||||
|
||||
@Column(name = "suggested_max_price", precision = 20, scale = 8)
|
||||
val suggestedMaxPrice: BigDecimal? = BigDecimal("0.80000000"),
|
||||
|
||||
@Column(name = "suggested_max_position_value", precision = 20, scale = 8)
|
||||
val suggestedMaxPositionValue: BigDecimal? = BigDecimal("5.00000000"),
|
||||
|
||||
@Column(name = "last_reviewed_at")
|
||||
val lastReviewedAt: Long? = null,
|
||||
|
||||
@Column(name = "last_promoted_at")
|
||||
val lastPromotedAt: Long? = null,
|
||||
|
||||
@Column(name = "cooldown_until")
|
||||
val cooldownUntil: Long? = null,
|
||||
|
||||
@Column(name = "locked", nullable = false)
|
||||
val locked: Boolean = false,
|
||||
|
||||
@Column(name = "research_candidate_id")
|
||||
val researchCandidateId: Long? = null,
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "research_state", length = 30, columnDefinition = "VARCHAR(30)")
|
||||
val researchState: LeaderResearchState? = null,
|
||||
|
||||
@Column(name = "research_badge", length = 50)
|
||||
val researchBadge: String? = null,
|
||||
|
||||
@Column(name = "research_summary", columnDefinition = "TEXT")
|
||||
val researchSummary: String? = null,
|
||||
|
||||
@Column(name = "research_score", precision = 20, scale = 8)
|
||||
val researchScore: BigDecimal? = null,
|
||||
|
||||
@Column(name = "research_updated_at")
|
||||
val researchUpdatedAt: Long? = null,
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
var updatedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
@@ -0,0 +1,600 @@
|
||||
package com.wrbug.polymarketbot.entity
|
||||
|
||||
import com.wrbug.polymarketbot.enums.*
|
||||
import jakarta.persistence.*
|
||||
import java.math.BigDecimal
|
||||
|
||||
@Entity
|
||||
@Table(name = "leader_research_run")
|
||||
data class LeaderResearchRun(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = null,
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "status", nullable = false, length = 30, columnDefinition = "VARCHAR(30)")
|
||||
val status: LeaderResearchRunStatus = LeaderResearchRunStatus.RUNNING,
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "trigger_type", nullable = false, length = 30, columnDefinition = "VARCHAR(30)")
|
||||
val triggerType: LeaderResearchTriggerType = LeaderResearchTriggerType.MANUAL,
|
||||
|
||||
@Column(name = "dry_run", nullable = false)
|
||||
val dryRun: Boolean = false,
|
||||
|
||||
@Column(name = "started_at", nullable = false)
|
||||
val startedAt: Long = System.currentTimeMillis(),
|
||||
|
||||
@Column(name = "finished_at")
|
||||
val finishedAt: Long? = null,
|
||||
|
||||
@Column(name = "duration_ms")
|
||||
val durationMs: Long? = null,
|
||||
|
||||
@Column(name = "source_counts_json", columnDefinition = "TEXT")
|
||||
val sourceCountsJson: String? = null,
|
||||
|
||||
@Column(name = "candidate_counts_json", columnDefinition = "TEXT")
|
||||
val candidateCountsJson: String? = null,
|
||||
|
||||
@Column(name = "error_class")
|
||||
val errorClass: String? = null,
|
||||
|
||||
@Column(name = "error_message", columnDefinition = "TEXT")
|
||||
val errorMessage: String? = null,
|
||||
|
||||
@Column(name = "partial_failure", nullable = false)
|
||||
val partialFailure: Boolean = false,
|
||||
|
||||
@Column(name = "skipped_reason")
|
||||
val skippedReason: String? = null,
|
||||
|
||||
@Column(name = "last_event_cursor")
|
||||
val lastEventCursor: String? = null,
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
val updatedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
@Entity
|
||||
@Table(name = "leader_research_candidate")
|
||||
data class LeaderResearchCandidate(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = null,
|
||||
|
||||
@Column(name = "normalized_wallet", nullable = false, length = 42, unique = true)
|
||||
val normalizedWallet: String,
|
||||
|
||||
@Column(name = "leader_id")
|
||||
val leaderId: Long? = null,
|
||||
|
||||
@Column(name = "pool_id")
|
||||
val poolId: Long? = null,
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "research_state", nullable = false, length = 30, columnDefinition = "VARCHAR(30)")
|
||||
val researchState: LeaderResearchState = LeaderResearchState.DISCOVERED,
|
||||
|
||||
@Column(name = "source", nullable = false, length = 50)
|
||||
val source: String = LeaderResearchSourceType.ACTIVITY_DERIVED.name,
|
||||
|
||||
@Column(name = "source_rank")
|
||||
val sourceRank: Int? = null,
|
||||
|
||||
@Column(name = "score", precision = 20, scale = 8)
|
||||
val score: BigDecimal? = null,
|
||||
|
||||
@Column(name = "score_version", length = 100)
|
||||
val scoreVersion: String? = null,
|
||||
|
||||
@Column(name = "reason", columnDefinition = "TEXT")
|
||||
val reason: String? = null,
|
||||
|
||||
@Column(name = "risk_flags", columnDefinition = "TEXT")
|
||||
val riskFlags: String? = null,
|
||||
|
||||
@Column(name = "locked", nullable = false)
|
||||
val locked: Boolean = false,
|
||||
|
||||
@Column(name = "agent_owned", nullable = false)
|
||||
val agentOwned: Boolean = true,
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "provenance", nullable = false, length = 50, columnDefinition = "VARCHAR(50)")
|
||||
val provenance: LeaderCandidateProvenance = LeaderCandidateProvenance.AGENT_CREATED,
|
||||
|
||||
@Column(name = "source_evidence", columnDefinition = "TEXT")
|
||||
val sourceEvidence: String? = null,
|
||||
|
||||
@Column(name = "first_seen_at", nullable = false)
|
||||
val firstSeenAt: Long = System.currentTimeMillis(),
|
||||
|
||||
@Column(name = "last_source_seen_at")
|
||||
val lastSourceSeenAt: Long? = null,
|
||||
|
||||
@Column(name = "last_scored_at")
|
||||
val lastScoredAt: Long? = null,
|
||||
|
||||
@Column(name = "cooldown_until")
|
||||
val cooldownUntil: Long? = null,
|
||||
|
||||
@Column(name = "cooldown_count", nullable = false)
|
||||
val cooldownCount: Int = 0,
|
||||
|
||||
@Column(name = "last_transition_at")
|
||||
val lastTransitionAt: Long? = null,
|
||||
|
||||
@Column(name = "trial_ready_at")
|
||||
val trialReadyAt: Long? = null,
|
||||
|
||||
@Column(name = "retired_at")
|
||||
val retiredAt: Long? = null,
|
||||
|
||||
@Column(name = "last_paper_session_id")
|
||||
val lastPaperSessionId: Long? = null,
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
val updatedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
@Entity
|
||||
@Table(name = "leader_research_score")
|
||||
data class LeaderResearchScore(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = null,
|
||||
|
||||
@Column(name = "candidate_id", nullable = false)
|
||||
val candidateId: Long,
|
||||
|
||||
@Column(name = "run_id")
|
||||
val runId: Long? = null,
|
||||
|
||||
@Column(name = "score_version", nullable = false, length = 100)
|
||||
val scoreVersion: String,
|
||||
|
||||
@Column(name = "total_score", nullable = false, precision = 20, scale = 8)
|
||||
val totalScore: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "profit_signal", nullable = false, precision = 20, scale = 8)
|
||||
val profitSignal: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "repeatability", nullable = false, precision = 20, scale = 8)
|
||||
val repeatability: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "liquidity_fit", nullable = false, precision = 20, scale = 8)
|
||||
val liquidityFit: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "entry_price_fit", nullable = false, precision = 20, scale = 8)
|
||||
val entryPriceFit: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "slippage_risk", nullable = false, precision = 20, scale = 8)
|
||||
val slippageRisk: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "holding_period_fit", nullable = false, precision = 20, scale = 8)
|
||||
val holdingPeriodFit: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "market_type_risk", nullable = false, precision = 20, scale = 8)
|
||||
val marketTypeRisk: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "drawdown_risk", nullable = false, precision = 20, scale = 8)
|
||||
val drawdownRisk: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "exit_liquidity_risk", nullable = false, precision = 20, scale = 8)
|
||||
val exitLiquidityRisk: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "data_freshness", nullable = false, precision = 20, scale = 8)
|
||||
val dataFreshness: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "filter_pass_rate", nullable = false, precision = 20, scale = 8)
|
||||
val filterPassRate: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "sample_trade_count", nullable = false)
|
||||
val sampleTradeCount: Int = 0,
|
||||
|
||||
@Column(name = "reason", columnDefinition = "TEXT")
|
||||
val reason: String? = null,
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
@Entity
|
||||
@Table(name = "leader_research_event")
|
||||
data class LeaderResearchEvent(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = null,
|
||||
|
||||
@Column(name = "candidate_id")
|
||||
val candidateId: Long? = null,
|
||||
|
||||
@Column(name = "run_id")
|
||||
val runId: Long? = null,
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "event_type", nullable = false, length = 50, columnDefinition = "VARCHAR(50)")
|
||||
val eventType: LeaderResearchEventType,
|
||||
|
||||
@Column(name = "reason", columnDefinition = "TEXT")
|
||||
val reason: String? = null,
|
||||
|
||||
@Column(name = "payload_summary", columnDefinition = "TEXT")
|
||||
val payloadSummary: String? = null,
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "notification_status", nullable = false, length = 30, columnDefinition = "VARCHAR(30)")
|
||||
val notificationStatus: LeaderResearchNotificationStatus = LeaderResearchNotificationStatus.PENDING,
|
||||
|
||||
@Column(name = "notification_error", columnDefinition = "TEXT")
|
||||
val notificationError: String? = null,
|
||||
|
||||
@Column(name = "dedupe_key")
|
||||
val dedupeKey: String? = null,
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
|
||||
@Column(name = "notified_at")
|
||||
val notifiedAt: Long? = null
|
||||
)
|
||||
|
||||
@Entity
|
||||
@Table(name = "leader_research_source_state")
|
||||
data class LeaderResearchSourceState(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = null,
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "source_type", nullable = false, length = 50, unique = true, columnDefinition = "VARCHAR(50)")
|
||||
val sourceType: LeaderResearchSourceType,
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "status", nullable = false, length = 30, columnDefinition = "VARCHAR(30)")
|
||||
val status: LeaderResearchSourceStatus = LeaderResearchSourceStatus.DISABLED,
|
||||
|
||||
@Column(name = "last_success_at")
|
||||
val lastSuccessAt: Long? = null,
|
||||
|
||||
@Column(name = "last_failure_at")
|
||||
val lastFailureAt: Long? = null,
|
||||
|
||||
@Column(name = "last_run_at")
|
||||
val lastRunAt: Long? = null,
|
||||
|
||||
@Column(name = "last_candidate_count", nullable = false)
|
||||
val lastCandidateCount: Int = 0,
|
||||
|
||||
@Column(name = "error_class")
|
||||
val errorClass: String? = null,
|
||||
|
||||
@Column(name = "error_message", columnDefinition = "TEXT")
|
||||
val errorMessage: String? = null,
|
||||
|
||||
@Column(name = "stale", nullable = false)
|
||||
val stale: Boolean = false,
|
||||
|
||||
@Column(name = "disabled_reason")
|
||||
val disabledReason: String? = null,
|
||||
|
||||
@Column(name = "last_cursor")
|
||||
val lastCursor: String? = null,
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
val updatedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
@Entity
|
||||
@Table(name = "leader_activity_event")
|
||||
data class LeaderActivityEvent(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = null,
|
||||
|
||||
@Column(name = "source", nullable = false, length = 50)
|
||||
val source: String,
|
||||
|
||||
@Column(name = "source_event_id")
|
||||
val sourceEventId: String? = null,
|
||||
|
||||
@Column(name = "stable_event_key", nullable = false, unique = true)
|
||||
val stableEventKey: String,
|
||||
|
||||
@Column(name = "normalized_wallet", length = 42)
|
||||
val normalizedWallet: String? = null,
|
||||
|
||||
@Column(name = "market_id")
|
||||
val marketId: String? = null,
|
||||
|
||||
@Column(name = "market_title")
|
||||
val marketTitle: String? = null,
|
||||
|
||||
@Column(name = "market_slug")
|
||||
val marketSlug: String? = null,
|
||||
|
||||
@Column(name = "asset")
|
||||
val asset: String? = null,
|
||||
|
||||
@Column(name = "side", length = 20)
|
||||
val side: String? = null,
|
||||
|
||||
@Column(name = "outcome")
|
||||
val outcome: String? = null,
|
||||
|
||||
@Column(name = "outcome_index")
|
||||
val outcomeIndex: Int? = null,
|
||||
|
||||
@Column(name = "price", precision = 20, scale = 8)
|
||||
val price: BigDecimal? = null,
|
||||
|
||||
@Column(name = "size", precision = 20, scale = 8)
|
||||
val size: BigDecimal? = null,
|
||||
|
||||
@Column(name = "amount", precision = 20, scale = 8)
|
||||
val amount: BigDecimal? = null,
|
||||
|
||||
@Column(name = "event_time", nullable = false)
|
||||
val eventTime: Long,
|
||||
|
||||
@Column(name = "raw_payload_hash", nullable = false, length = 128)
|
||||
val rawPayloadHash: String = "",
|
||||
|
||||
@Column(name = "payload_summary", columnDefinition = "TEXT")
|
||||
val payloadSummary: String? = null,
|
||||
|
||||
@Column(name = "usable_for_discovery", nullable = false)
|
||||
val usableForDiscovery: Boolean = false,
|
||||
|
||||
@Column(name = "usable_for_paper", nullable = false)
|
||||
val usableForPaper: Boolean = false,
|
||||
|
||||
@Column(name = "unusable_reason")
|
||||
val unusableReason: String? = null,
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "paper_processing_status", nullable = false, length = 30, columnDefinition = "VARCHAR(30)")
|
||||
val paperProcessingStatus: LeaderPaperProcessingStatus = LeaderPaperProcessingStatus.NEW,
|
||||
|
||||
@Column(name = "processing_attempts", nullable = false)
|
||||
val processingAttempts: Int = 0,
|
||||
|
||||
@Column(name = "paper_processing_started_at")
|
||||
val paperProcessingStartedAt: Long? = null,
|
||||
|
||||
@Column(name = "paper_processed_at")
|
||||
val paperProcessedAt: Long? = null,
|
||||
|
||||
@Column(name = "last_processing_error", columnDefinition = "TEXT")
|
||||
val lastProcessingError: String? = null,
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
val updatedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
@Entity
|
||||
@Table(name = "leader_paper_session")
|
||||
data class LeaderPaperSession(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = null,
|
||||
|
||||
@Column(name = "candidate_id", nullable = false)
|
||||
val candidateId: Long,
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "status", nullable = false, length = 30, columnDefinition = "VARCHAR(30)")
|
||||
val status: LeaderPaperSessionStatus = LeaderPaperSessionStatus.ACTIVE,
|
||||
|
||||
@Column(name = "started_at", nullable = false)
|
||||
val startedAt: Long = System.currentTimeMillis(),
|
||||
|
||||
@Column(name = "ended_at")
|
||||
val endedAt: Long? = null,
|
||||
|
||||
@Column(name = "trade_count", nullable = false)
|
||||
val tradeCount: Int = 0,
|
||||
|
||||
@Column(name = "filtered_count", nullable = false)
|
||||
val filteredCount: Int = 0,
|
||||
|
||||
@Column(name = "open_exposure", nullable = false, precision = 20, scale = 8)
|
||||
val openExposure: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "total_realized_pnl", nullable = false, precision = 20, scale = 8)
|
||||
val totalRealizedPnl: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "total_unrealized_pnl", nullable = false, precision = 20, scale = 8)
|
||||
val totalUnrealizedPnl: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "copyable_pnl", nullable = false, precision = 20, scale = 8)
|
||||
val copyablePnl: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "max_drawdown", nullable = false, precision = 20, scale = 8)
|
||||
val maxDrawdown: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "unknown_valuation_exposure", nullable = false, precision = 20, scale = 8)
|
||||
val unknownValuationExposure: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "confirmed_zero_exposure", nullable = false, precision = 20, scale = 8)
|
||||
val confirmedZeroExposure: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "filtered_ratio", nullable = false, precision = 20, scale = 8)
|
||||
val filteredRatio: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "last_processed_event_time")
|
||||
val lastProcessedEventTime: Long? = null,
|
||||
|
||||
@Column(name = "score_snapshot", precision = 20, scale = 8)
|
||||
val scoreSnapshot: BigDecimal? = null,
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
val updatedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
@Entity
|
||||
@Table(name = "leader_paper_trade")
|
||||
data class LeaderPaperTrade(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = null,
|
||||
|
||||
@Column(name = "session_id", nullable = false)
|
||||
val sessionId: Long,
|
||||
|
||||
@Column(name = "candidate_id", nullable = false)
|
||||
val candidateId: Long,
|
||||
|
||||
@Column(name = "activity_event_id")
|
||||
val activityEventId: Long? = null,
|
||||
|
||||
@Column(name = "leader_trade_id", nullable = false)
|
||||
val leaderTradeId: String,
|
||||
|
||||
@Column(name = "market_id", nullable = false)
|
||||
val marketId: String,
|
||||
|
||||
@Column(name = "market_title")
|
||||
val marketTitle: String? = null,
|
||||
|
||||
@Column(name = "market_slug")
|
||||
val marketSlug: String? = null,
|
||||
|
||||
@Column(name = "side", nullable = false, length = 20)
|
||||
val side: String,
|
||||
|
||||
@Column(name = "outcome")
|
||||
val outcome: String? = null,
|
||||
|
||||
@Column(name = "outcome_index")
|
||||
val outcomeIndex: Int? = null,
|
||||
|
||||
@Column(name = "leader_price", precision = 20, scale = 8)
|
||||
val leaderPrice: BigDecimal? = null,
|
||||
|
||||
@Column(name = "leader_size", precision = 20, scale = 8)
|
||||
val leaderSize: BigDecimal? = null,
|
||||
|
||||
@Column(name = "simulated_price", precision = 20, scale = 8)
|
||||
val simulatedPrice: BigDecimal? = null,
|
||||
|
||||
@Column(name = "simulated_size", precision = 20, scale = 8)
|
||||
val simulatedSize: BigDecimal? = null,
|
||||
|
||||
@Column(name = "simulated_amount", precision = 20, scale = 8)
|
||||
val simulatedAmount: BigDecimal? = null,
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "fill_assumption", nullable = false, length = 30, columnDefinition = "VARCHAR(30)")
|
||||
val fillAssumption: LeaderPaperFillAssumption = LeaderPaperFillAssumption.LEADER_PRICE,
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "quote_confidence", nullable = false, length = 30, columnDefinition = "VARCHAR(30)")
|
||||
val quoteConfidence: LeaderResearchQuoteConfidence = LeaderResearchQuoteConfidence.UNKNOWN,
|
||||
|
||||
@Column(name = "quote_source", length = 50)
|
||||
val quoteSource: String? = null,
|
||||
|
||||
@Column(name = "quote_timestamp")
|
||||
val quoteTimestamp: Long? = null,
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "filter_result", nullable = false, length = 30, columnDefinition = "VARCHAR(30)")
|
||||
val filterResult: LeaderPaperFilterResult = LeaderPaperFilterResult.PASSED,
|
||||
|
||||
@Column(name = "filter_reason", columnDefinition = "TEXT")
|
||||
val filterReason: String? = null,
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "valuation_status", nullable = false, length = 30, columnDefinition = "VARCHAR(30)")
|
||||
val valuationStatus: LeaderResearchValuationStatus = LeaderResearchValuationStatus.UNKNOWN,
|
||||
|
||||
@Column(name = "realized_pnl", precision = 20, scale = 8)
|
||||
val realizedPnl: BigDecimal? = null,
|
||||
|
||||
@Column(name = "event_time", nullable = false)
|
||||
val eventTime: Long,
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
@Entity
|
||||
@Table(name = "leader_paper_position")
|
||||
data class LeaderPaperPosition(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = null,
|
||||
|
||||
@Column(name = "session_id", nullable = false)
|
||||
val sessionId: Long,
|
||||
|
||||
@Column(name = "candidate_id", nullable = false)
|
||||
val candidateId: Long,
|
||||
|
||||
@Column(name = "market_id", nullable = false)
|
||||
val marketId: String,
|
||||
|
||||
@Column(name = "outcome")
|
||||
val outcome: String? = null,
|
||||
|
||||
@Column(name = "outcome_index")
|
||||
val outcomeIndex: Int? = null,
|
||||
|
||||
@Column(name = "quantity", nullable = false, precision = 20, scale = 8)
|
||||
val quantity: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "cost", nullable = false, precision = 20, scale = 8)
|
||||
val cost: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "avg_price", nullable = false, precision = 20, scale = 8)
|
||||
val avgPrice: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "current_price", precision = 20, scale = 8)
|
||||
val currentPrice: BigDecimal? = null,
|
||||
|
||||
@Column(name = "current_value", nullable = false, precision = 20, scale = 8)
|
||||
val currentValue: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "realized_pnl", nullable = false, precision = 20, scale = 8)
|
||||
val realizedPnl: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Column(name = "unrealized_pnl", nullable = false, precision = 20, scale = 8)
|
||||
val unrealizedPnl: BigDecimal = BigDecimal.ZERO,
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "valuation_status", nullable = false, length = 30, columnDefinition = "VARCHAR(30)")
|
||||
val valuationStatus: LeaderResearchValuationStatus = LeaderResearchValuationStatus.UNKNOWN,
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "quote_confidence", nullable = false, length = 30, columnDefinition = "VARCHAR(30)")
|
||||
val quoteConfidence: LeaderResearchQuoteConfidence = LeaderResearchQuoteConfidence.UNKNOWN,
|
||||
|
||||
@Column(name = "quote_source", length = 50)
|
||||
val quoteSource: String? = null,
|
||||
|
||||
@Column(name = "quote_timestamp")
|
||||
val quoteTimestamp: Long? = null,
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
val updatedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.wrbug.polymarketbot.entity
|
||||
|
||||
import jakarta.persistence.*
|
||||
|
||||
/**
|
||||
* 市场信息实体
|
||||
* 用于缓存市场的基本信息(名称、slug等)
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "markets", indexes = [
|
||||
Index(name = "idx_market_id", columnList = "market_id", unique = true)
|
||||
])
|
||||
data class Market(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = null,
|
||||
|
||||
@Column(name = "market_id", unique = true, nullable = false, length = 100)
|
||||
val marketId: String, // 市场ID(condition ID)
|
||||
|
||||
@Column(name = "title", nullable = false, length = 500)
|
||||
val title: String, // 市场名称(question)
|
||||
|
||||
@Column(name = "slug", length = 200)
|
||||
val slug: String? = null, // 市场slug(用于显示)
|
||||
|
||||
@Column(name = "event_slug", length = 200)
|
||||
val eventSlug: String? = null, // 跳转用的 slug(从 events[0].slug 获取)
|
||||
|
||||
@Column(name = "category", length = 50)
|
||||
val category: String? = null, // 市场分类
|
||||
|
||||
@Column(name = "icon", length = 500)
|
||||
val icon: String? = null, // 市场图标URL
|
||||
|
||||
@Column(name = "image", length = 500)
|
||||
val image: String? = null, // 市场图片URL
|
||||
|
||||
@Column(name = "description", columnDefinition = "TEXT")
|
||||
val description: String? = null, // 市场描述
|
||||
|
||||
@Column(name = "active", nullable = false)
|
||||
val active: Boolean = true, // 是否活跃
|
||||
|
||||
@Column(name = "closed", nullable = false)
|
||||
val closed: Boolean = false, // 是否已关闭
|
||||
|
||||
@Column(name = "archived", nullable = false)
|
||||
val archived: Boolean = false, // 是否已归档
|
||||
|
||||
@Column(name = "end_date")
|
||||
val endDate: Long? = null, // 市场截止时间(毫秒时间戳)
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
var updatedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.wrbug.polymarketbot.entity
|
||||
|
||||
import jakarta.persistence.*
|
||||
|
||||
/**
|
||||
* 消息推送模板实体
|
||||
* 用于存储用户自定义的消息模板
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "notification_templates")
|
||||
data class NotificationTemplate(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = null,
|
||||
|
||||
@Column(name = "template_type", unique = true, nullable = false, length = 50)
|
||||
val templateType: String, // ORDER_SUCCESS, ORDER_FAILED, ORDER_FILTERED, CRYPTO_TAIL_SUCCESS, REDEEM_SUCCESS, REDEEM_NO_RETURN
|
||||
|
||||
@Column(name = "template_content", nullable = false, columnDefinition = "TEXT")
|
||||
var templateContent: String, // 模板内容,支持 {{variable}} 变量
|
||||
|
||||
@Column(name = "is_default", nullable = false)
|
||||
var isDefault: Boolean = false, // 是否使用默认模板
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
var updatedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
@@ -110,6 +110,18 @@ enum class ErrorCode(
|
||||
COPY_TRADING_DISABLED(4202, "跟单关系已禁用", "error.copy_trading_disabled"),
|
||||
COPY_TRADING_ENABLED(4203, "跟单关系已启用", "error.copy_trading_enabled"),
|
||||
NO_ENABLED_COPY_TRADINGS(4204, "没有启用的跟单关系", "error.no_enabled_copy_tradings"),
|
||||
LEADER_POOL_NOT_FOUND(4251, "Leader 池项不存在", "error.leader_pool_not_found"),
|
||||
LEADER_POOL_ALREADY_EXISTS(4252, "Leader 已在池子中", "error.leader_pool_already_exists"),
|
||||
LEADER_POOL_DUPLICATE_TRIAL_CONFIG(4253, "该账户已存在此 Leader 的跟单配置", "error.leader_pool_duplicate_trial_config"),
|
||||
LEADER_POOL_CONFIRM_REQUIRED(4254, "立即启用试跟配置需要显式确认", "error.leader_pool_confirm_required"),
|
||||
LEADER_RESEARCH_CANDIDATE_NOT_FOUND(4261, "研究候选不存在", "error.leader_research_candidate_not_found"),
|
||||
LEADER_RESEARCH_CANDIDATE_NOT_READY(4262, "研究候选尚未进入试跟建议状态", "error.leader_research_candidate_not_ready"),
|
||||
LEADER_RESEARCH_APPROVAL_CONFIRM_REQUIRED(4263, "创建禁用试跟配置需要显式确认", "error.leader_research_approval_confirm_required"),
|
||||
LEADER_RESEARCH_DUPLICATE_TRIAL_CONFIG(4264, "该账户已存在此 Leader 的跟单配置", "error.leader_research_duplicate_trial_config"),
|
||||
LEADER_RESEARCH_REAL_MONEY_FORBIDDEN(4265, "研究 Agent 不允许自动启用真钱跟单", "error.leader_research_real_money_forbidden"),
|
||||
LEADER_RESEARCH_CANDIDATE_LOCKED(4266, "研究候选已锁定", "error.leader_research_candidate_locked"),
|
||||
LEADER_RESEARCH_SOURCE_UNAVAILABLE(4267, "研究来源不可用", "error.leader_research_source_unavailable"),
|
||||
LEADER_RESEARCH_PAPER_VALUATION_UNAVAILABLE(4268, "纸跟估值不可用", "error.leader_research_paper_valuation_unavailable"),
|
||||
|
||||
// 订单相关 (4301-4399)
|
||||
ORDER_CREATE_FAILED(4301, "创建订单失败", "error.order_create_failed"),
|
||||
@@ -158,6 +170,13 @@ enum class ErrorCode(
|
||||
ACCOUNT_BALANCE_FETCH_FAILED(4707, "查询账户余额失败", "error.account_balance_fetch_failed"),
|
||||
ACCOUNT_POSITIONS_FETCH_FAILED(4708, "查询仓位列表失败", "error.account_positions_fetch_failed"),
|
||||
|
||||
// 加密价差策略 (4710-4729)
|
||||
CRYPTO_TAIL_STRATEGY_NOT_FOUND(4710, "加密价差策略不存在", "error.crypto_tail_strategy_not_found"),
|
||||
CRYPTO_TAIL_STRATEGY_WINDOW_INVALID(4711, "时间区间开始不能大于结束", "error.crypto_tail_strategy_window_invalid"),
|
||||
CRYPTO_TAIL_STRATEGY_WINDOW_EXCEED(4712, "时间区间不能超过周期长度", "error.crypto_tail_strategy_window_exceed"),
|
||||
CRYPTO_TAIL_STRATEGY_INTERVAL_INVALID(4713, "周期仅支持 300 或 900 秒", "error.crypto_tail_strategy_interval_invalid"),
|
||||
CRYPTO_TAIL_STRATEGY_AMOUNT_MODE_INVALID(4714, "投入方式仅支持 RATIO 或 FIXED", "error.crypto_tail_strategy_amount_mode_invalid"),
|
||||
|
||||
// 统计相关 (4801-4899)
|
||||
STATISTICS_FETCH_FAILED(4801, "获取统计信息失败", "error.statistics_fetch_failed"),
|
||||
ORDER_LIST_FETCH_FAILED(4802, "查询订单列表失败", "error.order_list_fetch_failed"),
|
||||
@@ -206,6 +225,12 @@ enum class ErrorCode(
|
||||
SERVER_COPY_TRADING_DELETE_FAILED(5403, "删除跟单失败", "error.server.copy_trading_delete_failed"),
|
||||
SERVER_COPY_TRADING_LIST_FETCH_FAILED(5404, "查询跟单列表失败", "error.server.copy_trading_list_fetch_failed"),
|
||||
SERVER_COPY_TRADING_TEMPLATES_FETCH_FAILED(5405, "查询钱包绑定的模板失败", "error.server.copy_trading_templates_fetch_failed"),
|
||||
SERVER_LEADER_POOL_LIST_FETCH_FAILED(5451, "查询 Leader 池失败", "error.server.leader_pool_list_fetch_failed"),
|
||||
SERVER_LEADER_POOL_SAVE_FAILED(5452, "保存 Leader 池失败", "error.server.leader_pool_save_failed"),
|
||||
SERVER_LEADER_POOL_CREATE_TRIAL_FAILED(5453, "创建 Leader 池试跟配置失败", "error.server.leader_pool_create_trial_failed"),
|
||||
SERVER_LEADER_RESEARCH_RUN_FAILED(5454, "运行 Leader Research Agent 失败", "error.server.leader_research_run_failed"),
|
||||
SERVER_LEADER_RESEARCH_FETCH_FAILED(5455, "查询 Leader Research 数据失败", "error.server.leader_research_fetch_failed"),
|
||||
SERVER_LEADER_RESEARCH_APPROVAL_FAILED(5456, "创建禁用试跟配置失败", "error.server.leader_research_approval_failed"),
|
||||
|
||||
// 市场服务错误 (5501-5599)
|
||||
SERVER_MARKET_PRICE_FETCH_FAILED(5501, "获取市场价格失败", "error.server.market_price_fetch_failed"),
|
||||
@@ -231,7 +256,33 @@ enum class ErrorCode(
|
||||
SERVER_ORDER_TRACKING_PROCESS_FAILED(5901, "处理订单跟踪失败", "error.server.order_tracking_process_failed"),
|
||||
SERVER_ORDER_TRACKING_BUY_FAILED(5902, "处理买入订单失败", "error.server.order_tracking_buy_failed"),
|
||||
SERVER_ORDER_TRACKING_SELL_FAILED(5903, "处理卖出订单失败", "error.server.order_tracking_sell_failed"),
|
||||
SERVER_ORDER_TRACKING_MATCH_FAILED(5904, "订单匹配失败", "error.server.order_tracking_match_failed");
|
||||
SERVER_ORDER_TRACKING_MATCH_FAILED(5904, "订单匹配失败", "error.server.order_tracking_match_failed"),
|
||||
|
||||
// 回测服务错误 (4601-4699)
|
||||
BACKTEST_TASK_NOT_FOUND(4601, "回测任务不存在", "error.backtest.task_not_found"),
|
||||
BACKTEST_LEADER_NOT_FOUND(4602, "Leader不存在", "error.backtest.leader_not_found"),
|
||||
BACKTEST_DAYS_INVALID(4603, "回测天数超出限制", "error.backtest.days_invalid"),
|
||||
BACKTEST_INITIAL_BALANCE_INVALID(4604, "初始金额无效", "error.backtest.initial_balance_invalid"),
|
||||
BACKTEST_TASK_RUNNING(4605, "回测任务正在运行,无法删除", "error.backtest.task_running"),
|
||||
BACKTEST_TASK_NOT_COMPLETED(4606, "仅支持对已完成的回测任务重新测试", "error.backtest.task_not_completed"),
|
||||
SERVER_BACKTEST_CREATE_FAILED(5603, "创建回测任务失败", "error.server.backtest_create_failed"),
|
||||
SERVER_BACKTEST_UPDATE_FAILED(5604, "更新回测任务失败", "error.server.backtest_update_failed"),
|
||||
SERVER_BACKTEST_DELETE_FAILED(5605, "删除回测任务失败", "error.server.backtest_delete_failed"),
|
||||
SERVER_BACKTEST_LIST_FETCH_FAILED(5606, "查询回测列表失败", "error.server.backtest_list_fetch_failed"),
|
||||
SERVER_BACKTEST_DETAIL_FETCH_FAILED(5607, "查询回测详情失败", "error.server.backtest_detail_fetch_failed"),
|
||||
SERVER_BACKTEST_TRADES_FETCH_FAILED(5608, "查询回测交易记录失败", "error.server.backtest_trades_fetch_failed"),
|
||||
SERVER_BACKTEST_EXECUTE_FAILED(5609, "回测执行失败", "error.server.backtest_execute_failed"),
|
||||
SERVER_BACKTEST_HISTORICAL_DATA_FETCH_FAILED(5610, "历史数据获取失败", "error.server.backtest_historical_data_fetch_failed"),
|
||||
SERVER_BACKTEST_STOP_FAILED(5611, "停止回测任务失败", "error.server.backtest_stop_failed"),
|
||||
SERVER_BACKTEST_RETRY_FAILED(5612, "重试回测任务失败", "error.server.backtest_retry_failed"),
|
||||
SERVER_BACKTEST_RERUN_FAILED(5613, "按配置重新测试失败", "error.server.backtest_rerun_failed"),
|
||||
|
||||
// 加密价差策略服务 (5620-5629)
|
||||
SERVER_CRYPTO_TAIL_STRATEGY_CREATE_FAILED(5620, "创建加密价差策略失败", "error.server.crypto_tail_strategy_create_failed"),
|
||||
SERVER_CRYPTO_TAIL_STRATEGY_UPDATE_FAILED(5621, "更新加密价差策略失败", "error.server.crypto_tail_strategy_update_failed"),
|
||||
SERVER_CRYPTO_TAIL_STRATEGY_DELETE_FAILED(5622, "删除加密价差策略失败", "error.server.crypto_tail_strategy_delete_failed"),
|
||||
SERVER_CRYPTO_TAIL_STRATEGY_LIST_FETCH_FAILED(5623, "查询加密价差策略列表失败", "error.server.crypto_tail_strategy_list_fetch_failed"),
|
||||
SERVER_CRYPTO_TAIL_STRATEGY_TRIGGERS_FETCH_FAILED(5624, "查询触发记录失败", "error.server.crypto_tail_strategy_triggers_fetch_failed");
|
||||
|
||||
companion object {
|
||||
/**
|
||||
@@ -250,4 +301,3 @@ enum class ErrorCode(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.wrbug.polymarketbot.enums
|
||||
|
||||
enum class LeaderPoolStatus {
|
||||
CANDIDATE,
|
||||
WATCH,
|
||||
PAPER,
|
||||
TRIAL,
|
||||
ACTIVE,
|
||||
COOLDOWN,
|
||||
RETIRED
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package com.wrbug.polymarketbot.enums
|
||||
|
||||
enum class LeaderResearchState {
|
||||
DISCOVERED,
|
||||
CANDIDATE,
|
||||
PAPER,
|
||||
TRIAL_READY,
|
||||
COOLDOWN,
|
||||
RETIRED
|
||||
}
|
||||
|
||||
enum class LeaderResearchRunStatus {
|
||||
RUNNING,
|
||||
SUCCESS,
|
||||
PARTIAL_FAILURE,
|
||||
FAILED,
|
||||
SKIPPED
|
||||
}
|
||||
|
||||
enum class LeaderResearchTriggerType {
|
||||
MANUAL,
|
||||
SCHEDULED,
|
||||
PREVIEW
|
||||
}
|
||||
|
||||
enum class LeaderResearchSourceType {
|
||||
WATCHLIST,
|
||||
EXISTING_LEADER,
|
||||
ACTIVITY_DERIVED,
|
||||
GLOBAL_ACTIVITY_CAPTURE,
|
||||
PUBLIC_LEADERBOARD
|
||||
}
|
||||
|
||||
enum class LeaderResearchSourceStatus {
|
||||
SUCCESS,
|
||||
FAILURE,
|
||||
STALE,
|
||||
DISABLED,
|
||||
DEGRADED
|
||||
}
|
||||
|
||||
enum class LeaderCandidateProvenance {
|
||||
AGENT_CREATED,
|
||||
USER_LEADER,
|
||||
USER_POOL,
|
||||
MANUAL_LOCKED
|
||||
}
|
||||
|
||||
enum class LeaderPaperSessionStatus {
|
||||
ACTIVE,
|
||||
PAUSED,
|
||||
COMPLETED,
|
||||
FAILED
|
||||
}
|
||||
|
||||
enum class LeaderPaperProcessingStatus {
|
||||
NEW,
|
||||
PROCESSING,
|
||||
PROCESSED,
|
||||
FILTERED,
|
||||
RETRYABLE,
|
||||
FAILED
|
||||
}
|
||||
|
||||
enum class LeaderResearchValuationStatus {
|
||||
AVAILABLE,
|
||||
NO_MATCH,
|
||||
UNAVAILABLE,
|
||||
CONFIRMED_ZERO,
|
||||
UNKNOWN
|
||||
}
|
||||
|
||||
enum class LeaderResearchQuoteConfidence {
|
||||
HIGH,
|
||||
MEDIUM,
|
||||
LOW,
|
||||
UNKNOWN
|
||||
}
|
||||
|
||||
enum class LeaderPaperFillAssumption {
|
||||
LEADER_PRICE,
|
||||
BEST_ASK_AT_EVENT,
|
||||
MID_PRICE,
|
||||
UNKNOWN
|
||||
}
|
||||
|
||||
enum class LeaderPaperFilterResult {
|
||||
PASSED,
|
||||
FILTERED
|
||||
}
|
||||
|
||||
enum class LeaderResearchEventType {
|
||||
RUN_STARTED,
|
||||
RUN_COMPLETED,
|
||||
RUN_FAILED,
|
||||
RUN_SKIPPED,
|
||||
SOURCE_SUCCESS,
|
||||
SOURCE_FAILURE,
|
||||
SOURCE_DISABLED,
|
||||
CANDIDATE_DISCOVERED,
|
||||
CANDIDATE_UPDATED,
|
||||
PAPER_STARTED,
|
||||
PAPER_TRADE_RECORDED,
|
||||
PAPER_TRADE_FILTERED,
|
||||
PAPER_PROCESSING_FAILED,
|
||||
STATE_TRANSITION,
|
||||
TRIAL_READY,
|
||||
COOLDOWN,
|
||||
RETIRED,
|
||||
VALUATION_STALE,
|
||||
APPROVAL_CREATED_DISABLED_CONFIG,
|
||||
APPROVAL_REJECTED,
|
||||
DUPLICATE_APPROVAL,
|
||||
REAL_MONEY_ACTIVATION_FORBIDDEN,
|
||||
NOTIFICATION_SUMMARY
|
||||
}
|
||||
|
||||
enum class LeaderResearchNotificationStatus {
|
||||
PENDING,
|
||||
SENT,
|
||||
FAILED,
|
||||
SKIPPED
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.wrbug.polymarketbot.enums
|
||||
|
||||
/**
|
||||
* 价差方向枚举
|
||||
*/
|
||||
enum class SpreadDirection(val value: Int, val description: String) {
|
||||
/**
|
||||
* 最小价差:价差 >= 配置值时触发,买入价固定 0.99
|
||||
*/
|
||||
MIN(0, "最小价差"),
|
||||
|
||||
/**
|
||||
* 最大价差:价差 <= 配置值时触发,买入价 = 触发价 + 0.02
|
||||
*/
|
||||
MAX(1, "最大价差");
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* 从数值解析价差方向
|
||||
*/
|
||||
fun fromValue(value: Int?): SpreadDirection {
|
||||
if (value == null) {
|
||||
return MIN // 默认返回 MIN
|
||||
}
|
||||
return values().find { it.value == value }
|
||||
?: throw IllegalArgumentException("未知的价差方向: $value")
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全地从数值解析价差方向,解析失败返回默认值
|
||||
*/
|
||||
fun fromValueOrDefault(value: Int?, default: SpreadDirection = MIN): SpreadDirection {
|
||||
if (value == null) {
|
||||
return default
|
||||
}
|
||||
return values().find { it.value == value } ?: default
|
||||
}
|
||||
|
||||
/**
|
||||
* 从字符串解析价差方向(兼容旧逻辑)
|
||||
*/
|
||||
fun fromString(value: String?): SpreadDirection {
|
||||
if (value.isNullOrBlank()) {
|
||||
return MIN
|
||||
}
|
||||
return values().find { it.name.equals(value, ignoreCase = true) }
|
||||
?: throw IllegalArgumentException("未知的价差方向: $value")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.wrbug.polymarketbot.enums
|
||||
|
||||
import jakarta.persistence.AttributeConverter
|
||||
import jakarta.persistence.Converter
|
||||
|
||||
/**
|
||||
* SpreadDirection 枚举的 JPA 转换器
|
||||
* 数据库存储为 TINYINT (0 = MIN, 1 = MAX)
|
||||
*/
|
||||
@Converter(autoApply = false)
|
||||
class SpreadDirectionConverter : AttributeConverter<SpreadDirection, Int> {
|
||||
|
||||
override fun convertToDatabaseColumn(attribute: SpreadDirection?): Int {
|
||||
return attribute?.value ?: SpreadDirection.MIN.value
|
||||
}
|
||||
|
||||
override fun convertToEntityAttribute(dbData: Int?): SpreadDirection {
|
||||
return SpreadDirection.fromValueOrDefault(dbData)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.wrbug.polymarketbot.enums
|
||||
|
||||
/**
|
||||
* 价差模式枚举
|
||||
*/
|
||||
enum class SpreadMode(val value: Int, val description: String) {
|
||||
/**
|
||||
* 不校验价差
|
||||
*/
|
||||
NONE(0, "无"),
|
||||
|
||||
/**
|
||||
* 固定值:用户输入一个数值
|
||||
*/
|
||||
FIXED(1, "固定"),
|
||||
|
||||
/**
|
||||
* 自动:系统按历史 K 线计算建议价差
|
||||
*/
|
||||
AUTO(2, "自动");
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* 从数值解析价差模式
|
||||
*/
|
||||
fun fromValue(value: Int?): SpreadMode {
|
||||
if (value == null) {
|
||||
return NONE // 默认返回 NONE
|
||||
}
|
||||
return values().find { it.value == value }
|
||||
?: throw IllegalArgumentException("未知的价差模式: $value")
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全地从数值解析价差模式,解析失败返回默认值
|
||||
*/
|
||||
fun fromValueOrDefault(value: Int?, default: SpreadMode = NONE): SpreadMode {
|
||||
if (value == null) {
|
||||
return default
|
||||
}
|
||||
return values().find { it.value == value } ?: default
|
||||
}
|
||||
|
||||
/**
|
||||
* 从字符串解析价差模式(兼容旧逻辑)
|
||||
*/
|
||||
fun fromString(value: String?): SpreadMode {
|
||||
if (value.isNullOrBlank()) {
|
||||
return NONE
|
||||
}
|
||||
return values().find { it.name.equals(value, ignoreCase = true) }
|
||||
?: throw IllegalArgumentException("未知的价差模式: $value")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.wrbug.polymarketbot.enums
|
||||
|
||||
import jakarta.persistence.AttributeConverter
|
||||
import jakarta.persistence.Converter
|
||||
|
||||
/**
|
||||
* SpreadMode 枚举的 JPA 转换器
|
||||
* 数据库存储为 TINYINT (0 = NONE, 1 = FIXED, 2 = AUTO)
|
||||
*/
|
||||
@Converter(autoApply = false)
|
||||
class SpreadModeConverter : AttributeConverter<SpreadMode, Int> {
|
||||
|
||||
override fun convertToDatabaseColumn(attribute: SpreadMode?): Int {
|
||||
return attribute?.value ?: SpreadMode.NONE.value
|
||||
}
|
||||
|
||||
override fun convertToEntityAttribute(dbData: Int?): SpreadMode {
|
||||
return SpreadMode.fromValueOrDefault(dbData)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.wrbug.polymarketbot.enums
|
||||
|
||||
/**
|
||||
* 钱包类型枚举
|
||||
*/
|
||||
enum class WalletType(val value: String, val description: String) {
|
||||
/**
|
||||
* Magic 钱包(邮箱/OAuth 登录)
|
||||
* 使用 PROXY 代理合约,通过 Builder Relayer 执行 Gasless 交易
|
||||
*/
|
||||
MAGIC("magic", "Magic(邮箱/OAuth登录)"),
|
||||
|
||||
/**
|
||||
* Safe 钱包(MetaMask 等 Web3 钱包)
|
||||
* 使用 Gnosis Safe 代理合约,支持 Builder Relayer Gasless 或手动交易
|
||||
*/
|
||||
SAFE("safe", "Safe(Web3钱包)");
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* 从字符串值解析钱包类型(不区分大小写)
|
||||
*/
|
||||
fun fromString(value: String?): WalletType {
|
||||
if (value.isNullOrBlank()) {
|
||||
return SAFE // 默认返回 SAFE
|
||||
}
|
||||
return values().find { it.value.equals(value, ignoreCase = true) }
|
||||
?: throw IllegalArgumentException("未知的钱包类型: $value")
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全地从字符串值解析钱包类型(不区分大小写),解析失败返回默认值
|
||||
*/
|
||||
fun fromStringOrDefault(value: String?, default: WalletType = SAFE): WalletType {
|
||||
if (value.isNullOrBlank()) {
|
||||
return default
|
||||
}
|
||||
return values().find { it.value.equals(value, ignoreCase = true) } ?: default
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查字符串是否为有效的钱包类型
|
||||
*/
|
||||
fun isValid(value: String?): Boolean {
|
||||
if (value.isNullOrBlank()) {
|
||||
return false
|
||||
}
|
||||
return values().any { it.value.equals(value, ignoreCase = true) }
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.wrbug.polymarketbot.event
|
||||
|
||||
import org.springframework.context.ApplicationEvent
|
||||
|
||||
/**
|
||||
* 加密价差策略创建/更新/启用状态变更后发布,用于立即触发一轮执行检查。
|
||||
*/
|
||||
class CryptoTailStrategyChangedEvent(source: Any) : ApplicationEvent(source)
|
||||
@@ -1,7 +1,11 @@
|
||||
package com.wrbug.polymarketbot.repository
|
||||
|
||||
import com.wrbug.polymarketbot.entity.Account
|
||||
import jakarta.persistence.LockModeType
|
||||
import org.springframework.data.jpa.repository.JpaRepository
|
||||
import org.springframework.data.jpa.repository.Lock
|
||||
import org.springframework.data.jpa.repository.Query
|
||||
import org.springframework.data.repository.query.Param
|
||||
import org.springframework.stereotype.Repository
|
||||
|
||||
/**
|
||||
@@ -19,6 +23,10 @@ interface AccountRepository : JpaRepository<Account, Long> {
|
||||
* 查找默认账户
|
||||
*/
|
||||
fun findByIsDefaultTrue(): Account?
|
||||
|
||||
@Lock(LockModeType.PESSIMISTIC_WRITE)
|
||||
@Query("select a from Account a where a.id = :id")
|
||||
fun findByIdForUpdate(@Param("id") id: Long): Account?
|
||||
|
||||
/**
|
||||
* 查找所有账户,按创建时间排序
|
||||
@@ -29,5 +37,9 @@ interface AccountRepository : JpaRepository<Account, Long> {
|
||||
* 检查钱包地址是否存在
|
||||
*/
|
||||
fun existsByWalletAddress(walletAddress: String): Boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查代理地址是否存在
|
||||
*/
|
||||
fun existsByProxyAddress(proxyAddress: String): Boolean
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.wrbug.polymarketbot.repository
|
||||
|
||||
import com.wrbug.polymarketbot.entity.BacktestTask
|
||||
import org.springframework.data.jpa.repository.JpaRepository
|
||||
import org.springframework.data.jpa.repository.Modifying
|
||||
import org.springframework.data.jpa.repository.Query
|
||||
import org.springframework.stereotype.Repository
|
||||
|
||||
/**
|
||||
* 回测任务Repository
|
||||
*/
|
||||
@Repository
|
||||
interface BacktestTaskRepository : JpaRepository<BacktestTask, Long> {
|
||||
|
||||
/**
|
||||
* 根据 Leader ID 查询回测任务
|
||||
*/
|
||||
fun findByLeaderId(leaderId: Long): List<BacktestTask>
|
||||
|
||||
/**
|
||||
* 根据状态查询回测任务
|
||||
*/
|
||||
fun findByStatus(status: String): List<BacktestTask>
|
||||
|
||||
/**
|
||||
* 根据 Leader ID 和状态查询回测任务
|
||||
*/
|
||||
fun findByLeaderIdAndStatus(leaderId: Long, status: String): List<BacktestTask>
|
||||
|
||||
/**
|
||||
* 根据 Leader ID、收益率排序查询
|
||||
*/
|
||||
@Query("SELECT t FROM BacktestTask t WHERE t.leaderId = :leaderId AND t.status = :status ORDER BY t.profitRate DESC")
|
||||
fun findByLeaderIdAndStatusOrderByProfitRateDesc(leaderId: Long, status: String): List<BacktestTask>
|
||||
|
||||
/**
|
||||
* 根据状态和创建时间倒序查询
|
||||
*/
|
||||
@Query("SELECT t FROM BacktestTask t WHERE t.status = :status ORDER BY t.createdAt DESC")
|
||||
fun findByStatusOrderByCreatedAtDesc(status: String): List<BacktestTask>
|
||||
|
||||
/**
|
||||
* 更新回测任务状态
|
||||
*/
|
||||
@Modifying
|
||||
@Query("UPDATE BacktestTask t SET t.status = :status, t.updatedAt = :updatedAt WHERE t.id = :id")
|
||||
fun updateStatus(id: Long, status: String, updatedAt: Long = System.currentTimeMillis())
|
||||
|
||||
/**
|
||||
* 更新回测任务状态和错误信息
|
||||
*/
|
||||
@Modifying
|
||||
@Query("UPDATE BacktestTask t SET t.status = :status, t.errorMessage = :errorMessage, t.updatedAt = :updatedAt WHERE t.id = :id")
|
||||
fun updateStatusAndError(id: Long, status: String, errorMessage: String?, updatedAt: Long = System.currentTimeMillis())
|
||||
|
||||
/**
|
||||
* 更新回测任务进度
|
||||
*/
|
||||
@Modifying
|
||||
@Query("UPDATE BacktestTask t SET t.progress = :progress, t.updatedAt = :updatedAt WHERE t.id = :id")
|
||||
fun updateProgress(id: Long, progress: Int, updatedAt: Long = System.currentTimeMillis())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.wrbug.polymarketbot.repository
|
||||
|
||||
import com.wrbug.polymarketbot.entity.BacktestTrade
|
||||
import org.springframework.data.jpa.repository.JpaRepository
|
||||
import org.springframework.data.jpa.repository.Query
|
||||
import org.springframework.stereotype.Repository
|
||||
|
||||
/**
|
||||
* 回测交易记录Repository
|
||||
*/
|
||||
@Repository
|
||||
interface BacktestTradeRepository : JpaRepository<BacktestTrade, Long> {
|
||||
|
||||
/**
|
||||
* 根据回测任务ID查询所有交易记录
|
||||
*/
|
||||
fun findByBacktestTaskIdOrderByTradeTime(backtestTaskId: Long): List<BacktestTrade>
|
||||
|
||||
/**
|
||||
* 根据回测任务ID分页查询交易记录
|
||||
*/
|
||||
@Query("SELECT t FROM BacktestTrade t WHERE t.backtestTaskId = :backtestTaskId ORDER BY t.tradeTime")
|
||||
fun findByBacktestTaskId(
|
||||
backtestTaskId: Long,
|
||||
pageable: org.springframework.data.domain.Pageable
|
||||
): org.springframework.data.domain.Page<BacktestTrade>
|
||||
|
||||
/**
|
||||
* 根据回测任务ID统计交易数量
|
||||
*/
|
||||
fun countByBacktestTaskId(backtestTaskId: Long): Long
|
||||
|
||||
/**
|
||||
* 删除回测任务的所有交易记录(由级联删除处理)
|
||||
*/
|
||||
fun deleteByBacktestTaskId(backtestTaskId: Long)
|
||||
}
|
||||
|
||||
+19
-5
@@ -75,14 +75,28 @@ interface CopyOrderTrackingRepository : JpaRepository<CopyOrderTracking, Long> {
|
||||
fun countActivePositions(copyTradingId: Long): Int
|
||||
|
||||
/**
|
||||
* 检查指定市场是否存在活跃仓位
|
||||
* 计算指定跟单配置、市场和方向下的当前持仓总价值 (成本价计算)
|
||||
* 按市场+方向(outcomeIndex)分别统计
|
||||
*/
|
||||
fun existsByCopyTradingIdAndMarketIdAndRemainingQuantityGreaterThan(copyTradingId: Long, marketId: String, remainingQuantity: BigDecimal): Boolean
|
||||
@Query("SELECT SUM(t.remainingQuantity * t.price) FROM CopyOrderTracking t WHERE t.copyTradingId = :copyTradingId AND t.marketId = :marketId AND t.outcomeIndex = :outcomeIndex AND t.remainingQuantity > 0")
|
||||
fun sumCurrentPositionValueByMarketAndOutcomeIndex(copyTradingId: Long, marketId: String, outcomeIndex: Int): BigDecimal?
|
||||
|
||||
/**
|
||||
* 计算指定跟单配置和市场下的当前持仓总价值 (成本价计算)
|
||||
* 查询指定跟单配置下,创建时间超过指定时间点的未匹配订单(FIFO顺序)
|
||||
* 用于避免刚创建的订单被误判为已卖出
|
||||
*
|
||||
* @param copyTradingId 跟单配置ID
|
||||
* @param marketId 市场ID
|
||||
* @param outcomeIndex 结果索引
|
||||
* @param thresholdTime 时间阈值(毫秒时间戳),只查询创建时间小于该值的订单
|
||||
* @return 未匹配订单列表(按创建时间升序排列)
|
||||
*/
|
||||
@Query("SELECT SUM(t.remainingQuantity * t.price) FROM CopyOrderTracking t WHERE t.copyTradingId = :copyTradingId AND t.marketId = :marketId AND t.remainingQuantity > 0")
|
||||
fun sumCurrentPositionValueByMarket(copyTradingId: Long, marketId: String): BigDecimal?
|
||||
@Query("SELECT t FROM CopyOrderTracking t WHERE t.copyTradingId = :copyTradingId AND t.marketId = :marketId AND t.outcomeIndex = :outcomeIndex AND t.remainingQuantity > 0 AND t.createdAt < :thresholdTime ORDER BY t.createdAt ASC")
|
||||
fun findUnmatchedBuyOrdersByOutcomeIndexOlderThan(
|
||||
copyTradingId: Long,
|
||||
marketId: String,
|
||||
outcomeIndex: Int,
|
||||
thresholdTime: Long
|
||||
): List<CopyOrderTracking>
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user