[
{
"nodes": [
{
"parameters": {
"rule": {
"interval": [
{
"triggerAt": "atInterval"
}
]
},
"triggerAt": "*/5 * * * *",
"options": {}
},
"name": "Cron Trigger (Every 5 Min)",
"type": "n8n-nodes-base.cron",
"typeVersion": 1,
"position": [660, 220]
},
{
"parameters": {
"operation": "getAccountInfo",
"options": {}
},
"name": "Get Binance Account Info",
"type": "n8n-nodes-base.binanceApi",
"typeVersion": 1,
"position": [660, 380],
"credentials": {
"binanceApi": {
"environmentVariableName": "BINANCE_CREDENTIALS"
}
}
},
{
"parameters": {
"function": "const accountInfo = $json.data;\nconst availableBalance = accountInfo.balances.find(b => b.asset === 'USDT').free;\n\n// Simple check if a position in the target symbol exists\n// This assumes the target symbol is hardcoded or passed as a variable\nconst targetSymbol = $env['BINANCE_TRADE_SYMBOL'] || 'ETHUSDT'; // Example: ETHUSDT\nconst baseAsset = targetSymbol.replace('USDT', ''); // Example: ETH\nconst currentPosition = accountInfo.balances.find(b => b.asset === baseAsset).free;\n\n// Store relevant info for later use\nreturn [\n {\n json: {\n accountInfo: accountInfo,\n availableBalance: parseFloat(availableBalance),\n currentPosition: parseFloat(currentPosition),\n targetSymbol: targetSymbol,\n baseAsset: baseAsset\n }\n }\n];",
"options": {}
},
"name": "Process Account State",
"type": "n8n-nodes-base.code",
"typeVersion": 1,
"position": [660, 520],
"notes": "Check available balance and current position in the target asset. Reads target symbol from environment variable."
},
{
"parameters": {
"operation": "candlestickChart",
"symbol": "={{ $json.targetSymbol }}",
"interval": "5m",
"limit": 100,
"options": {}
},
"name": "Get Market Data (Candlesticks)",
"type": "n8n-nodes-base.binanceApi",
"typeVersion": 1,
"position": [890, 520],
"credentials": {
"binanceApi": {
"environmentVariableName": "BINANCE_CREDENTIALS"
}
},
"notes": "Fetch candlestick data for technical analysis and AI input."
},
{
"parameters": {
"url": "={{ $env['AI_SERVICE_URL'] }}",
"method": "POST",
"authentication": "none",
"bodyParameters": {
"parameters": [
{
"name": "candlestickData",
"value": "={{ $json.candlestickData }}"
},
{
"name": "accountInfo",
"value": "={{ $json.accountInfo }}"
},
{
"name": "currentPrice",
"value": "={{ $json.currentPrice }}"
}
]
},
"options": {}
},
"name": "Call External AI Service (RL Agent)",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 3,
"position": [1130, 520],
"notes": "Sends market data and account state to an external AI/RL service for decision making. Expects a JSON response like { \"action\": \"buy\", \"size\": 0.01, \"confidence\": 0.8 } or { \"action\": \"hold\" }"
},
{
"parameters": {
"function": "const aiResponse = $json.body;\nconst accountInfo = $json.accountInfo;\nconst availableBalance = $json.availableBalance;\nconst currentPosition = $json.currentPosition;\nconst targetSymbol = $json.targetSymbol;\nconst baseAsset = $json.baseAsset;\n\n// --- AI Response --- \nconst action = aiResponse.action; // e.g., 'buy', 'sell', 'hold'\nconst predictedSize = aiResponse.size || 0; // Optional: size suggested by AI\nconst confidence = aiResponse.confidence || 0; // Optional: confidence score\n\n// --- Risk Management & Position Check --- \nlet finalAction = 'hold';\nlet orderQuantity = 0;\nlet orderPrice = 0; // For limit orders, need logic to set this\nlet orderType = 'MARKET'; // Default to MARKET for simplicity, use LIMIT for better control\n\nconst minOrderValueUSDT = 10; // Binance minimum order value\nconst maxRiskPercentage = 0.01; // Example: risk 1% of available balance per trade\n\nif (action === 'buy') {\n // Avoid buying if we already hold a significant position or don't have enough USDT\n if (currentPosition < ($env['MAX_ALLOWED_POSITION_MULTIPLIER'] || 0.1) && availableBalance > minOrderValueUSDT) { // Example: Max position 10% of initial capital (needs proper state tracking)\n // Calculate potential buy quantity based on available balance and risk\n // This is a simplified example. A real risk model is much more complex.\n const maxSpendUSDT = availableBalance * ($env['MAX_SPEND_PERCENTAGE'] || 0.05); // Example: spend max 5% of available balance\n orderQuantity = maxSpendUSDT / $json.currentPrice; // Calculate quantity based on current price\n \n // Further refine quantity based on AI's suggested size and confidence\n // Example: Use AI's size if confidence is high, otherwise use calculated size\n // if (confidence > 0.7) orderQuantity = predictedSize; \n \n // Ensure order quantity meets Binance minimums (needs fetching exchange info)\n // For now, just a placeholder check\n if (orderQuantity * $json.currentPrice > minOrderValueUSDT) {\n finalAction = 'buy';\n }\n }\n} else if (action === 'sell') {\n // Check if we actually hold the asset to sell\n if (currentPosition > ($env['MIN_POSITION_TO_SELL'] || 0.0001)) { // Example: Need min position to sell\n // Decide how much to sell (e.g., all, partial based on AI size/confidence)\n orderQuantity = currentPosition; // Example: Sell all\n // if (confidence > 0.7 && predictedSize > 0 && predictedSize < currentPosition) orderQuantity = predictedSize;\n \n // Ensure quantity meets minimums\n if (orderQuantity * $json.currentPrice > minOrderValueUSDT) {\n finalAction = 'sell';\n }\n }\n}\n\n// Pass the decision and order details to the next nodes\nreturn [\n {\n json: {\n ...$json, // Keep previous data\n decision: finalAction,\n orderQuantity: orderQuantity,\n orderType: orderType,\n orderPrice: orderPrice, // Relevant for LIMIT orders\n aiResponse: aiResponse // Keep AI response for logging/debugging\n }\n }\n];",
"options": {}
},
"name": "Process AI Response & Risk",
"type": "n8n-nodes-base.code",
"typeVersion": 1,
"position": [1380, 520],
"notes": "Interprets the AI's decision, applies risk management rules, and determines the final action and order details. Requires significant custom logic."
},
{
"parameters": {
"conditions": [
{
"value1": "={{ $json.decision }}",
"operator": "in",
"value2": "buy,sell"
}
]
},
"name": "If Decision is Buy/Sell",
"type": "n8n-nodes-base.if",
"typeVersion": 1,
"position": [1620, 520]
},
{
"parameters": {
"operation": "createOrder",
"symbol": "={{ $json.targetSymbol }}",
"side": "buy",
"type": "={{ $json.orderType }}",
"quantity": "={{ $json.orderQuantity }}",
"options": {}
},
"name": "Place Buy Order",
"type": "n8n-nodes-base.binanceApi",
"typeVersion": 1,
"position": [1880, 380],
"credentials": {
"binanceApi": {
"environmentVariableName": "BINANCE_CREDENTIALS"
}
},
"notes": "Places a BUY order on Binance based on the calculated quantity and type."
},
{
"parameters": {
"operation": "createOrder",
"symbol": "={{ $json.targetSymbol }}",
"side": "sell",
"type": "={{ $json.orderType }}",
"quantity": "={{ $json.orderQuantity }}",
"options": {}
},
"name": "Place Sell Order",
"type": "n8n-nodes-base.binanceApi",
"typeVersion": 1,
"position": [1880, 660],
"credentials": {
"binanceApi": {
"environmentVariableName": "BINANCE_CREDENTIALS"
}
},
"notes": "Places a SELL order on Binance based on the calculated quantity and type."
},
{
"parameters": {
"text": "🤖 Trade Bot Alert:\n\n📈 **BUY Signal Detected!**\nSymbol: {{ $json.targetSymbol }}\nQuantity: {{ $json.orderQuantity.toFixed(4) }}\nOrder Type: {{ $json.orderType }}\nAI Confidence: {{ $json.aiResponse.confidence ? $json.aiResponse.confidence.toFixed(2) : 'N/A' }}\nStatus: Attempting to place order...",
"chatId": "={{ $env['TELEGRAM_CHAT_ID'] }}",
"options": {}
},
"name": "Send Buy Signal Telegram Alert",
"type": "n8n-nodes-base.telegram",
"typeVersion": 1,
"position": [1620, 380],
"credentials": {
"telegramApi": {
"environmentVariableName": "TELEGRAM_CREDENTIALS"
}
},
"notes": "Notifies Telegram channel about a detected BUY signal before placing the order."
},
{
"parameters": {
"text": "🤖 Trade Bot Alert:\n\n📉 **SELL Signal Detected!**\nSymbol: {{ $json.targetSymbol }}\nQuantity: {{ $json.orderQuantity.toFixed(4) }}\nOrder Type: {{ $json.orderType }}\nAI Confidence: {{ $json.aiResponse.confidence ? $json.aiResponse.confidence.toFixed(2) : 'N/A' }}\nStatus: Attempting to place order...",
"chatId": "={{ $env['TELEGRAM_CHAT_ID'] }}",
"options": {}
},
"name": "Send Sell Signal Telegram Alert",
"type": "n8n-nodes-base.telegram",
"typeVersion": 1,
"position": [1620, 660],
"credentials": {
"telegramApi": {
"environmentVariableName": "TELEGRAM_CREDENTIALS"
}
},
"notes": "Notifies Telegram channel about a detected SELL signal before placing the order."
},
{
"parameters": {
"text": "🤖 Trade Bot Alert:\n\n✅ **BUY Order Placed Successfully!**\nSymbol: {{ $json.targetSymbol }}\nQuantity: {{ $json.executedQty }}\nAvg. Price: {{ $json.cummulativeQuoteQty / $json.executedQty }}\nOrder ID: {{ $json.orderId }}\n",
"chatId": "={{ $env['TELEGRAM_CHAT_ID'] }}",
"options": {}
},
"name": "Send Buy Order Confirmation Telegram",
"type": "n8n-nodes-base.telegram",
"typeVersion": 1,
"position": [2150, 380],
"credentials": {
"telegramApi": {
"environmentVariableName": "TELEGRAM_CREDENTIALS"
}
},
"notes": "Notifies Telegram about a successful BUY order execution."
},
{
"parameters": {
"text": "🤖 Trade Bot Alert:\n\n✅ **SELL Order Placed Successfully!**\nSymbol: {{ $json.targetSymbol }}\nQuantity: {{ $json.executedQty }}\nAvg. Price: {{ $json.cummulativeQuoteQty / $json.executedQty }}\nOrder ID: {{ $json.orderId }}\n",
"chatId": "={{ $env['TELEGRAM_CHAT_ID'] }}",
"options": {}
},
"name": "Send Sell Order Confirmation Telegram",
"type": "n8n-nodes-base.telegram",
"typeVersion": 1,
"position": [2150, 660],
"credentials": {
"telegramApi": {
"environmentVariableName": "TELEGRAM_CREDENTIALS"
}
},
"notes": "Notifies Telegram about a successful SELL order execution."
},
{
"parameters": {
"text": "🤖 Trade Bot Info:\n\n⏳ **No Action Taken This Cycle**\nReason: AI decision was 'hold' or risk rules prevented trade.\nSymbol: {{ $json.targetSymbol }}\nAI Decision: {{ $json.decision || 'hold' }}\nAI Confidence: {{ $json.aiResponse.confidence ? $json.aiResponse.confidence.toFixed(2) : 'N/A' }}\nAvailable USDT: {{ $json.availableBalance.toFixed(2) }}\nCurrent {{ $json.baseAsset }} Position: {{ $json.currentPosition.toFixed(4) }}",
"chatId": "={{ $env['TELEGRAM_CHAT_ID'] }}",
"options": {}
},
"name": "Send No Action Telegram Notification",
"type": "n8n-nodes-base.telegram",
"typeVersion": 1,
"position": [1620, 800],
"credentials": {
"telegramApi": {
"environmentVariableName": "TELEGRAM_CREDENTIALS"
}
},
"notes": "Notifies Telegram when the bot decides not to trade in a given cycle."
},
{
"parameters": {
"text": "🤖 Trade Bot **ERROR**!:\n\nAn error occurred during workflow execution.\n\nError Message: {{ $json.error.message }}\nNode: {{ $json.error.node.name }}\nDetails: {{ $json.error.stack }}",
"chatId": "={{ $env['TELEGRAM_CHAT_ID'] }}",
"options": {}
},
"name": "Send Error Telegram Alert",
"type": "n8n-nodes-base.telegram",
"typeVersion": 1,
"position": [1130, 800],
"credentials": {
"telegramApi": {
"environmentVariableName": "TELEGRAM_CREDENTIALS"
}
},
"notes": "Sends an alert to Telegram if any node fails."
},
{
"parameters": {
"function": "const orderResult = $json; // Binance API response for order creation\n\n// --- State & Performance Update Placeholder ---\n// In a real scenario, this node (or a connected database node) would:\n// 1. Record the completed trade details (symbol, side, quantity, price, timestamp, fees).\n// 2. Calculate PnL for closed positions.\n// 3. Update the overall portfolio value.\n// 4. Store this data in an external database.\n\n// For this example, we'll just prepare a simple message.\n\nreturn [\n {\n json: {\n ...$json,\n message: `Trade recorded for ${orderResult.symbol}: ${orderResult.side} ${orderResult.executedQty} @ ${orderResult.cummulativeQuoteQty / orderResult.executedQty}`\n }\n }\n];\n\n// Example of how you might send data to a database service via HTTP Request:\n/*\nasync function execute() {\n const orderResult = $json;\n const dbServiceUrl = $env['DB_SERVICE_URL']; // URL of your external DB API\n\n const tradeData = {\n symbol: orderResult.symbol,\n side: orderResult.side,\n quantity: orderResult.executedQty,\n price: parseFloat(orderResult.cummulativeQuoteQty) / parseFloat(orderResult.executedQty),\n orderId: orderResult.orderId,\n timestamp: Date.now(),\n fees: 'N/A' // Need to fetch fees separately or estimate\n // Add other relevant data like PnL (if closing a position)\n };\n\n // Send data to your external database service\n const response = await this.helpers.httpRequest({\n method: 'POST',\n url: `${dbServiceUrl}/trades`,\n body: tradeData,\n json: true\n });\n\n return [\n {\n json: {\n ...orderResult,\n dbResponse: response,\n message: `Trade recorded and sent to DB service: ${orderResult.symbol} ${orderResult.side}`\n }\n }\n ];\n}\n\nreturn execute();\n*/",
"options": {}
},
"name": "Record Trade & Update Performance (Placeholder)",
"type": "n8n-nodes-base.code",
"typeVersion": 1,
"position": [2440, 520],
"notes": "Placeholder: This node or a connected node should record the trade details in an external database and update performance metrics. Crucial for Telegram monitoring!"
},
{
"parameters": {
"text": "🤖 Trade Bot Performance Update:\n\n📊 **Periodic Performance Snapshot**\n\nSymbol: {{ $json.targetSymbol }}\nAvailable USDT: {{ $json.availableBalance.toFixed(2) }}\nCurrent {{ $json.baseAsset }} Position: {{ $json.currentPosition.toFixed(4) }}\n\n--- Overall Performance (Requires DB) ---\nTotal Trades: XX (Need to read from DB)\nWinning Trades: XX\nLosing Trades: XX\nTotal PnL (USDT): XXX.XX\n\nLast Updated: {{ new Date().toLocaleString() }}",
"chatId": "={{ $env['TELEGRAM_CHAT_ID'] }}",
"options": {}
},
"name": "Send Performance Telegram Update (Placeholder)",
"type": "n8n-nodes-base.telegram",
"typeVersion": 1,
"position": [2440, 800],
"credentials": {
"telegramApi": {
"environmentVariableName": "TELEGRAM_CREDENTIALS"
}
},
"notes": "Placeholder: This node would ideally send periodic performance summaries, which require fetching data from the external database."
},
{
"parameters": {
"function": "// --- Placeholder for advanced data processing ---\n// Calculate Technical Indicators (RSI, MACD, Moving Averages, etc.)\n// Perform pattern recognition on candlestick data\n// Prepare final feature set for the external AI model call\n\nconst candlestickData = $json.json.data;\nconst accountInfo = $json.json.accountInfo;\nconst availableBalance = $json.json.availableBalance;\nconst currentPosition = $json.json.currentPosition;\nconst targetSymbol = $json.json.targetSymbol;\nconst baseAsset = $json.json.baseAsset;\n\n// Get latest price\nconst latestCandle = candlestickData[candlestickData.length - 1];\nconst currentPrice = parseFloat(latestCandle[4]); // Close price of the latest candle\n\n// Example: Calculate a simple Moving Average (requires more data than 100 candles for longer MAs)\n// This requires a proper library or extensive code\n// const closingPrices = candlestickData.map(c => parseFloat(c[4]));\n// const sma20 = calculateSMA(closingPrices, 20); // You'd need to implement calculateSMA function\n\n// Attach processed data for the next node (AI Call)\nreturn [\n {\n json: {\n candlestickData: candlestickData,\n accountInfo: accountInfo,\n availableBalance: availableBalance,\n currentPosition: currentPosition,\n targetSymbol: targetSymbol,\n baseAsset: baseAsset,\n currentPrice: currentPrice\n // Add calculated indicators here\n // sma20: sma20\n }\n }\n];\n\n// Example SMA calculation (needs error handling, etc.)\n/*\nfunction calculateSMA(data, period) {\n if (data.length < period) return null;\n let sum = 0;\n for (let i = data.length - period; i < data.length; i++) {\n sum += data[i];\n }\n return sum / period;\n}\n*/",
"options": {}
},
"name": "Process Data & Add Indicators (Code)",
"type": "n8n-nodes-base.code",
"typeVersion": 1,
"position": [890, 660],
"notes": "Performs technical analysis, calculates indicators, and prepares the data payload for the external AI service."
}
],
"connections": {
"Cron Trigger (Every 5 Min)": [
[
{
"node": "Get Binance Account Info",
"outputIndex": 0
}
]
],
"Get Binance Account Info": [
[
{
"node": "Process Account State",
"outputIndex": 0
}
]
],
"Process Account State": [
[
{
"node": "Get Market Data (Candlesticks)",
"outputIndex": 0
},
{
"node": "Send Performance Telegram Update (Placeholder)",
"outputIndex": 0
}
]
],
"Get Market Data (Candlesticks)": [
[
{
"node": "Process Data & Add Indicators (Code)",
"outputIndex": 0
}
]
],
"Call External AI Service (RL Agent)": [
[
{
"node": "Process AI Response & Risk",
"outputIndex": 0
}
]
],
"Process AI Response & Risk": [
[
{
"node": "If Decision is Buy/Sell",
"outputIndex": 0
},
{
"node": "Send No Action Telegram Notification",
"outputIndex": 0
}
]
],
"If Decision is Buy/Sell": [
[
{
"node": "Send Buy Signal Telegram Alert",
"outputIndex": 0
}
],
[
{
"node": "Send Sell Signal Telegram Alert",
"outputIndex": 0
}
]
],
"Place Buy Order": [
[
{
"node": "Send Buy Order Confirmation Telegram",
"outputIndex": 0
}
]
],
"Place Sell Order": [
[
{
"node": "Send Sell Order Confirmation Telegram",
"outputIndex": 0
}
]
],
"Send Buy Order Confirmation Telegram": [
[
{
"node": "Record Trade & Update Performance (Placeholder)",
"outputIndex": 0
}
]
],
"Send Sell Order Confirmation Telegram": [
[
{
"node": "Record Trade & Update Performance (Placeholder)",
"outputIndex": 0
}
]
],
"Process Data & Add Indicators (Code)": [
[
{
"node": "Call External AI Service (RL Agent)",
"outputIndex": 0
}
]
],
"Send Buy Signal Telegram Alert": [
[
{
"node": "Place Buy Order",
"outputIndex": 0
}
]
],
"Send Sell Signal Telegram Alert": [
[
{
"node": "Place Sell Order",
"outputIndex": 0
}
]
]
}
}
]