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\" )'
```