Files
trading_bot_v4/docs/N8N_API_MANAGEMENT.md
mindesbunister ff92e7b78c feat(v9): Complete MA gap backend integration
Integrated MA gap analysis into signal quality evaluation pipeline:

BACKEND SCORING (lib/trading/signal-quality.ts):
- Added maGap?: number parameter to scoreSignalQuality interface
- Implemented convergence/divergence scoring logic:
  * LONG: +15pts tight bullish (0-2%), +12pts converging (-2-0%), +8pts early momentum (-5--2%)
  * SHORT: +15pts tight bearish (-2-0%), +12pts converging (0-2%), +8pts early momentum (2-5%)
  * Penalties: -5pts for misaligned MA structure (>5% wrong direction)

N8N PARSER (workflows/trading/parse_signal_enhanced.json):
- Added MAGAP:([-\d.]+) regex pattern for negative number support
- Extracts maGap from TradingView v9 alert messages
- Returns maGap in parsed output (backward compatible with v8)
- Updated comment to show v9 format

API ENDPOINTS:
- app/api/trading/check-risk/route.ts: Pass maGap to scoreSignalQuality (2 calls)
- app/api/trading/execute/route.ts: Pass maGap to scoreSignalQuality (2 calls)

FULL PIPELINE NOW COMPLETE:
1. TradingView v9 → Generates signal with MAGAP field
2. n8n webhook → Extracts maGap from alert message
3. Backend scoring → Evaluates MA gap convergence (+8 to +15 pts)
4. Quality threshold → Borderline signals (75-85) can reach 91+
5. Execute decision → Only signals scoring ≥91 are executed

MOTIVATION:
Helps borderline quality signals reach execution threshold without overriding
safety rules. Addresses Nov 25 missed opportunity where good signal had MA
convergence but borderline quality score.

TESTING REQUIRED:
- Verify n8n parses MAGAP correctly from v9 alerts
- Confirm backend receives maGap parameter
- Validate MA gap scoring applied to quality calculation
- Monitor first 10-20 v9 signals for scoring accuracy
2025-11-26 10:50:25 +01:00

365 lines
9.7 KiB
Markdown

