Skip to content

Conversation

@the-dev-z
Copy link
Collaborator

🎯 Motivation

Based on extensive production usage and user feedback, we've developed a more comprehensive prompt system with:

  • Stronger risk management rules
  • Better handling of partial_close and update_stop_loss
  • Multiple strategy templates for different risk profiles
  • Enhanced decision quality and consistency

📊 What's Changed

1. Prompt System v6.0.0

All prompts now follow a standardized format with:

  • Version header: Clear versioning (v6.0.0)
  • Strategy positioning: Conservative/Moderate/Relaxed/Altcoin
  • Core parameters: Confidence thresholds, cooldown periods, BTC confirmation requirements
  • Unified structure: Consistent across all templates

2. New Strategy Templates

Added two new templates to cover different trading scenarios:

  • adaptive_altcoin.txt - Optimized for altcoin trading

    • Higher leverage limits (10x-15x)
    • More aggressive position sizing
    • Faster decision cycles
  • adaptive_moderate.txt - Balanced strategy

    • Medium risk tolerance
    • Flexible BTC confirmation
    • Suitable for most traders

3. Enhanced Safety Rules

partial_close Safety (Addresses #301)

⚠️ Mandatory Check:
- Before partial_close, calculate: remaining_value = current_value × (1 - close_percentage/100)
- If remaining_value ≤ $10 → Must use close_long/close_short instead
- Prevents "Order must have minimum value of $10" exchange errors

update_stop_loss Threshold Rules

⚠️ Strict Rules:
- Profit <3% → FORBIDDEN to move stop-loss (avoid premature trailing)
- Profit 3-5% → Can move to breakeven
- Profit ≥10% → Can move to entry +5% (lock partial profit)

TP/SL Restoration After partial_close

⚠️ Important: 
- Exchanges auto-cancel TP/SL orders when position size changes
- Must provide new_stop_loss + new_take_profit with partial_close
- Otherwise remaining position has NO protection (liquidation risk)

4. Files Changed

  • prompts/adaptive.txt - Conservative strategy (v6.0.0)
  • prompts/adaptive_relaxed.txt - Relaxed strategy (v6.0.0)
  • prompts/adaptive_altcoin.txt - NEW: Altcoin-optimized strategy
  • prompts/adaptive_moderate.txt - NEW: Balanced strategy

Statistics: +1104 lines, -100 lines

🔗 Related Issues

✅ Testing

  • All 4 templates follow v6.0.0 format
  • partial_close safety rules included
  • update_stop_loss threshold rules included
  • TP/SL restoration warnings included
  • Strategy-specific parameters validated

📝 Notes

This PR focuses on prompt layer enhancements only.

Backend safety checks (trader/auto_trader.go) will be submitted in a separate PR for easier review.

The two PRs can be merged independently or together - they complement each other:

  • This PR: AI makes better decisions (prevent bad actions)
  • Next PR: Backend validates and auto-corrects (safety net)

🎬 Next Steps

After this PR is reviewed, I will submit:

  • PR: Backend safety checks (MIN_POSITION_VALUE, TP/SL restoration)
  • PR: Enhanced position info display (decision/engine.go)

🤖 Generated with Claude Code

Co-Authored-By: Claude [email protected]

## 🎯 Motivation

Based on extensive production usage and user feedback, we've developed a more comprehensive prompt system with:
- Stronger risk management rules
- Better handling of partial_close and update_stop_loss
- Multiple strategy templates for different risk profiles
- Enhanced decision quality and consistency

## 📊 What's Changed

### 1. Prompt System v6.0.0

All prompts now follow a standardized format with:
- **Version header**: Clear versioning (v6.0.0)
- **Strategy positioning**: Conservative/Moderate/Relaxed/Altcoin
- **Core parameters**: Confidence thresholds, cooldown periods, BTC confirmation requirements
- **Unified structure**: Consistent across all templates

### 2. New Strategy Templates

Added two new templates to cover different trading scenarios:

- `adaptive_altcoin.txt` - Optimized for altcoin trading
  - Higher leverage limits (10x-15x)
  - More aggressive position sizing
  - Faster decision cycles

- `adaptive_moderate.txt` - Balanced strategy
  - Medium risk tolerance
  - Flexible BTC confirmation
  - Suitable for most traders

### 3. Enhanced Safety Rules

#### partial_close Safety (Addresses NoFxAiOS#301)
```
⚠️ Mandatory Check:
- Before partial_close, calculate: remaining_value = current_value × (1 - close_percentage/100)
- If remaining_value ≤ $10 → Must use close_long/close_short instead
- Prevents "Order must have minimum value of $10" exchange errors
```

#### update_stop_loss Threshold Rules
```
⚠️ Strict Rules:
- Profit <3% → FORBIDDEN to move stop-loss (avoid premature trailing)
- Profit 3-5% → Can move to breakeven
- Profit ≥10% → Can move to entry +5% (lock partial profit)
```

#### TP/SL Restoration After partial_close
```
⚠️ Important:
- Exchanges auto-cancel TP/SL orders when position size changes
- Must provide new_stop_loss + new_take_profit with partial_close
- Otherwise remaining position has NO protection (liquidation risk)
```

### 4. Files Changed

- `prompts/adaptive.txt` - Conservative strategy (v6.0.0)
- `prompts/adaptive_relaxed.txt` - Relaxed strategy (v6.0.0)
- `prompts/adaptive_altcoin.txt` - NEW: Altcoin-optimized strategy
- `prompts/adaptive_moderate.txt` - NEW: Balanced strategy

## 🔗 Related Issues

- Closes NoFxAiOS#301 (Prompt layer safety rules)
- Related to NoFxAiOS#418 (Same validation issue)
- Complements PR NoFxAiOS#415 (Backend implementation)

## ✅ Testing

- [x] All 4 templates follow v6.0.0 format
- [x] partial_close safety rules included
- [x] update_stop_loss threshold rules included
- [x] TP/SL restoration warnings included
- [x] Strategy-specific parameters validated

## 📝 Notes

This PR focuses on **prompt layer enhancements only**.

Backend safety checks (trader/auto_trader.go) will be submitted in a separate PR for easier review.

The two PRs can be merged independently or together - they complement each other:
- This PR: AI makes better decisions (prevent bad actions)
- Next PR: Backend validates and auto-corrects (safety net)

---

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@github-actions
Copy link

github-actions bot commented Nov 7, 2025

🤖 Advisory Check Results

These are advisory checks to help improve code quality. They won't block your PR from being merged.

📋 PR Information

Title Format: ✅ Good - Follows Conventional Commits
PR Size: 🔴 Large (1204 lines: +1104 -100)

💡 Suggestion: This is a large PR. Consider breaking it into smaller, focused PRs for easier review.

🔧 Backend Checks

Go Formatting: ✅ Good
Go Vet: ✅ Good
Tests: ✅ Passed

Fix locally:

go fmt ./...      # Format code
go vet ./...      # Check for issues
go test ./...     # Run tests

⚛️ Frontend Checks

Build & Type Check: ✅ Success

Fix locally:

cd web
npm run build  # Test build (includes type checking)

📖 Resources

Questions? Feel free to ask in the comments! 🙏


These checks are advisory and won't block your PR from being merged. This comment is automatically generated from pr-checks-run.yml.

the-dev-z added a commit to the-dev-z/nofx that referenced this pull request Nov 7, 2025
## 🎯 Problem

After PR NoFxAiOS#415 added partial_close functionality, production users reported two critical issues:

1. **Exchange minimum value error**: "Order must have minimum value of $10" when remaining position value falls below exchange threshold
2. **Unprotected positions after partial close**: Exchanges auto-cancel TP/SL orders when position size changes, leaving remaining position exposed to liquidation risk

## 🔧 Solution

This PR adds **backend safety checks** as a safety net layer that complements the prompt-based rules from PR NoFxAiOS#712.

### 1. Minimum Position Value Check (trader/auto_trader.go:1164-1189)

**Protection**: Before executing partial_close, verify remaining position value > $10

```go
const MIN_POSITION_VALUE = 10.0 // Exchange底线
remainingValue := remainingQuantity * markPrice

if remainingValue > 0 && remainingValue <= MIN_POSITION_VALUE {
    // 🔄 Auto-correct to full close
    decision.Action = "close_long" // or "close_short"
    return at.executeCloseLongWithRecord(decision, actionRecord)
}
```

**Behavior**:
- Position $20 → partial_close 50% → remaining $10 ≤ $10 → Auto full close ✅
- Position $30 → partial_close 50% → remaining $15 > $10 → Allow partial close ✅

### 2. TP/SL Restoration After partial_close (trader/auto_trader.go:1211-1235)

**Protection**: Restore TP/SL orders for remaining position if AI provides new_stop_loss/new_take_profit

```go
// Exchanges auto-cancel TP/SL when position size changes
if decision.NewStopLoss > 0 {
    at.trader.SetStopLoss(symbol, side, remainingQuantity, decision.NewStopLoss)
}
if decision.NewTakeProfit > 0 {
    at.trader.SetTakeProfit(symbol, side, remainingQuantity, decision.NewTakeProfit)
}

// Warning if AI didn't provide new TP/SL
if decision.NewStopLoss <= 0 && decision.NewTakeProfit <= 0 {
    log.Printf("⚠️⚠️⚠️ Warning: Remaining position has NO TP/SL protection")
}
```

### 3. Enhanced Position Info Display (decision/engine.go:378-384)

**Improvement**: Show position quantity and value to help AI make better decisions

```
Before: | 入场价100.00 当前价105.00 | 盈亏+5.00% | ...
After:  | 入场价100.00 当前价105.00 | 数量0.5000 | 仓位价值52.50 USDT | 盈亏+5.00% | ...
```

**Benefits**:
- AI can now calculate: remaining_value = current_value × (1 - close_percentage/100)
- AI can proactively avoid decisions that would violate $10 threshold

## 📊 Changes

### trader/auto_trader.go (+54 lines)
- Added MIN_POSITION_VALUE check before execution
- Auto-correct to full close if remaining value ≤ $10
- Restore TP/SL for remaining position
- Warning logs when AI doesn't provide new TP/SL

### decision/engine.go (+8 lines)
- Import "math" package
- Calculate and display position value
- Add quantity and position value to prompt

## 🔗 Related

- Complements PR NoFxAiOS#712 (Prompt v6.0.0 safety rules)
- Addresses NoFxAiOS#301 (Backend layer)
- Based on PR NoFxAiOS#415 (Core functionality)

## ⚡ Two-Layer Protection

| Layer | Location | Purpose |
|-------|----------|---------|
| **Layer 1: AI Prompt** | PR NoFxAiOS#712 | Prevent bad decisions before they happen |
| **Layer 2: Backend** | This PR | Auto-correct and safety net |

**Together they provide**:
- ✅ AI makes better decisions (sees position value, knows rules)
- ✅ Backend catches edge cases (auto-corrects violations)
- ✅ User-friendly warnings (explains what happened)

## ✅ Testing

- [x] Compiles successfully (`go build ./...`)
- [x] MIN_POSITION_VALUE logic correct
- [x] TP/SL restoration logic correct
- [x] Position value display format validated
- [x] Auto-correction flow tested

## 📝 Notes

This PR can be merged **independently** of PR NoFxAiOS#712, or together.

Suggested merge order:
1. PR NoFxAiOS#712 (Prompt v6.0.0) - AI layer improvements
2. This PR (Backend safety) - Safety net layer

Or merge together for complete two-layer protection.

---

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@SkywalkerJi SkywalkerJi merged commit 241c905 into NoFxAiOS:dev Nov 7, 2025
11 checks passed
simonjiang99 pushed a commit to simonjiang99/nofx that referenced this pull request Nov 7, 2025
…AiOS#712)

## 🎯 Motivation

Based on extensive production usage and user feedback, we've developed a more comprehensive prompt system with:
- Stronger risk management rules
- Better handling of partial_close and update_stop_loss
- Multiple strategy templates for different risk profiles
- Enhanced decision quality and consistency

## 📊 What's Changed

### 1. Prompt System v6.0.0

All prompts now follow a standardized format with:
- **Version header**: Clear versioning (v6.0.0)
- **Strategy positioning**: Conservative/Moderate/Relaxed/Altcoin
- **Core parameters**: Confidence thresholds, cooldown periods, BTC confirmation requirements
- **Unified structure**: Consistent across all templates

### 2. New Strategy Templates

Added two new templates to cover different trading scenarios:

- `adaptive_altcoin.txt` - Optimized for altcoin trading
  - Higher leverage limits (10x-15x)
  - More aggressive position sizing
  - Faster decision cycles

- `adaptive_moderate.txt` - Balanced strategy
  - Medium risk tolerance
  - Flexible BTC confirmation
  - Suitable for most traders

### 3. Enhanced Safety Rules

#### partial_close Safety (Addresses NoFxAiOS#301)
```
⚠️ Mandatory Check:
- Before partial_close, calculate: remaining_value = current_value × (1 - close_percentage/100)
- If remaining_value ≤ $10 → Must use close_long/close_short instead
- Prevents "Order must have minimum value of $10" exchange errors
```

#### update_stop_loss Threshold Rules
```
⚠️ Strict Rules:
- Profit <3% → FORBIDDEN to move stop-loss (avoid premature trailing)
- Profit 3-5% → Can move to breakeven
- Profit ≥10% → Can move to entry +5% (lock partial profit)
```

#### TP/SL Restoration After partial_close
```
⚠️ Important:
- Exchanges auto-cancel TP/SL orders when position size changes
- Must provide new_stop_loss + new_take_profit with partial_close
- Otherwise remaining position has NO protection (liquidation risk)
```

### 4. Files Changed

- `prompts/adaptive.txt` - Conservative strategy (v6.0.0)
- `prompts/adaptive_relaxed.txt` - Relaxed strategy (v6.0.0)
- `prompts/adaptive_altcoin.txt` - NEW: Altcoin-optimized strategy
- `prompts/adaptive_moderate.txt` - NEW: Balanced strategy

## 🔗 Related Issues

- Closes NoFxAiOS#301 (Prompt layer safety rules)
- Related to NoFxAiOS#418 (Same validation issue)
- Complements PR NoFxAiOS#415 (Backend implementation)

## ✅ Testing

- [x] All 4 templates follow v6.0.0 format
- [x] partial_close safety rules included
- [x] update_stop_loss threshold rules included
- [x] TP/SL restoration warnings included
- [x] Strategy-specific parameters validated

## 📝 Notes

This PR focuses on **prompt layer enhancements only**.

Backend safety checks (trader/auto_trader.go) will be submitted in a separate PR for easier review.

The two PRs can be merged independently or together - they complement each other:
- This PR: AI makes better decisions (prevent bad actions)
- Next PR: Backend validates and auto-corrects (safety net)

---

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <[email protected]>
ForeverInLaw pushed a commit to ForeverInLaw/nofx that referenced this pull request Nov 8, 2025
…AiOS#712)

## 🎯 Motivation

Based on extensive production usage and user feedback, we've developed a more comprehensive prompt system with:
- Stronger risk management rules
- Better handling of partial_close and update_stop_loss
- Multiple strategy templates for different risk profiles
- Enhanced decision quality and consistency

## 📊 What's Changed

### 1. Prompt System v6.0.0

All prompts now follow a standardized format with:
- **Version header**: Clear versioning (v6.0.0)
- **Strategy positioning**: Conservative/Moderate/Relaxed/Altcoin
- **Core parameters**: Confidence thresholds, cooldown periods, BTC confirmation requirements
- **Unified structure**: Consistent across all templates

### 2. New Strategy Templates

Added two new templates to cover different trading scenarios:

- `adaptive_altcoin.txt` - Optimized for altcoin trading
  - Higher leverage limits (10x-15x)
  - More aggressive position sizing
  - Faster decision cycles

- `adaptive_moderate.txt` - Balanced strategy
  - Medium risk tolerance
  - Flexible BTC confirmation
  - Suitable for most traders

### 3. Enhanced Safety Rules

#### partial_close Safety (Addresses NoFxAiOS#301)
```
⚠️ Mandatory Check:
- Before partial_close, calculate: remaining_value = current_value × (1 - close_percentage/100)
- If remaining_value ≤ $10 → Must use close_long/close_short instead
- Prevents "Order must have minimum value of $10" exchange errors
```

#### update_stop_loss Threshold Rules
```
⚠️ Strict Rules:
- Profit <3% → FORBIDDEN to move stop-loss (avoid premature trailing)
- Profit 3-5% → Can move to breakeven
- Profit ≥10% → Can move to entry +5% (lock partial profit)
```

#### TP/SL Restoration After partial_close
```
⚠️ Important:
- Exchanges auto-cancel TP/SL orders when position size changes
- Must provide new_stop_loss + new_take_profit with partial_close
- Otherwise remaining position has NO protection (liquidation risk)
```

### 4. Files Changed

- `prompts/adaptive.txt` - Conservative strategy (v6.0.0)
- `prompts/adaptive_relaxed.txt` - Relaxed strategy (v6.0.0)
- `prompts/adaptive_altcoin.txt` - NEW: Altcoin-optimized strategy
- `prompts/adaptive_moderate.txt` - NEW: Balanced strategy

## 🔗 Related Issues

- Closes NoFxAiOS#301 (Prompt layer safety rules)
- Related to NoFxAiOS#418 (Same validation issue)
- Complements PR NoFxAiOS#415 (Backend implementation)

## ✅ Testing

- [x] All 4 templates follow v6.0.0 format
- [x] partial_close safety rules included
- [x] update_stop_loss threshold rules included
- [x] TP/SL restoration warnings included
- [x] Strategy-specific parameters validated

## 📝 Notes

This PR focuses on **prompt layer enhancements only**.

Backend safety checks (trader/auto_trader.go) will be submitted in a separate PR for easier review.

The two PRs can be merged independently or together - they complement each other:
- This PR: AI makes better decisions (prevent bad actions)
- Next PR: Backend validates and auto-corrects (safety net)

---

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <[email protected]>
xqliu pushed a commit to nofxai/nofx that referenced this pull request Nov 9, 2025
…AiOS#712)

## 🎯 Motivation

Based on extensive production usage and user feedback, we've developed a more comprehensive prompt system with:
- Stronger risk management rules
- Better handling of partial_close and update_stop_loss
- Multiple strategy templates for different risk profiles
- Enhanced decision quality and consistency

## 📊 What's Changed

### 1. Prompt System v6.0.0

All prompts now follow a standardized format with:
- **Version header**: Clear versioning (v6.0.0)
- **Strategy positioning**: Conservative/Moderate/Relaxed/Altcoin
- **Core parameters**: Confidence thresholds, cooldown periods, BTC confirmation requirements
- **Unified structure**: Consistent across all templates

### 2. New Strategy Templates

Added two new templates to cover different trading scenarios:

- `adaptive_altcoin.txt` - Optimized for altcoin trading
  - Higher leverage limits (10x-15x)
  - More aggressive position sizing
  - Faster decision cycles

- `adaptive_moderate.txt` - Balanced strategy
  - Medium risk tolerance
  - Flexible BTC confirmation
  - Suitable for most traders

### 3. Enhanced Safety Rules

#### partial_close Safety (Addresses NoFxAiOS#301)
```
⚠️ Mandatory Check:
- Before partial_close, calculate: remaining_value = current_value × (1 - close_percentage/100)
- If remaining_value ≤ $10 → Must use close_long/close_short instead
- Prevents "Order must have minimum value of $10" exchange errors
```

#### update_stop_loss Threshold Rules
```
⚠️ Strict Rules:
- Profit <3% → FORBIDDEN to move stop-loss (avoid premature trailing)
- Profit 3-5% → Can move to breakeven
- Profit ≥10% → Can move to entry +5% (lock partial profit)
```

#### TP/SL Restoration After partial_close
```
⚠️ Important:
- Exchanges auto-cancel TP/SL orders when position size changes
- Must provide new_stop_loss + new_take_profit with partial_close
- Otherwise remaining position has NO protection (liquidation risk)
```

### 4. Files Changed

- `prompts/adaptive.txt` - Conservative strategy (v6.0.0)
- `prompts/adaptive_relaxed.txt` - Relaxed strategy (v6.0.0)
- `prompts/adaptive_altcoin.txt` - NEW: Altcoin-optimized strategy
- `prompts/adaptive_moderate.txt` - NEW: Balanced strategy

## 🔗 Related Issues

- Closes NoFxAiOS#301 (Prompt layer safety rules)
- Related to NoFxAiOS#418 (Same validation issue)
- Complements PR NoFxAiOS#415 (Backend implementation)

## ✅ Testing

- [x] All 4 templates follow v6.0.0 format
- [x] partial_close safety rules included
- [x] update_stop_loss threshold rules included
- [x] TP/SL restoration warnings included
- [x] Strategy-specific parameters validated

## 📝 Notes

This PR focuses on **prompt layer enhancements only**.

Backend safety checks (trader/auto_trader.go) will be submitted in a separate PR for easier review.

The two PRs can be merged independently or together - they complement each other:
- This PR: AI makes better decisions (prevent bad actions)
- Next PR: Backend validates and auto-corrects (safety net)

---

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <[email protected]>
the-dev-z added a commit to the-dev-z/nofx that referenced this pull request Nov 10, 2025
After PR NoFxAiOS#415 added partial_close functionality, production users reported two critical issues:

1. **Exchange minimum value error**: "Order must have minimum value of $10" when remaining position value falls below exchange threshold
2. **Unprotected positions after partial close**: Exchanges auto-cancel TP/SL orders when position size changes, leaving remaining position exposed to liquidation risk

This PR adds **backend safety checks** as a safety net layer that complements the prompt-based rules from PR NoFxAiOS#712.

**Protection**: Before executing partial_close, verify remaining position value > $10

```go
const MIN_POSITION_VALUE = 10.0 // Exchange底线
remainingValue := remainingQuantity * markPrice

if remainingValue > 0 && remainingValue <= MIN_POSITION_VALUE {
    // 🔄 Auto-correct to full close
    decision.Action = "close_long" // or "close_short"
    return at.executeCloseLongWithRecord(decision, actionRecord)
}
```

**Behavior**:
- Position $20 → partial_close 50% → remaining $10 ≤ $10 → Auto full close ✅
- Position $30 → partial_close 50% → remaining $15 > $10 → Allow partial close ✅

**Protection**: Restore TP/SL orders for remaining position if AI provides new_stop_loss/new_take_profit

```go
// Exchanges auto-cancel TP/SL when position size changes
if decision.NewStopLoss > 0 {
    at.trader.SetStopLoss(symbol, side, remainingQuantity, decision.NewStopLoss)
}
if decision.NewTakeProfit > 0 {
    at.trader.SetTakeProfit(symbol, side, remainingQuantity, decision.NewTakeProfit)
}

// Warning if AI didn't provide new TP/SL
if decision.NewStopLoss <= 0 && decision.NewTakeProfit <= 0 {
    log.Printf("⚠️⚠️⚠️ Warning: Remaining position has NO TP/SL protection")
}
```

**Improvement**: Show position quantity and value to help AI make better decisions

```
Before: | 入场价100.00 当前价105.00 | 盈亏+5.00% | ...
After:  | 入场价100.00 当前价105.00 | 数量0.5000 | 仓位价值52.50 USDT | 盈亏+5.00% | ...
```

**Benefits**:
- AI can now calculate: remaining_value = current_value × (1 - close_percentage/100)
- AI can proactively avoid decisions that would violate $10 threshold

- Added MIN_POSITION_VALUE check before execution
- Auto-correct to full close if remaining value ≤ $10
- Restore TP/SL for remaining position
- Warning logs when AI doesn't provide new TP/SL

- Import "math" package
- Calculate and display position value
- Add quantity and position value to prompt

- Complements PR NoFxAiOS#712 (Prompt v6.0.0 safety rules)
- Addresses NoFxAiOS#301 (Backend layer)
- Based on PR NoFxAiOS#415 (Core functionality)

| Layer | Location | Purpose |
|-------|----------|---------|
| **Layer 1: AI Prompt** | PR NoFxAiOS#712 | Prevent bad decisions before they happen |
| **Layer 2: Backend** | This PR | Auto-correct and safety net |

**Together they provide**:
- ✅ AI makes better decisions (sees position value, knows rules)
- ✅ Backend catches edge cases (auto-corrects violations)
- ✅ User-friendly warnings (explains what happened)

- [x] Compiles successfully (`go build ./...`)
- [x] MIN_POSITION_VALUE logic correct
- [x] TP/SL restoration logic correct
- [x] Position value display format validated
- [x] Auto-correction flow tested

This PR can be merged **independently** of PR NoFxAiOS#712, or together.

Suggested merge order:
1. PR NoFxAiOS#712 (Prompt v6.0.0) - AI layer improvements
2. This PR (Backend safety) - Safety net layer

Or merge together for complete two-layer protection.

---

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
the-dev-z added a commit to the-dev-z/nofx that referenced this pull request Nov 11, 2025
After PR NoFxAiOS#415 added partial_close functionality, production users reported two critical issues:

1. **Exchange minimum value error**: "Order must have minimum value of $10" when remaining position value falls below exchange threshold
2. **Unprotected positions after partial close**: Exchanges auto-cancel TP/SL orders when position size changes, leaving remaining position exposed to liquidation risk

This PR adds **backend safety checks** as a safety net layer that complements the prompt-based rules from PR NoFxAiOS#712.

**Protection**: Before executing partial_close, verify remaining position value > $10

```go
const MIN_POSITION_VALUE = 10.0 // Exchange底线
remainingValue := remainingQuantity * markPrice

if remainingValue > 0 && remainingValue <= MIN_POSITION_VALUE {
    // 🔄 Auto-correct to full close
    decision.Action = "close_long" // or "close_short"
    return at.executeCloseLongWithRecord(decision, actionRecord)
}
```

**Behavior**:
- Position $20 → partial_close 50% → remaining $10 ≤ $10 → Auto full close ✅
- Position $30 → partial_close 50% → remaining $15 > $10 → Allow partial close ✅

**Protection**: Restore TP/SL orders for remaining position if AI provides new_stop_loss/new_take_profit

```go
// Exchanges auto-cancel TP/SL when position size changes
if decision.NewStopLoss > 0 {
    at.trader.SetStopLoss(symbol, side, remainingQuantity, decision.NewStopLoss)
}
if decision.NewTakeProfit > 0 {
    at.trader.SetTakeProfit(symbol, side, remainingQuantity, decision.NewTakeProfit)
}

// Warning if AI didn't provide new TP/SL
if decision.NewStopLoss <= 0 && decision.NewTakeProfit <= 0 {
    log.Printf("⚠️⚠️⚠️ Warning: Remaining position has NO TP/SL protection")
}
```

**Improvement**: Show position quantity and value to help AI make better decisions

```
Before: | 入场价100.00 当前价105.00 | 盈亏+5.00% | ...
After:  | 入场价100.00 当前价105.00 | 数量0.5000 | 仓位价值52.50 USDT | 盈亏+5.00% | ...
```

**Benefits**:
- AI can now calculate: remaining_value = current_value × (1 - close_percentage/100)
- AI can proactively avoid decisions that would violate $10 threshold

- Added MIN_POSITION_VALUE check before execution
- Auto-correct to full close if remaining value ≤ $10
- Restore TP/SL for remaining position
- Warning logs when AI doesn't provide new TP/SL

- Import "math" package
- Calculate and display position value
- Add quantity and position value to prompt

- Complements PR NoFxAiOS#712 (Prompt v6.0.0 safety rules)
- Addresses NoFxAiOS#301 (Backend layer)
- Based on PR NoFxAiOS#415 (Core functionality)

| Layer | Location | Purpose |
|-------|----------|---------|
| **Layer 1: AI Prompt** | PR NoFxAiOS#712 | Prevent bad decisions before they happen |
| **Layer 2: Backend** | This PR | Auto-correct and safety net |

**Together they provide**:
- ✅ AI makes better decisions (sees position value, knows rules)
- ✅ Backend catches edge cases (auto-corrects violations)
- ✅ User-friendly warnings (explains what happened)

- [x] Compiles successfully (`go build ./...`)
- [x] MIN_POSITION_VALUE logic correct
- [x] TP/SL restoration logic correct
- [x] Position value display format validated
- [x] Auto-correction flow tested

This PR can be merged **independently** of PR NoFxAiOS#712, or together.

Suggested merge order:
1. PR NoFxAiOS#712 (Prompt v6.0.0) - AI layer improvements
2. This PR (Backend safety) - Safety net layer

Or merge together for complete two-layer protection.

---

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
hzb1115 pushed a commit that referenced this pull request Nov 12, 2025
* fix(trader): add backend safety checks for partial_close

After PR #415 added partial_close functionality, production users reported two critical issues:

1. **Exchange minimum value error**: "Order must have minimum value of $10" when remaining position value falls below exchange threshold
2. **Unprotected positions after partial close**: Exchanges auto-cancel TP/SL orders when position size changes, leaving remaining position exposed to liquidation risk

This PR adds **backend safety checks** as a safety net layer that complements the prompt-based rules from PR #712.

**Protection**: Before executing partial_close, verify remaining position value > $10

```go
const MIN_POSITION_VALUE = 10.0 // Exchange底线
remainingValue := remainingQuantity * markPrice

if remainingValue > 0 && remainingValue <= MIN_POSITION_VALUE {
    // 🔄 Auto-correct to full close
    decision.Action = "close_long" // or "close_short"
    return at.executeCloseLongWithRecord(decision, actionRecord)
}
```

**Behavior**:
- Position $20 → partial_close 50% → remaining $10 ≤ $10 → Auto full close ✅
- Position $30 → partial_close 50% → remaining $15 > $10 → Allow partial close ✅

**Protection**: Restore TP/SL orders for remaining position if AI provides new_stop_loss/new_take_profit

```go
// Exchanges auto-cancel TP/SL when position size changes
if decision.NewStopLoss > 0 {
    at.trader.SetStopLoss(symbol, side, remainingQuantity, decision.NewStopLoss)
}
if decision.NewTakeProfit > 0 {
    at.trader.SetTakeProfit(symbol, side, remainingQuantity, decision.NewTakeProfit)
}

// Warning if AI didn't provide new TP/SL
if decision.NewStopLoss <= 0 && decision.NewTakeProfit <= 0 {
    log.Printf("⚠️⚠️⚠️ Warning: Remaining position has NO TP/SL protection")
}
```

**Improvement**: Show position quantity and value to help AI make better decisions

```
Before: | 入场价100.00 当前价105.00 | 盈亏+5.00% | ...
After:  | 入场价100.00 当前价105.00 | 数量0.5000 | 仓位价值52.50 USDT | 盈亏+5.00% | ...
```

**Benefits**:
- AI can now calculate: remaining_value = current_value × (1 - close_percentage/100)
- AI can proactively avoid decisions that would violate $10 threshold

- Added MIN_POSITION_VALUE check before execution
- Auto-correct to full close if remaining value ≤ $10
- Restore TP/SL for remaining position
- Warning logs when AI doesn't provide new TP/SL

- Import "math" package
- Calculate and display position value
- Add quantity and position value to prompt

- Complements PR #712 (Prompt v6.0.0 safety rules)
- Addresses #301 (Backend layer)
- Based on PR #415 (Core functionality)

| Layer | Location | Purpose |
|-------|----------|---------|
| **Layer 1: AI Prompt** | PR #712 | Prevent bad decisions before they happen |
| **Layer 2: Backend** | This PR | Auto-correct and safety net |

**Together they provide**:
- ✅ AI makes better decisions (sees position value, knows rules)
- ✅ Backend catches edge cases (auto-corrects violations)
- ✅ User-friendly warnings (explains what happened)

- [x] Compiles successfully (`go build ./...`)
- [x] MIN_POSITION_VALUE logic correct
- [x] TP/SL restoration logic correct
- [x] Position value display format validated
- [x] Auto-correction flow tested

This PR can be merged **independently** of PR #712, or together.

Suggested merge order:
1. PR #712 (Prompt v6.0.0) - AI layer improvements
2. This PR (Backend safety) - Safety net layer

Or merge together for complete two-layer protection.

---

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* fix: add error handling for markPrice type assertion

- Check type assertion success before using markPrice
- Return error if markPrice is invalid or <= 0
- Addresses code review feedback from @xqliu in PR #713

* test(trader): add comprehensive unit tests for partial_close safety checks

- Test minimum position value check (< 10 USDT triggers full close)
- Test boundary condition (exactly 10 USDT also triggers full close)
- Test stop-loss/take-profit recovery after partial close
- Test edge cases (invalid close percentages)
- Test integration scenarios with mock trader

All 14 test cases passed, covering:
1. MinPositionCheck (5 cases): normal, small remainder, boundary, edge cases
2. StopLossTakeProfitRecovery (4 cases): both/SL only/TP only/none
3. EdgeCases (4 cases): zero/over 100/negative/normal percentages
4. Integration (2 cases): LONG with SL/TP, SHORT with auto full close

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* style: apply go fmt after rebase

Only formatting changes:
- api/server.go: fix indentation
- manager/trader_manager.go: add blank line
- trader/partial_close_test.go: align struct fields

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* fix(test): rename MockTrader to MockPartialCloseTrader to avoid conflict

Problem:
- trader/partial_close_test.go defined MockTrader
- trader/auto_trader_test.go already has MockTrader
- Methods CloseLong, CloseShort, SetStopLoss, SetTakeProfit were declared twice
- Compilation failed with 'already declared' errors

Solution:
- Rename MockTrader to MockPartialCloseTrader in partial_close_test.go
- This avoids naming conflict while keeping test logic independent

Test Results:
- All partial close tests pass
- All trader tests pass

Related: PR #713

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: ZhouYongyou <[email protected]>
Co-authored-by: Claude <[email protected]>
Co-authored-by: the-dev-z <[email protected]>
@the-dev-z the-dev-z deleted the refactor/prompts-v6-with-safety-rules branch November 12, 2025 08:37
XiaYiHann pushed a commit to XiaYiHann/nofx that referenced this pull request Nov 13, 2025
* fix(trader): add backend safety checks for partial_close

After PR NoFxAiOS#415 added partial_close functionality, production users reported two critical issues:

1. **Exchange minimum value error**: "Order must have minimum value of $10" when remaining position value falls below exchange threshold
2. **Unprotected positions after partial close**: Exchanges auto-cancel TP/SL orders when position size changes, leaving remaining position exposed to liquidation risk

This PR adds **backend safety checks** as a safety net layer that complements the prompt-based rules from PR NoFxAiOS#712.

**Protection**: Before executing partial_close, verify remaining position value > $10

```go
const MIN_POSITION_VALUE = 10.0 // Exchange底线
remainingValue := remainingQuantity * markPrice

if remainingValue > 0 && remainingValue <= MIN_POSITION_VALUE {
    // 🔄 Auto-correct to full close
    decision.Action = "close_long" // or "close_short"
    return at.executeCloseLongWithRecord(decision, actionRecord)
}
```

**Behavior**:
- Position $20 → partial_close 50% → remaining $10 ≤ $10 → Auto full close ✅
- Position $30 → partial_close 50% → remaining $15 > $10 → Allow partial close ✅

**Protection**: Restore TP/SL orders for remaining position if AI provides new_stop_loss/new_take_profit

```go
// Exchanges auto-cancel TP/SL when position size changes
if decision.NewStopLoss > 0 {
    at.trader.SetStopLoss(symbol, side, remainingQuantity, decision.NewStopLoss)
}
if decision.NewTakeProfit > 0 {
    at.trader.SetTakeProfit(symbol, side, remainingQuantity, decision.NewTakeProfit)
}

// Warning if AI didn't provide new TP/SL
if decision.NewStopLoss <= 0 && decision.NewTakeProfit <= 0 {
    log.Printf("⚠️⚠️⚠️ Warning: Remaining position has NO TP/SL protection")
}
```

**Improvement**: Show position quantity and value to help AI make better decisions

```
Before: | 入场价100.00 当前价105.00 | 盈亏+5.00% | ...
After:  | 入场价100.00 当前价105.00 | 数量0.5000 | 仓位价值52.50 USDT | 盈亏+5.00% | ...
```

**Benefits**:
- AI can now calculate: remaining_value = current_value × (1 - close_percentage/100)
- AI can proactively avoid decisions that would violate $10 threshold

- Added MIN_POSITION_VALUE check before execution
- Auto-correct to full close if remaining value ≤ $10
- Restore TP/SL for remaining position
- Warning logs when AI doesn't provide new TP/SL

- Import "math" package
- Calculate and display position value
- Add quantity and position value to prompt

- Complements PR NoFxAiOS#712 (Prompt v6.0.0 safety rules)
- Addresses NoFxAiOS#301 (Backend layer)
- Based on PR NoFxAiOS#415 (Core functionality)

| Layer | Location | Purpose |
|-------|----------|---------|
| **Layer 1: AI Prompt** | PR NoFxAiOS#712 | Prevent bad decisions before they happen |
| **Layer 2: Backend** | This PR | Auto-correct and safety net |

**Together they provide**:
- ✅ AI makes better decisions (sees position value, knows rules)
- ✅ Backend catches edge cases (auto-corrects violations)
- ✅ User-friendly warnings (explains what happened)

- [x] Compiles successfully (`go build ./...`)
- [x] MIN_POSITION_VALUE logic correct
- [x] TP/SL restoration logic correct
- [x] Position value display format validated
- [x] Auto-correction flow tested

This PR can be merged **independently** of PR NoFxAiOS#712, or together.

Suggested merge order:
1. PR NoFxAiOS#712 (Prompt v6.0.0) - AI layer improvements
2. This PR (Backend safety) - Safety net layer

Or merge together for complete two-layer protection.

---

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* fix: add error handling for markPrice type assertion

- Check type assertion success before using markPrice
- Return error if markPrice is invalid or <= 0
- Addresses code review feedback from @xqliu in PR NoFxAiOS#713

* test(trader): add comprehensive unit tests for partial_close safety checks

- Test minimum position value check (< 10 USDT triggers full close)
- Test boundary condition (exactly 10 USDT also triggers full close)
- Test stop-loss/take-profit recovery after partial close
- Test edge cases (invalid close percentages)
- Test integration scenarios with mock trader

All 14 test cases passed, covering:
1. MinPositionCheck (5 cases): normal, small remainder, boundary, edge cases
2. StopLossTakeProfitRecovery (4 cases): both/SL only/TP only/none
3. EdgeCases (4 cases): zero/over 100/negative/normal percentages
4. Integration (2 cases): LONG with SL/TP, SHORT with auto full close

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* style: apply go fmt after rebase

Only formatting changes:
- api/server.go: fix indentation
- manager/trader_manager.go: add blank line
- trader/partial_close_test.go: align struct fields

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* fix(test): rename MockTrader to MockPartialCloseTrader to avoid conflict

Problem:
- trader/partial_close_test.go defined MockTrader
- trader/auto_trader_test.go already has MockTrader
- Methods CloseLong, CloseShort, SetStopLoss, SetTakeProfit were declared twice
- Compilation failed with 'already declared' errors

Solution:
- Rename MockTrader to MockPartialCloseTrader in partial_close_test.go
- This avoids naming conflict while keeping test logic independent

Test Results:
- All partial close tests pass
- All trader tests pass

Related: PR NoFxAiOS#713

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: ZhouYongyou <[email protected]>
Co-authored-by: Claude <[email protected]>
Co-authored-by: the-dev-z <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] 解析AI响应失败: 决策验证失败: 决策 #2 验证失败: 无效的action: update_stop_loss

2 participants