### Starting the Backend Server Manually for nofx Source: https://github.com/nofxaios/nofx/blob/dev/README.md Instructions for starting the nofx backend server after manual installation. This involves building the Go program and then executing the compiled binary. The output indicates successful startup and the API server address. ```bash # Build the program (first time only, or after code changes) go build -o nofx # Start the backend ./nofx ``` -------------------------------- ### Docker One-Click Deployment for nofx Source: https://github.com/nofxaios/nofx/blob/dev/README.md This snippet demonstrates the easiest way to deploy the nofx AI trading platform using Docker. It automates dependency installation and environment setup, requiring only configuration file preparation and running a start script or docker compose command. Access is then available via a web browser. ```bash # Copy configuration template cp config.json.example config.json # Edit and fill in your API keys nano config.json # or use any editor ``` ```bash # Option 1: Use convenience script (Recommended) chmod +x start.sh ./start.sh start --build ``` ```bash # Option 2: Use docker compose directly docker compose up -d --build ``` ```bash ./start.sh logs # View logs ./start.sh status # Check status ./start.sh stop # Stop services ./start.sh restart # Restart services ``` -------------------------------- ### NoFx System Configuration Examples Source: https://github.com/nofxaios/nofx/blob/dev/docs/prompt-guide.md Illustrates how to configure NoFx prompts, specifically focusing on the 'override_base_prompt' setting which controls whether custom prompts replace or augment the default system prompt. ```text ## Method 2: Add Custom Strategy on Top of Official Template (Recommended) Steps: 1. Keep `prompts/default.txt` unchanged 2. Add your strategy in the web interface's "Custom Prompt" 3. **Turn OFF** "Override Base Prompt" switch (`override_base_prompt = false`) ## Method 3: Complete Customization (Advanced) Steps: 1. Write a complete Prompt (including all risk control rules) 2. **Turn ON** "Override Base Prompt" switch (`override_base_prompt = true`) 3. ⚠️ You are responsible for all risk controls and output formats ``` -------------------------------- ### System configuration validation snippet Source: https://github.com/nofxaios/nofx/blob/dev/docs/prompt-guide.md Example showing correct mode configuration validation with hard constraints check. Prevents decision validation failure when using override modes ```text Set override_base_prompt = true But custom Prompt doesn't include hard constraints and output format ❌ Wrong Example: Set override_base_prompt = true But custom Prompt doesn't include hard constraints and output format ``` -------------------------------- ### Demonstrate Go Backend Code Quality Standards Source: https://github.com/nofxaios/nofx/blob/dev/docs/maintainers/PR_REVIEW_GUIDE.md Shows bad and good examples of Go function implementations for PR review. The good example demonstrates proper error handling, parameter validation, and meaningful naming, while the bad example shows ambiguous naming and lack of error handling. These patterns help maintainers evaluate code quality against project standards. ```go // ❌ Bad - Reject func GetData(a, b string) interface{} { d := doSomething(a, b) return d } // ✅ Good - Approve func GetAccountBalance(apiKey, secretKey string) (*Balance, error) { if apiKey == "" || secretKey == "" { return nil, fmt.Errorf("API credentials required") } balance, err := client.FetchBalance(apiKey, secretKey) if err != nil { return nil, fmt.Errorf("failed to fetch balance: %w", err) } return balance, nil } ``` -------------------------------- ### Manual Installation Dependencies for nofx Source: https://github.com/nofxaios/nofx/blob/dev/README.md This section details the manual installation process for the nofx AI trading platform, focusing on setting up the necessary environment and dependencies. It covers installing the TA-Lib library on macOS and Ubuntu/Debian, cloning the project repository, and installing backend (Go) and frontend (Node.js) dependencies. ```bash brew install ta-lib ``` ```bash sudo apt-get install libta-lib0-dev ``` ```bash git clone https://github.com/tinkle-community/nofx.git cd nofx ``` ```bash # Backend: go mod download ``` ```bash # Frontend: cd web npm install cd .. ``` -------------------------------- ### Create Test PR in Bash Source: https://github.com/nofxaios/nofx/blob/dev/docs/maintainers/SETUP_GUIDE.md This Bash script automates creating a test branch with a simple file change, committing, and pushing to verify PR system automation. It requires Git, GitHub CLI, and repository write access. Input: None directly, but relies on existing Git setup. Output: A new branch and committed file ready for PR creation. Limitations: Fails if GitHub authentication is invalid or branch conflicts exist. ```bash # Create a test branch git checkout -b test/pr-system-check # Make a small change echo "# Test" >> TEST.md # Commit and push git add TEST.md git commit -m "test: verify PR automation system" git push origin test/pr-system-check # Create PR on GitHub # Verify: # - PR template loads # - Auto-labels are applied # - CI checks run # - Size label is added ``` -------------------------------- ### NoFx Prompt Output Format Example Source: https://github.com/nofxaios/nofx/blob/dev/docs/prompt-guide.md Demonstrates the required output format for NoFx AI trading decisions, which includes XML tags for reasoning and a JSON array for specific trading actions like opening positions. ```xml BTC broke support, MACD death cross, volume increased... ```json [ { "symbol": "BTCUSDT", "action": "open_short", "leverage": 10, "position_size_usd": 5000, "stop_loss": 97000, "take_profit": 91000, "confidence": 85, "reasoning": "Bearish technical turn" } ] ``` ``` -------------------------------- ### Git Workflow for Contributing Source: https://github.com/nofxaios/nofx/blob/dev/README.md A quick start guide for contributing to the nofx project using Git. It covers forking the repository, creating a feature branch, committing changes, and pushing the branch to open a pull request. ```git 1. Fork the project 2. Create feature branch (`git checkout -b feature/AmazingFeature`) 3. Commit changes (`git commit -m 'Add some AmazingFeature'`) 4. Push to branch (`git push origin feature/AmazingFeature`) 5. Open Pull Request ``` -------------------------------- ### Demonstrate Go Security Best Practices Source: https://github.com/nofxaios/nofx/blob/dev/docs/maintainers/PR_REVIEW_GUIDE.md Shows insecure and secure Go authentication code for PR review. The insecure example demonstrates SQL injection vulnerability through string concatenation, while the secure example uses parameterized queries. These patterns help maintainers identify and prevent critical security vulnerabilities in database operations. ```go // 🚨 REJECT - Security Issue func Login(username, password string) { query := "SELECT * FROM users WHERE username='" + username + "'" // SQL Injection! db.Query(query) } // ✅ APPROVE - Secure func Login(username, password string) error { query := "SELECT * FROM users WHERE username = ?" row := db.QueryRow(query, username) // Parameterized query // ... proper password verification with bcrypt } ``` -------------------------------- ### Sync GitHub Labels Using CLI or GitHub Action Source: https://github.com/nofxaios/nofx/blob/dev/docs/maintainers/SETUP_GUIDE.md Provides methods to synchronize GitHub labels defined in labels.yml. Option 1 uses gh CLI for manual label management. Option 2 uses GitHub Labeler Action for automated synchronization on push events. ```bash # Option 1: Using gh CLI (recommended) gh label list # See current labels gh label delete # Remove old labels if needed gh label create "priority: critical" --color "d73a4a" --description "Critical priority" # ... repeat for all labels in labels.yml ``` ```yaml name: Sync Labels on: push: branches: [main, dev] paths: - '.github/labels.yml' jobs: labels: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: crazy-max/ghaction-github-labeler@v5 with: github-token: ${{ secrets.GITHUB_TOKEN }} yaml-file: .github/labels.yml ``` -------------------------------- ### Starting the Frontend Development Server for nofx Source: https://github.com/nofxaios/nofx/blob/dev/README.md This snippet shows how to start the frontend development server for the nofx platform. It requires navigating to the 'web' directory and running the npm dev command. This should be done in a separate terminal window from the backend server. ```bash cd web npm run dev ``` -------------------------------- ### Define Code Owners for Repository Areas Source: https://github.com/nofxaios/nofx/blob/dev/docs/maintainers/SETUP_GUIDE.md Configures CODEOWNERS file to automatically assign code review responsibilities based on file paths. Supports global owners, frontend, exchange integrations, AI components, and documentation areas. ```text # Global owners * @tinkle @zack # Frontend /web/ @frontend-lead # Exchange integrations /internal/exchange/ @exchange-lead # AI components /internal/ai/ @ai-lead # Documentation /docs/ @tinkle @zack *.md @tinkle @zack ``` -------------------------------- ### Create and Manage AutoTrader (Go) Source: https://context7.com/nofxaios/nofx/llms.txt This code demonstrates how to initialize a trading database, configure an automated trading bot with exchange settings and trading parameters, start the trader in a background goroutine, monitor its status and account information in real-time, and gracefully stop the trader. The example uses the nofx/trader and nofx/config packages to create a BTC scalper bot that trades on Binance with configurable leverage and scanning intervals. ```go package main import ( "fmt" "log" "time" "nofx/trader" "nofx/config" ) func main() { // Initialize database database, err := config.NewDatabase("config.db") if err != nil { log.Fatal(err) } defer database.Close() // Create trader configuration traderConfig := trader.AutoTraderConfig{ ID: "my_trader_001", Name: "BTC Scalper Bot", AIModelID: "deepseek", ExchangeID: "binance", InitialBalance: 1000.0, BTCETHLeverage: 5, AltcoinLeverage: 5, ScanIntervalMinutes: 3, TradingSymbols: []string{"BTCUSDT", "ETHUSDT"}, IsCrossMargin: true, } // Create trader instance autoTrader, err := trader.NewAutoTrader(traderConfig, database, "user_id_here") if err != nil { log.Fatal(err) } // Set custom prompt (optional) autoTrader.SetCustomPrompt("Focus on breakout patterns. Use tight stop losses.") autoTrader.SetOverrideBasePrompt(false) // Append to base prompt // Start trader in background go func() { if err := autoTrader.Run(); err != nil { log.Printf("Trader error: %v", err) } }() // Monitor trader status ticker := time.NewTicker(30 * time.Second) defer ticker.Stop() for i := 0; i < 10; i++ { <-ticker.C // Get status status := autoTrader.GetStatus() fmt.Printf("\n=== Trader Status ===\n") fmt.Printf("Running: %v\n", status["is_running"]) fmt.Printf("Uptime: %v minutes\n", status["uptime_minutes"]) fmt.Printf("Total Decisions: %v\n", status["total_decisions"]) // Get account info account, err := autoTrader.GetAccountInfo() if err == nil { fmt.Printf("\n=== Account Info ===\n") fmt.Printf("Balance: %.2f USDT\n", account["total_wallet_balance"]) fmt.Printf("Unrealized P&L: %.2f USDT\n", account["total_unrealized_profit"]) fmt.Printf("Available: %.2f USDT\n", account["available_balance"]) } } // Stop trader gracefully fmt.Println("\nStopping trader...") autoTrader.Stop() fmt.Println("Trader stopped successfully") } ``` -------------------------------- ### Test Frontend Auto-Labeling in Bash Source: https://github.com/nofxaios/nofx/blob/dev/docs/maintainers/SETUP_GUIDE.md This Bash script creates a test branch with a frontend file change to verify auto-labeling for frontend areas. It depends on Git and repository access. Input: None, but assumes a clean working directory. Output: A new branch and file creation. Limitations: Labels must be pre-configured in GitHub, and automation may not apply if workflows fail. ```bash # Test 1: Frontend changes git checkout -b test/frontend-label touch web/src/test.tsx git add . && git commit -m "test: frontend labeling" git push origin test/frontend-label # Should get "area: frontend" label ``` -------------------------------- ### Test Backend Auto-Labeling in Bash Source: https://github.com/nofxaios/nofx/blob/dev/docs/maintainers/SETUP_GUIDE.md This Bash script creates a test branch with a backend file change to verify auto-labeling for backend areas. It requires Git and repository permissions. Input: None direct. Output: A new branch and file creation. Limitations: Dependent on labeler.yml configuration; may require manual label application if automation is disabled. ```bash # Test 2: Backend changes git checkout -b test/backend-label touch internal/test.go git add . && git commit -m "test: backend labeling" git push origin test/backend-label # Should get "area: backend" label ``` -------------------------------- ### Validate GitHub Workflow Locally in Bash Source: https://github.com/nofxaios/nofx/blob/dev/docs/maintainers/SETUP_GUIDE.md This Bash command uses the 'act' tool to validate GitHub Actions workflows locally. It depends on 'act' installed. Input: None. Output: Workflow validation results. Limitations: Requires Docker; may not catch all GitHub-specific issues; simulations are local. ```bash # Validate workflow locally act pull_request # Using 'act' tool ``` -------------------------------- ### Retrieve PRs and Issues Data in Bash Source: https://github.com/nofxaios/nofx/blob/dev/docs/maintainers/SETUP_GUIDE.md This Bash script uses GitHub CLI to list all pull requests and issues with metadata for weekly reviews. It requires GitHub CLI authenticated. Input: None. Output: JSON data of PRs and issues. Limitations: Limited to CLI permissions; alternative is GitHub Insights for UI metrics. ```bash # Using gh CLI gh pr list --state all --json number,createdAt,closedAt gh issue list --state all --json number,createdAt,closedAt # Or use GitHub Insights # Repository → Insights → Pulse, Contributors, Traffic ``` -------------------------------- ### Emergency System Reset - Complete Recovery Procedure Source: https://github.com/nofxaios/nofx/blob/dev/docs/guides/TROUBLESHOOTING.md Emergency reset procedure for completely broken systems. Includes stopping all services, backing up databases, removing database files, and performing a complete restart with rebuild. Warning: This will lose trading history but provides a clean system start. ```bash # Stop everything docker compose down # Backup databases (just in case) cp config.db config.db.backup cp trading.db trading.db.backup # Remove databases (fresh start) rm config.db trading.db # Restart with rebuild docker compose up -d --build ``` -------------------------------- ### Database Query Commands - Traders, Models, and Config Source: https://github.com/nofxaios/nofx/blob/dev/docs/guides/TROUBLESHOOTING.md SQLite commands to query the NOFX configuration database for traders, AI models, and system configuration. These diagnostic queries help verify system setup, check AI model status, and troubleshoot configuration issues. ```bash # Check traders in database sqlite3 config.db "SELECT id, name, ai_model_id, exchange_id, is_running FROM traders;" # Check AI models sqlite3 config.db "SELECT id, name, model_type, enabled FROM ai_models;" # Check system configuration sqlite3 config.db "SELECT key, value FROM system_config;" ``` -------------------------------- ### Core strategy prompt template with hard constraints Source: https://github.com/nofxaios/nofx/blob/dev/docs/prompt-guide.md Complete template framework for Mode 3 custom prompts including core strategy description, hard constraints for risk management, and XML+JSON output format requirements ```text [Your Core Strategy] # Hard Constraints 1. Risk-reward ratio ≥ 1:3 2. Maximum 3 positions 3. Single position: Altcoin 0.8-1.5x equity, BTC/ETH 5-10x equity 4. Leverage: Altcoin ≤5x, BTC/ETH ≤20x 5. Margin usage ≤ 90% 6. Minimum opening: General ≥12U, BTC/ETH ≥60U # Output Format Use and tags: Chain of thought analysis ```json [{decision object}] ``` ``` -------------------------------- ### Demonstrate TypeScript React Code Quality Standards Source: https://github.com/nofxaios/nofx/blob/dev/docs/maintainers/PR_REVIEW_GUIDE.md Shows bad and good examples of TypeScript React component implementations for PR review. The good example demonstrates proper type safety with interfaces, functional component patterns, and JSX structure, while the bad example shows unsafe use of 'any' type and poor component design. These patterns help maintainers evaluate frontend code quality. ```typescript // ❌ Bad - Reject const getData = (data: any) => { return data.map(d =>
{d.name}
) } // ✅ Good - Approve interface Trader { id: string; name: string; status: 'running' | 'stopped'; } const TraderList: React.FC<{ traders: Trader[] }> = ({ traders }) => { return (
{traders.map(trader => ( ))}
); }; ``` -------------------------------- ### Start Trader with Curl Source: https://context7.com/nofxaios/nofx/llms.txt Initiates the trading process for a specified trader. This endpoint activates the bot, allowing it to start making decisions and executing trades based on its configuration. An authorization token is required. ```bash # Start trader curl -X POST http://localhost:8080/api/traders/trader_abc123/start \ -H "Authorization: Bearer YOUR_JWT_TOKEN" ``` -------------------------------- ### Install TA-Lib for macOS and Ubuntu Source: https://github.com/nofxaios/nofx/blob/dev/README.md Instructions for installing the TA-Lib library, a common dependency for financial technical analysis, on macOS and Ubuntu systems. This is crucial for resolving compilation errors related to TA-Lib not being found. ```bash # macOS brew install ta-lib # Ubuntu sudo apt-get install libta-lib0-dev ``` -------------------------------- ### Check Backend and Processes Source: https://github.com/nofxaios/nofx/blob/dev/docs/guides/TROUBLESHOOTING.md Commands to verify if the nofx backend is running and to list running processes. Useful for initial system health checks. ```bash docker compose ps ps aux | grep nofx ``` -------------------------------- ### GET /api/performance Source: https://context7.com/nofxaios/nofx/llms.txt Get detailed AI performance analysis with per-coin statistics and comprehensive performance metrics. The endpoint is mentioned but the documentation appears to be incomplete in the provided text. ```APIDOC ## GET /api/performance ### Description Get detailed AI performance analysis with per-coin statistics and comprehensive performance metrics. Provides in-depth analysis of AI trading performance across different cryptocurrencies. ### Method GET ### Endpoint /api/performance ### Parameters #### Path Parameters None #### Query Parameters - **trader_id** (string) - Required - Unique identifier for the trader #### Request Body None ### Request Example ``` GET /api/performance?trader_id=trader_abc123 Authorization: Bearer YOUR_JWT_TOKEN ``` ### Response #### Success Response (200) - Performance analysis data (structure not fully documented in provided text) #### Response Example ```json { "message": "Performance analysis endpoint - detailed response structure not provided in documentation" } ``` ``` -------------------------------- ### POST /api/traders/{trader_id}/start Source: https://context7.com/nofxaios/nofx/llms.txt Start a specified trader to begin autonomous trading operations. ```APIDOC ## POST /api/traders/{trader_id}/start ### Description Start a specified trader to begin autonomous trading operations. ### Method POST ### Endpoint /api/traders/{trader_id}/start ### Parameters #### Path Parameters - **trader_id** (string) - Required - The ID of the trader to start. #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X POST http://localhost:8080/api/traders/trader_abc123/start \ -H "Authorization: Bearer YOUR_JWT_TOKEN" ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message that the trader has started. #### Response Example ```json { "message": "Trader started successfully" } ``` ``` -------------------------------- ### Trader Management API Source: https://github.com/nofxaios/nofx/blob/dev/README.md Endpoints for managing trading instances, including creation, deletion, starting, and stopping. ```APIDOC ## GET /api/traders ### Description Retrieves a list of all configured traders. ### Method GET ### Endpoint /api/traders ### Parameters None ### Request Example None ### Response #### Success Response (200) - **traders** (array) - An array of trader objects, each containing trader details. #### Response Example ```json { "traders": [ { "id": "trader_123", "name": "BTC Scalper", "status": "running", "model_id": "v2.0.2" } ] } ``` ## POST /api/traders ### Description Creates a new trader instance. Requires a JSON payload with trader configuration details. ### Method POST ### Endpoint /api/traders ### Parameters #### Request Body - **name** (string) - Required - The name for the new trader. - **model_id** (string) - Required - The ID of the AI model to use. - **exchange_id** (string) - Required - The ID of the exchange configuration to use. ### Request Example ```json { "name": "ETH Futures Trader", "model_id": "v2.0.2", "exchange_id": "bybit_config" } ``` ### Response #### Success Response (201) - **id** (string) - The unique ID of the newly created trader. - **message** (string) - Confirmation message. #### Response Example ```json { "id": "trader_456", "message": "Trader created successfully." } ``` ## DELETE /api/traders/:id ### Description Deletes a specific trader instance identified by its ID. ### Method DELETE ### Endpoint /api/traders/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the trader to delete. ### Request Example None ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating successful deletion. #### Response Example ```json { "message": "Trader deleted successfully." } ``` ## POST /api/traders/:id/start ### Description Starts a specific trader instance identified by its ID. ### Method POST ### Endpoint /api/traders/:id/start ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the trader to start. ### Request Example None ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the trader has started. #### Response Example ```json { "message": "Trader started successfully." } ``` ## POST /api/traders/:id/stop ### Description Stops a specific trader instance identified by its ID. ### Method POST ### Endpoint /api/traders/:id/stop ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the trader to stop. ### Request Example None ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the trader has stopped. #### Response Example ```json { "message": "Trader stopped successfully." } ``` ``` -------------------------------- ### Configure Trader Leverage Settings Source: https://github.com/nofxaios/nofx/blob/dev/docs/guides/TROUBLESHOOTING.md JSON configuration for setting leverage limits for BTC/ETH and altcoins. This is used to adjust trading risk within the nofx Web UI. ```json { "btc_eth_leverage": 5, "altcoin_leverage": 5 } ``` -------------------------------- ### GET /api/positions Source: https://context7.com/nofxaios/nofx/llms.txt List all open positions for a specific trader, including details like entry price, current P&L, and liquidation price. ```APIDOC ## GET /api/positions ### Description List all open positions for a specific trader, including details like entry price, current P&L, and liquidation price. ### Method GET ### Endpoint /api/positions ### Parameters #### Path Parameters None #### Query Parameters - **trader_id** (string) - Required - The ID of the trader whose positions are to be retrieved. #### Request Body None ### Request Example ```bash curl "http://localhost:8080/api/positions?trader_id=trader_abc123" \ -H "Authorization: Bearer YOUR_JWT_TOKEN" ``` ### Response #### Success Response (200) - **data** (array) - A list of open positions. - **symbol** (string) - Trading symbol (e.g., "BTCUSDT"). - **position_side** (string) - Side of the position (e.g., "LONG", "SHORT"). - **position_amount** (float) - The amount of the asset in the position. - **entry_price** (float) - The price at which the position was opened. - **mark_price** (float) - The current market price. - **unrealized_profit** (float) - The unrealized profit or loss for the position. - **unrealized_profit_percentage** (float) - The unrealized profit or loss as a percentage. - **leverage** (integer) - The leverage applied to the position. - **liquidation_price** (float) - The price at which the position would be liquidated. - **margin_type** (string) - The margin type (e.g., "cross", "isolated"). - **position_value_usd** (float) - The total value of the position in USD. - **holding_duration_minutes** (integer) - The duration the position has been held in minutes. - **count** (integer) - The total number of open positions. - **total_unrealized_pnl** (float) - The sum of unrealized P&L across all open positions. #### Response Example ```json { "data": [ { "symbol": "BTCUSDT", "position_side": "LONG", "position_amount": 0.01, "entry_price": 95000.0, "mark_price": 96500.0, "unrealized_profit": 15.0, "unrealized_profit_percentage": 1.58, "leverage": 5, "liquidation_price": 76000.0, "margin_type": "cross", "position_value_usd": 965.0, "holding_duration_minutes": 45 }, { "symbol": "ETHUSDT", "position_side": "SHORT", "position_amount": 0.5, "entry_price": 3500.0, "mark_price": 3480.0, "unrealized_profit": 10.0, "unrealized_profit_percentage": 0.57, "leverage": 5, "liquidation_price": 4200.0, "margin_type": "cross", "position_value_usd": 1740.0, "holding_duration_minutes": 120 } ], "count": 2, "total_unrealized_pnl": 25.0 } ``` ``` -------------------------------- ### Delete Existing Labels in Bash Source: https://github.com/nofxaios/nofx/blob/dev/docs/maintainers/SETUP_GUIDE.md This Bash script deletes all existing GitHub labels using the GitHub CLI for syncing. It requires GitHub CLI installed and authenticated. Input: None. Output: All labels removed. Limitations: Cannot be undone; requires repository admin access; follow with manual label creation. ```bash # Delete all existing labels first gh label list --json name --jq '.[].name' | xargs -I {} gh label delete "{}" --yes # Then create from labels.yml manually or via action ``` -------------------------------- ### Build and Run Commands Source: https://github.com/nofxaios/nofx/blob/dev/docs/architecture/README.md Bash commands for building and running the application components. Backend compilation produces a nofx binary, frontend development uses npm dev server, and Docker compose provides containerized deployment. Covers development, testing, and production setups. ```bash # Backend go build -o nofx ./nofx # Frontend cd web npm run dev # Docker docker compose up --build ``` -------------------------------- ### List AI Model Configurations (Bash) Source: https://context7.com/nofxaios/nofx/llms.txt Retrieves a list of all configured AI models used by the NOFX system. Requires an authorization token for access. Returns details about each model's status and settings. ```bash # List AI models curl http://localhost:8080/api/models \ -H "Authorization: Bearer YOUR_JWT_TOKEN" ``` -------------------------------- ### Partial Reset Script with Docker Compose (Bash) Source: https://github.com/nofxaios/nofx/blob/dev/docs/guides/TROUBLESHOOTING.md This bash script clears decision logs, stops Docker containers, rebuilds images without cache, and restarts services in detached mode to perform a partial reset while keeping the project configuration intact. It requires Docker and Docker Compose to be installed and the project directory to contain a docker-compose.yml file. Inputs are command-line executions; outputs include cleared logs and refreshed containers; limitations include potential downtime during rebuild. ```bash # Clear decision logs rm -rf decision_logs/* # Clear Docker cache and rebuild docker compose down docker compose build --no-cache docker compose up -d ``` -------------------------------- ### View system logs to find actual AI prompts Source: https://github.com/nofxaios/nofx/blob/dev/docs/prompt-guide.md Docker command to view system logs and locate the actual prompts sent to the AI system. This helps with debugging prompt validation and ensuring field references match actual output format ```bash # View system logs, find actual Prompt sent to AI docker logs nofx-trader | grep "User Prompt" ``` -------------------------------- ### Get Competition Leaderboard Source: https://context7.com/nofxaios/nofx/llms.txt Retrieves a leaderboard of all active traders in the competition, including their performance metrics and rank. You can also filter the results to get only the top traders. ```APIDOC ## GET /api/competition ### Description Get full competition data comparing all active traders. ### Method GET ### Endpoint `/api/competition` ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of traders to return. ### Request Example ```bash # Get competition leaderboard curl http://localhost:8080/api/competition \ -H "Authorization: Bearer YOUR_JWT_TOKEN" # Get only top 3 traders curl -s http://localhost:8080/api/competition?limit=3 \ -H "Authorization: Bearer YOUR_JWT_TOKEN" | jq '.traders[:3]' ``` ### Response #### Success Response (200) - **traders** (array) - An array of trader objects, each containing performance data. - **count** (integer) - The total number of traders. - **update_time** (string) - The timestamp of the last data update. #### Response Example ```json { "traders": [ { "id": "trader_abc123", "name": "DeepSeek BTC Trader", "ai_model": "deepseek", "exchange": "binance", "initial_balance": 1000.0, "current_equity": 1150.50, "pnl_percentage": 15.05, "win_rate": 62.22, "total_trades": 45, "sharpe_ratio": 1.85, "max_drawdown": 8.5, "rank": 1, "is_leader": true } ], "count": 2, "update_time": "2025-01-15T15:35:00Z" } ``` ``` -------------------------------- ### Backend Log Collection - Docker and PM2 Methods Source: https://github.com/nofxaios/nofx/blob/dev/docs/guides/TROUBLESHOOTING.md Commands to capture and analyze backend application logs from both Docker and PM2 deployments. Includes methods to view recent logs, follow live output, and save logs to files for troubleshooting trading decisions and system errors. ```bash # Docker method - View last 100 lines docker compose logs backend --tail=100 # Follow live logs docker compose logs -f backend # Save to file docker compose logs backend --tail=500 > backend_logs.txt ``` ```bash # PM2 method - Terminal where you ran ./nofx shows logs # PM2: pm2 logs nofx --lines 100 # Save to file pm2 logs nofx --lines 500 > backend_logs.txt ``` -------------------------------- ### Configuring and Using Coin Pool APIs in Go Source: https://context7.com/nofxaios/nofx/llms.txt This example configures the coin pool APIs for AI500 and OI Top, sets default coins as fallback, and demonstrates fetching various coin pools including AI500, top-rated, OI positions, merged pools, and available coins. It requires the 'nofx/pool' package and handles errors with logging. Outputs include coin lists, scores, positions, and symbols; limitations include dependency on external APIs which may fail, triggering fallback to defaults. ```go package main import ( "fmt" "log" "nofx/pool" ) func main() { // Configure coin pool APIs pool.SetCoinPoolAPI("https://api.example.com/ai500") pool.SetOITopAPI("https://api.example.com/oi-top") // Enable default coins fallback pool.SetUseDefaultCoins(true) pool.SetDefaultCoins([]string{ "BTCUSDT", "ETHUSDT", "SOLUSDT", "BNBUSDT", "XRPUSDT", "DOGEUSDT", }) // === Get AI500 Coin Pool === coins, err := pool.GetCoinPool() if err != nil { log.Printf("Error fetching coin pool: %v", err) // Falls back to default coins automatically } else { fmt.Printf("AI500 Coins: %d\n", len(coins)) for i, coin := range coins[:5] { fmt.Printf("%d. %s (Score: %.2f)\n", i+1, coin.Symbol, coin.Score) } } // === Get Top Rated Coins === topCoins, err := pool.GetTopRatedCoins(20) if err != nil { log.Printf("Error: %v", err) } else { fmt.Printf("\nTop 20 Rated Coins:\n") fmt.Println(topCoins) } // === Get OI Top Positions === oiPositions, err := pool.GetOITopPositions() if err != nil { log.Printf("Error: %v", err) } else { fmt.Printf("\nOI Top Positions: %d\n", len(oiPositions)) for _, pos := range oiPositions[:5] { fmt.Printf("- %s: Long $%.2fM | Short $%.2fM | Ratio: %.2f%%\n", pos.Symbol, pos.LongPositionUSD/1e6, pos.ShortPositionUSD/1e6, pos.LongShortRatio*100) } } // === Get Merged Coin Pool (AI500 + OI Top) === mergedPool, err := pool.GetMergedCoinPool(20) if err != nil { log.Printf("Error: %v", err) } else { fmt.Printf("\nMerged Coin Pool:\n") fmt.Printf("Total Symbols: %d\n", len(mergedPool.AllSymbols)) fmt.Printf("Symbols: %v\n", mergedPool.AllSymbols) // Check symbol sources for _, symbol := range mergedPool.AllSymbols[:5] { sources := mergedPool.SymbolSources[symbol] fmt.Printf("%s: %v\n", symbol, sources) } } // === Get Available Coins (respects default coins setting) === available, err := pool.GetAvailableCoins() if err != nil { log.Printf("Error: %v", err) } else { fmt.Printf("\nAvailable Coins for Trading: %d\n", len(available)) fmt.Println(available) } } ``` -------------------------------- ### Retrieve System Configuration (Bash) Source: https://context7.com/nofxaios/nofx/llms.txt Fetches the current system configuration, including trading parameters like leverage, risk limits, and enabled modes. Supports parsing specific configuration values using tools like `jq`. ```bash # Get system configuration curl http://localhost:8080/api/config # Response example # { # "beta_mode": false, # "api_server_port": 8080, # "use_default_coins": true, # "default_coins": ["BTCUSDT", "ETHUSDT", "SOLUSDT", "BNBUSDT", "XRPUSDT"], # "coin_pool_api_url": "", # "oi_top_api_url": "", # "max_daily_loss": 500.0, # "max_drawdown": 1000.0, # "stop_trading_minutes": 60, # "leverage": { # "btc_eth_leverage": 5, # "altcoin_leverage": 5 # }, # "admin_mode": true, # "registration_enabled": false # } # Parse specific values with jq curl -s http://localhost:8080/api/config | jq '.leverage.btc_eth_leverage' # Output: 5 ``` -------------------------------- ### Get Performance Analysis (Bash/curl) Source: https://context7.com/nofxaios/nofx/llms.txt Retrieves detailed AI performance analysis data from the API, including per-coin statistics. The command sends a GET request to the performance endpoint, requiring the trader ID. ```Bash curl "http://localhost:8080/api/performance?trader_id=trader_abc123" -H "Authorization: Bearer YOUR_JWT_TOKEN" ``` -------------------------------- ### GET /api/statistics Source: https://context7.com/nofxaios/nofx/llms.txt Get comprehensive trading statistics including win rate, profit factor, Sharpe ratio, and detailed trade analysis by symbol. Provides essential metrics for performance evaluation and risk assessment. ```APIDOC ## GET /api/statistics ### Description Get comprehensive trading statistics including win rate, profit factor, Sharpe ratio, and detailed trade analysis by symbol. Provides essential metrics for performance evaluation and risk assessment. ### Method GET ### Endpoint /api/statistics ### Parameters #### Path Parameters None #### Query Parameters - **trader_id** (string) - Required - Unique identifier for the trader #### Request Body None ### Request Example ``` GET /api/statistics?trader_id=trader_abc123 Authorization: Bearer YOUR_JWT_TOKEN ``` ### Response #### Success Response (200) - **total_trades** (number) - Total number of trades executed - **winning_trades** (number) - Number of profitable trades - **losing_trades** (number) - Number of losing trades - **win_rate** (number) - Percentage of winning trades - **average_profit_percentage** (number) - Average profit per winning trade - **average_loss_percentage** (number) - Average loss per losing trade - **profit_factor** (number) - Ratio of gross profit to gross loss - **sharpe_ratio** (number) - Risk-adjusted return measure - **max_drawdown** (number) - Maximum drawdown percentage - **total_pnl** (number) - Total profit and loss amount - **total_pnl_percentage** (number) - Total P&L as percentage - **best_trade** (object) - Best performing trade details - **worst_trade** (object) - Worst performing trade details - **trades_by_symbol** (object) - Performance breakdown by trading symbol #### Response Example ```json { "total_trades": 45, "winning_trades": 28, "losing_trades": 17, "win_rate": 62.22, "average_profit_percentage": 3.5, "average_loss_percentage": -2.1, "profit_factor": 1.67, "sharpe_ratio": 1.85, "max_drawdown": 8.5, "total_pnl": 150.50, "total_pnl_percentage": 15.05, "best_trade": { "symbol": "SOLUSDT", "pnl": 45.0, "pnl_percentage": 9.0, "date": "2025-01-14T18:30:00Z" }, "worst_trade": { "symbol": "BNBUSDT", "pnl": -25.0, "pnl_percentage": -5.0, "date": "2025-01-13T10:15:00Z" }, "trades_by_symbol": { "BTCUSDT": {"total": 20, "wins": 13, "win_rate": 65.0}, "ETHUSDT": {"total": 15, "wins": 9, "win_rate": 60.0}, "SOLUSDT": {"total": 10, "wins": 6, "win_rate": 60.0} } } ``` ``` -------------------------------- ### Get Trading Statistics (Bash/curl) Source: https://context7.com/nofxaios/nofx/llms.txt Retrieves comprehensive trading statistics from the API, including win rate, profit factor, and Sharpe ratio. It sends a GET request to the statistics endpoint with the trader ID. The response provides a detailed overview of trading performance. ```Bash curl "http://localhost:8080/api/statistics?trader_id=trader_abc123" -H "Authorization: Bearer YOUR_JWT_TOKEN" ``` -------------------------------- ### Interact with multiple exchanges using Go SDK Trader interface Source: https://context7.com/nofxaios/nofx/llms.txt Shows how to configure and use the unified Trader interface for Binance Futures, Hyperliquid DEX, and Aster DEX. It requires the nofx/trader and nofx/config packages, a SQLite database, and a user ID. The code retrieves balances, positions, places orders, sets stop‑losses, and demonstrates common methods across all exchanges. ```go package main import ( "fmt" "log" "nofx/trader" "nofx/config" ) func main() { db, err := config.NewDatabase("config.db") if err != nil { log.Fatal(err) } defer db.Close() userID := "user123" // === Example 1: Binance Futures === binanceConfig := trader.AutoTraderConfig{ ID: "binance_trader", ExchangeID: "binance", // ... other config } binanceTrader, _ := trader.NewAutoTrader(binanceConfig, db, userID) // Get balance balance, _ := binanceTrader.GetBalance() fmt.Printf("Binance Balance: %.2f USDT\n", balance["total_wallet_balance"]) // Get positions positions, _ := binanceTrader.GetPositions() fmt.Printf("Binance Positions: %d\n", len(positions)) // Open long position result, err := binanceTrader.OpenLong("BTCUSDT", 0.001, 5) if err != nil { log.Printf("Open long error: %v", err) } else { fmt.Printf("Order placed: %v\n", result) } // Set stop loss err = binanceTrader.SetStopLoss("BTCUSDT", "LONG", 0.001, 94000.0) if err != nil { log.Printf("Stop loss error: %v", err) } // === Example 2: Hyperliquid D === hyperConfig := trader.AutoTraderConfig{ ID: "hyper_trader", ExchangeID: "hyperliquid", // ... other config } hyperTrader, _ := trader.NewAutoTrader(hyperConfig, db, userID) // Get balance hyperBalance, _ := hyperTrader.GetBalance() fmt.Printf("Hyperliquid Balance: %.2f USDT\n", hyperBalance["total_wallet_balance"]) // Open short position result, err = hyperTrader.OpenShort("ETHUSDT", 0.1, 3) if err != nil { log.Printf("Open short error: %v", err) } // === Example 3: Aster DEX === asterConfig := trader.AutoTraderConfig{ ID: "aster_trader", ExchangeID: "aster", // ... other config } asterTrader, _ := trader.NewAutoTrader(asterConfig, db, userID) // Get market price btcPrice, _ := asterTrader.GetMarketPrice("BTCUSDT") fmt.Printf("BTC Price on Aster: %.2f\n", btcPrice) // === Common Interface Methods (work on all exchanges) === traders := []trader.Trader{binanceTrader, hyperTrader, asterTrader} for _, t := range traders { // Get balance bal, _ := t.GetBalance() fmt.Printf("Balance: %.2f\n", bal["total_wallet_balance"]) // Get positions pos, _ := t.GetPositions() fmt.Printf("Positions: %d\n", len(pos)) // Close all positions for _, p := range pos { symbol := p["symbol"].(string) side := p"position_side"].(string) qty := p["position_amount"].(float64) if side == "LONG" { t.CloseLong(symbol, qty) } else if side == "SHORT" { t.CloseShort(symbol, qty) } } // Cancel all orders t.CancelAllOrders("BTCUSDT") } } ``` -------------------------------- ### Code Quality Commands Source: https://github.com/nofxaios/nofx/blob/dev/docs/architecture/README.md Bash commands for code formatting, linting, and type checking. Go fmt formats Go code across the project, golangci-lint runs configured linters, and npm build performs TypeScript type checking for the frontend component. ```bash # Format Go code go fmt ./... # Lint (if configured) golangci-lint run # Type check TypeScript cd web && npm run build ``` -------------------------------- ### Docker Compose Environment Setup in YAML Source: https://github.com/nofxaios/nofx/blob/dev/README.md This YAML snippet configures environment variables in Docker Compose for the NOFX service, specifically setting the admin password. It facilitates secure deployment by injecting the NOFX_ADMIN_PASSWORD from host variables. Used in self-hosted setups; limitations include single-instance suitability without additional shared storage. ```yaml services: nofx: environment: - NOFX_ADMIN_PASSWORD=${NOFX_ADMIN_PASSWORD} ``` -------------------------------- ### Get Latest AI Decisions (Bash/curl/jq) Source: https://context7.com/nofxaios/nofx/llms.txt This snippet fetches the most recent AI trading decisions from the API. It uses curl to make a GET request, and jq to filter the response to retrieve only successful trades. The API response includes details about the decisions, reasoning, and execution status. ```Bash curl "http://localhost:8080/api/decisions/latest?trader_id=trader_abc123" -H "Authorization: Bearer YOUR_JWT_TOKEN" ``` ```Bash curl -s "http://localhost:8080/api/decisions/latest?trader_id=trader_abc123" -H "Authorization: Bearer YOUR_JWT_TOKEN" | jq '.data[] | select(.execution_status == \"success\" )' ```