# n8n API Management Guide
**Created:** Nov 26, 2025
**Purpose:** Document n8n API access for workflow automation and management
---
## API Credentials
**n8n Instance:** http://localhost:8098 (Docker container, port mapped 0.0.0.0:8098->5678)
**External Domain:** https://flow.egonetix.de (currently DNS unavailable)
**API Key:** `n8n_api_42f1838c1e2de90cadcb669f78083de92697a85322c0b6009ad2e55760db992ab0bf61515a3cf0e1`
**Environment Variable (.env):**
```bash
N8N_API_KEY=n8n_api_42f1838c1e2de90cadcb669f78083de92697a85322c0b6009ad2e55760db992ab0bf61515a3cf0e1
N8N_API_URL=http://localhost:8098/api/v1
```
---
## Common API Operations
### 1. List All Workflows
```bash
curl -X GET "http://localhost:8098/api/v1/workflows" \
-H "X-N8N-API-KEY: n8n_api_42f1838c1e2de90cadcb669f78083de92697a85322c0b6009ad2e55760db992ab0bf61515a3cf0e1" \
-H "Accept: application/json"
```
**Response Fields:**
- `id` - Workflow ID (use for updates/deletes)
- `name` - Workflow name
- `active` - true/false (is workflow enabled?)
- `nodes` - Array of workflow nodes
- `connections` - Node connections map
**Current Workflows (as of Nov 26, 2025):**
- `gUDqTiHyHSfRUXv6` - **Money Machine** (Active: true) - Main trading workflow
- `Zk4gbBzjxVppHiCB` - nextcloud deck tf bank (Active: true)
- `l5Bnf1Nh3C2GDcpv` - nextcloud deck gebührenfrei mastercard (Active: true)
### 2. Get Specific Workflow
```bash
# Get Money Machine workflow details
curl -X GET "http://localhost:8098/api/v1/workflows/gUDqTiHyHSfRUXv6" \
-H "X-N8N-API-KEY: n8n_api_42f1838c1e2de90cadcb669f78083de92697a85322c0b6009ad2e55760db992ab0bf61515a3cf0e1" \
-H "Accept: application/json"
```
**Money Machine Workflow Nodes:**
- **Parse Signal Enhanced** - Extracts metrics from TradingView alerts
- **Check Risk1** - Validates signal quality via `/api/trading/check-risk`
- **Execute Trade1** - Opens position via `/api/trading/execute`
- **Trade Success?** - Validation/branching logic
### 3. Update Workflow
```bash
curl -X PATCH "http://localhost:8098/api/v1/workflows/{workflow_id}" \
-H "X-N8N-API-KEY: n8n_api_42f1838c1e2de90cadcb669f78083de92697a85322c0b6009ad2e55760db992ab0bf61515a3cf0e1" \
-H "Content-Type: application/json" \
-d '{
"name": "Updated Workflow Name",
"active": true,
"nodes": [...],
"connections": {...}
}'
```
### 4. Activate/Deactivate Workflow
```bash
# Activate Money Machine workflow
curl -X PATCH "http://localhost:8098/api/v1/workflows/gUDqTiHyHSfRUXv6" \
-H "X-N8N-API-KEY: n8n_api_42f1838c1e2de90cadcb669f78083de92697a85322c0b6009ad2e55760db992ab0bf61515a3cf0e1" \
-H "Content-Type: application/json" \
-d '{"active": true}'
# Deactivate (use for maintenance or testing)
curl -X PATCH "http://localhost:8098/api/v1/workflows/gUDqTiHyHSfRUXv6" \
-H "X-N8N-API-KEY: n8n_api_42f1838c1e2de90cadcb669f78083de92697a85322c0b6009ad2e55760db992ab0bf61515a3cf0e1" \
-H "Content-Type: application/json" \
-d '{"active": false}'
```
### 5. Execute Workflow
```bash
curl -X POST "https://flow.egonetix.de/api/v1/workflows/{workflow_id}/executions" \
-H "X-N8N-API-KEY: n8n_api_42f1838c1e2de90cadcb669f78083de92697a85322c0b6009ad2e55760db992ab0bf61515a3cf0e1" \
-H "Content-Type: application/json" \
-d '{
"data": {
"symbol": "SOL-PERP",
"direction": "long",
"atr": 0.45
}
}'
```
### 6. List Executions
```bash
curl -X GET "https://flow.egonetix.de/api/v1/executions?workflowId={workflow_id}&limit=10" \
-H "X-N8N-API-KEY: n8n_api_42f1838c1e2de90cadcb669f78083de92697a85322c0b6009ad2e55760db992ab0bf61515a3cf0e1" \
-H "Accept: application/json"
```
---
## Trading Bot Workflows
### Key Workflows to Manage
1. **Parse Signal Enhanced**
- Extracts metrics from TradingView alerts
- Parses: ATR, ADX, RSI, volumeRatio, pricePosition, timeframe, indicator version
- **Future:** Will include maGap for v9 indicator
2. **Check Risk**
- Calls `/api/trading/check-risk` endpoint
- Validates signal quality score
- Checks duplicate signals, cooldown periods
- Blocks if quality < threshold (LONG: 90, SHORT: 95)
3. **Execute Trade**
- Calls `/api/trading/execute` endpoint
- Opens position on Drift Protocol
- Places TP/SL orders
- Adds to Position Manager monitoring
### Updating Workflows for v9 Enhancement
When implementing v9 MA gap enhancement:
**Step 1: Update Parse Signal Enhanced node**
```json
{
"nodes": [
{
"name": "Parse Signal Enhanced",
"parameters": {
"jsCode": "// Add MA gap parsing\nconst maGapMatch = message.match(/MAGAP:([\\d.-]+)/);\nconst maGap = maGapMatch ? parseFloat(maGapMatch[1]) : undefined;\n\nreturn { maGap };"
}
}
]
}
```
**Step 2: Update HTTP Request nodes**
Add `maGap` to request body:
```json
{
"body": {
"symbol": "={{$json.symbol}}",
"direction": "={{$json.direction}}",
"atr": "={{$json.atr}}",
"adx": "={{$json.adx}}",
"rsi": "={{$json.rsi}}",
"volumeRatio": "={{$json.volumeRatio}}",
"pricePosition": "={{$json.pricePosition}}",
"maGap": "={{$json.maGap}}",
"timeframe": "={{$json.timeframe}}"
}
}
```
---
## Workflow IDs Reference
**Trading Workflow:**
- **ID:** `gUDqTiHyHSfRUXv6`
- **Name:** Money Machine
- **Status:** Active
- **Nodes:**
- Parse Signal Enhanced (extracts TradingView metrics)
- Check Risk1 (validates quality score, duplicates, cooldowns)
- Execute Trade1 (opens position on Drift)
- Trade Success? (validation branching)
**Quick Commands:**
```bash
# Get Money Machine workflow
curl -s http://localhost:8098/api/v1/workflows/gUDqTiHyHSfRUXv6 \
-H "X-N8N-API-KEY: n8n_api_42f1838c1e2de90cadcb669f78083de92697a85322c0b6009ad2e55760db992ab0bf61515a3cf0e1"
# List all workflows
curl -s http://localhost:8098/api/v1/workflows \
-H "X-N8N-API-KEY: n8n_api_42f1838c1e2de90cadcb669f78083de92697a85322c0b6009ad2e55760db992ab0bf61515a3cf0e1" \
| jq -r '.data[] | "\(.id) | \(.name) | Active: \(.active)"'
```
---
## API Response Examples
### Successful Workflow List
```json
{
"data": [
{
"id": "12345",
"name": "Trading Signal Complete Workflow",
"active": true,
"createdAt": "2025-11-15T12:00:00.000Z",
"updatedAt": "2025-11-20T15:30:00.000Z",
"nodes": [...],
"connections": {...}
}
]
}
```
### Error Responses
**401 Unauthorized:**
```json
{
"code": 401,
"message": "Unauthorized"
}
```
→ Check API key is correct
**404 Not Found:**
```json
{
"code": 404,
"message": "Workflow not found"
}
```
→ Check workflow ID
**429 Rate Limited:**
```json
{
"code": 429,
"message": "Too many requests"
}
```
→ Wait before retrying
---
## Troubleshooting
### API Connection Issues
**DNS Resolution Failed:**
```bash
# Test DNS
ping flow.egonetix.de
# If fails, check:
# 1. n8n instance is running
# 2. Domain DNS is configured
# 3. Server firewall allows access
```
**SSL Certificate Issues:**
```bash
# Test with --insecure (dev only!)
curl --insecure -X GET "https://flow.egonetix.de/api/v1/workflows" \
-H "X-N8N-API-KEY: n8n_api_42f1838c1e2de90cadcb669f78083de92697a85322c0b6009ad2e55760db992ab0bf61515a3cf0e1"
```
**401 Unauthorized:**
- Verify API key is correct (no typos)
- Check API key hasn't been revoked in n8n settings
- Ensure API access is enabled in n8n instance
---
## Security Best Practices
1. **Store API key in .env file** (never commit to git)
2. **Use environment variables** in scripts:
```bash
export N8N_API_KEY="n8n_api_42f1838c1e2de90cadcb669f78083de92697a85322c0b6009ad2e55760db992ab0bf61515a3cf0e1"
curl -H "X-N8N-API-KEY: $N8N_API_KEY" ...
```
3. **Rotate API keys periodically** (quarterly recommended)
4. **Monitor API usage** in n8n admin panel
5. **Restrict API key permissions** if possible (read vs write)
---
## Automated Workflow Management Scripts
### Check Workflow Status
```bash
#!/bin/bash
# check-n8n-workflows.sh
API_KEY="n8n_api_42f1838c1e2de90cadcb669f78083de92697a85322c0b6009ad2e55760db992ab0bf61515a3cf0e1"
BASE_URL="https://flow.egonetix.de/api/v1"
echo "🔍 Checking n8n workflows..."
curl -s -X GET "$BASE_URL/workflows" \
-H "X-N8N-API-KEY: $API_KEY" \
| jq -r '.data[] | "[\(if .active then "✅" else "❌" end)] \(.name) (ID: \(.id))"'
```
### Deploy Workflow Update
```bash
#!/bin/bash
# deploy-workflow-update.sh
WORKFLOW_ID=$1
WORKFLOW_FILE=$2
if [ -z "$WORKFLOW_ID" ] || [ -z "$WORKFLOW_FILE" ]; then
echo "Usage: ./deploy-workflow-update.sh <workflow_id> <workflow.json>"
exit 1
fi
API_KEY="n8n_api_42f1838c1e2de90cadcb669f78083de92697a85322c0b6009ad2e55760db992ab0bf61515a3cf0e1"
BASE_URL="https://flow.egonetix.de/api/v1"
echo "📤 Deploying workflow update..."
curl -X PATCH "$BASE_URL/workflows/$WORKFLOW_ID" \
-H "X-N8N-API-KEY: $API_KEY" \
-H "Content-Type: application/json" \
-d @"$WORKFLOW_FILE" \
| jq '.'
```
---
## Next Steps After API Test
Once n8n instance is reachable:
1. **Test API connection:**
```bash
curl -X GET "https://flow.egonetix.de/api/v1/workflows" \
-H "X-N8N-API-KEY: n8n_api_42f1838c1e2de90cadcb669f78083de92697a85322c0b6009ad2e55760db992ab0bf61515a3cf0e1"
```
2. **Document workflow IDs** in this file
3. **Update .env file** with API key:
```bash
sed -i 's/N8N_API_KEY=.*/N8N_API_KEY=n8n_api_42f1838c1e2de90cadcb669f78083de92697a85322c0b6009ad2e55760db992ab0bf61515a3cf0e1/' /home/icke/traderv4/.env
```
4. **Backup current workflows:**
```bash
mkdir -p /home/icke/traderv4/workflows/n8n/backups
# Export each workflow via API
```
5. **Test workflow update** with non-critical workflow first
---
**Status:** ✅ API key verified and working (Nov 26, 2025)
**Instance:** http://localhost:8098 (Docker container n8n)
**Main Workflow:** Money Machine (ID: gUDqTiHyHSfRUXv6) - Active
**Last Test:** Nov 26, 2025 - Successfully listed workflows and retrieved Money Machine details