
최근 미국 AI 연구소 nof1ai는 주목할 만한 실험을 시작했습니다. 6개의 최고 AI 모델(Claude, DeepSeek, Gemini, GPT-5, Grok, Tongyi Qianwen)이 각각 1만 달러의 상금을 받고 실제 암호화폐 무기한 선물 시장에서 경쟁하는 실험이었습니다. 이는 모의 거래가 아닌 실제 돈으로 진행된 경쟁이었습니다. 결과는 놀라웠습니다. 중국 AI DeepSeek이 꾸준히 선두를 달렸고, GPT-5와 Gemini는 모두 뒤처졌습니다. 이 경쟁의 가장 큰 가치는 팀이 사용된 단서, 데이터 구조, 그리고 의사 결정 프로세스를 오픈소스로 공개하여 AI 기반 양적 거래 연구에 훌륭한 모델을 제공했다는 것입니다.

이 글에서는 이러한 공개 아키텍처를 기반으로 AI 양적 거래 워크플로의 각 노드와 논리를 자세히 분석하여 AI가 실제 시장에서 거래 결정을 내리는 방식을 이해하는 데 도움을 드립니다.
이 AI 양적 거래 시스템은 고전적인 “인지-결정-실행” 3단계 아키텍처를 채택합니다. 전체 워크플로는 여러 핵심 노드로 구성됩니다.

코어 노드 설명:
각 노드의 디자인 논리를 하나씩 분석해 보겠습니다.
타이밍 트리거는 인간의 심장 박동과 비슷하게 전체 워크플로의 시작점으로, 시스템이 주기적으로 작동하도록 합니다.
디자인 고려 사항:
이는 계정의 다양한 핵심 지표를 초기화, 추적, 계산하는 역할을 하는 주요 상태 관리 노드입니다.
// 设置币安模拟交易所API基础地址
api_base = "https://testnet.binancefuture.com"
exchange.SetBase(api_base)
// 初始化检查 - 首次运行时设置基准值
if (_G('invoketime') === null) {
_G('invoketime', 0);
_G('STARTTIME', Date.now());
const initAccount = exchange.GetAccount();
_G('initmoney', initAccount.Equity);
}
// 累计调用次数
const invoketime = _G('invoketime') + 1;
_G('invoketime', invoketime);
// 计算运行时长(分钟)
const duringtime = Math.floor((Date.now() - _G('STARTTIME')) / 60000);
// 获取当前账户信息
const currentAccount = exchange.GetAccount();
const currentAccountValue = currentAccount.Equity;
// 计算总收益率
const initMoney = _G('initmoney');
const totalReturnPercent = ((currentAccountValue - initMoney) / initMoney * 100).toFixed(2);
// 记录收益到系统日志
LogProfit(currentAccountValue - initMoney, "&")
// 返回5个核心指标
return [{
json: {
invoketime: invoketime,
duringtime: duringtime,
totalReturnPercent: totalReturnPercent + '%',
availableCash: currentAccount.Balance.toFixed(2),
currentAccountValue: currentAccountValue.toFixed(2)
}
}];
{
"invoketime": 42, // 系统调用次数
"duringtime": 126, // 运行时长(分钟)
"totalReturnPercent": "3.45%", // 总收益率
"availableCash": "10345.67", // 可用资金
"currentAccountValue": "10345.00" // 账户总价值
}
_G()함수는 사이클 전반에 걸쳐 데이터 지속성을 구현합니다.initmoney이익 계산의 기초로서LogProfit()이 기능은 실시간으로 수익을 시스템 차트로 다시 공급합니다.이는 전체 시스템의 “눈”으로, 다양한 시장 데이터와 기술 지표를 수집, 처리, 계산하는 역할을 합니다.
시장 데이터 수집 노드의 기능은 세 가지 수준으로 나눌 수 있습니다.
// 解析币种列表
const coins = $vars.coinList ?
($vars.coinList.includes(',') ? $vars.coinList.split(',') : [$vars.coinList]) : [];
if (coins.length === 0) {
return {};
}
// 为每个币种获取市场数据
const allCoinsData = {};
for (let i = 0; i < coins.length; i++) {
const coin = coins[i].trim();
try {
allCoinsData[coin] = getMarketDataForCoin(coin);
} catch (e) {
allCoinsData[coin] = { error: e.toString() };
}
}
return { data: allCoinsData };
function getMarketDataForCoin(symbol) {
// 切换到对应币种的永续合约
exchange.SetCurrency(symbol + "_USDT");
exchange.SetContractType("swap");
// 获取3分钟和4小时K线数据
const kline3m = exchange.GetRecords(60 * 3); // 3分钟周期
const kline4h = exchange.GetRecords(60 * 60 * 4); // 4小时周期
// 数据有效性检查
if (!kline3m || kline3m.length < 50 || !kline4h || kline4h.length < 50) {
return { error: "K线数据不足" };
}
// 计算3分钟周期技术指标
const ema20_3m = TA.EMA(kline3m, 20); // 20周期指数移动平均
const macd_3m = TA.MACD(kline3m, 12, 26, 9); // MACD指标
const rsi7_3m = TA.RSI(kline3m, 7); // 7周期RSI
const rsi14_3m = TA.RSI(kline3m, 14); // 14周期RSI
// 计算4小时周期技术指标
const ema20_4h = TA.EMA(kline4h, 20); // 20周期EMA
const ema50_4h = TA.EMA(kline4h, 50); // 50周期EMA
const macd_4h = TA.MACD(kline4h, 12, 26, 9); // MACD指标
const rsi14_4h = TA.RSI(kline4h, 14); // 14周期RSI
const atr3_4h = TA.ATR(kline4h, 3); // 3周期ATR(波动率)
const atr14_4h = TA.ATR(kline4h, 14); // 14周期ATR
// 获取最新K线和最近10根K线
const latest3m = kline3m[kline3m.length - 1];
const latest4h = kline4h[kline4h.length - 1];
const recent10_3m = kline3m.slice(-10);
const recent10_4h = kline4h.slice(-10);
// 计算平均成交量
const volumes4h = recent10_4h.map(k => k.Volume);
const avgVolume4h = volumes4h.reduce((a, b) => a + b, 0) / volumes4h.length;
// 返回结构化数据...
}
듀얼 타임 프레임 전략:
이러한 다중 시간 프레임 분석은 전문적인 양적 거래의 표준 기능으로, AI에 “현미경”과 “망원경” 관점을 모두 제공하는 것과 같습니다.
return {
symbol: symbol,
current_price: latest3m.Close,
current_ema20: ema20_3m[ema20_3m.length - 1],
current_macd: macd_3m[2][macd_3m[2].length - 1],
current_rsi_7: rsi7_3m[rsi7_3m.length - 1],
funding_rate: fundingRate,
intraday_3min: {
mid_prices: recent10_3m.map(k => k.Close),
ema_20_series: recent10_3m.map((k, i) => ema20_3m[ema20_3m.length - 10 + i]),
macd_series: recent10_3m.map((k, i) => macd_3m[2][macd_3m[2].length - 10 + i]),
rsi_7_series: recent10_3m.map((k, i) => rsi7_3m[rsi7_3m.length - 10 + i]),
rsi_14_series: recent10_3m.map((k, i) => rsi14_3m[rsi14_3m.length - 10 + i])
},
longer_term_4hour: {
ema_20: ema20_4h[ema20_4h.length - 1],
ema_50: ema50_4h[ema50_4h.length - 1],
atr_3: atr3_4h[atr3_4h.length - 1],
atr_14: atr14_4h[atr14_4h.length - 1],
current_volume: latest4h.Volume,
average_volume: avgVolume4h,
macd_series: recent10_4h.map((k, i) => macd_4h[2][macd_4h[2].length - 10 + i]),
rsi_14_series: recent10_4h.map((k, i) => rsi14_4h[rsi14_4h.length - 10 + i])
}
};
1. EMA(지수 이동 평균)
2. MACD(이동평균수렴·발산)
3. RSI(상대 강도 지수)
4. ATR(평균 진폭)
위치 데이터 수집 노드는 각 통화의 현재 위치 상태를 추적하고 AI에 완전한 위치 정보를 제공하는 역할을 합니다.
function getAllPositions() {
// 获取当前账户权益
const curequity = exchange.GetAccount().Equity;
// 获取币种列表
const coins = $vars.coinList ?
($vars.coinList.includes(',') ? $vars.coinList.split(',') : [$vars.coinList]) : [];
// 计算每个币种的风险金额 = 账户权益 / 币种数量
const risk_usd = coins.length > 0 ? curequity / coins.length : 0;
// 获取所有实际持仓
const rawPositions = exchange.GetPositions();
// 创建持仓映射表 (币种符号 -> 持仓对象)
const positionMap = {};
if (rawPositions && rawPositions.length > 0) {
for (let pos of rawPositions) {
if (pos.Amount && Math.abs(pos.Amount) > 0) {
// 提取币种符号 (如 BTC_USDT.swap -> BTC)
const coinSymbol = pos.Symbol.replace('_USDT.swap', '')
.replace('.swap', '')
.replace('_USDT', '');
positionMap[coinSymbol] = pos;
}
}
}
// 为每个币种创建position信息
const allPositions = [];
for (let i = 0; i < coins.length; i++) {
const coin = coins[i].trim();
const pos = positionMap[coin];
if (pos) {
// 有持仓的情况 - 构建完整持仓信息
// 获取止盈止损订单ID
const { tpOrderId, slOrderId } = getTPSLOrderIds(pos.Symbol, currentPrice, pos.Type);
// 获取退出计划
const exitPlan = _G(`exit_plan_${pos.Symbol}`) || {
profit_target: null,
stop_loss: null,
invalidation_condition: ""
};
allPositions.push({
symbol: coin,
quantity: Math.abs(pos.Amount), // 持仓数量
entry_price: pos.Price, // 入场价格
current_price: currentPrice, // 当前价格
liquidation_price: /* 强平价格计算 */,
unrealized_pnl: _N(pos.Profit, 2), // 未实现盈亏
leverage: pos.MarginLevel || 1, // 杠杆倍数
exit_plan: exitPlan, // 退出计划
confidence: exitPlan?.confidence || null,
risk_usd: risk_usd, // 风险金额
sl_oid: slOrderId, // 止损订单ID
tp_oid: tpOrderId, // 止盈订单ID
wait_for_fill: false,
entry_oid: pos.Info?.posId || -1,
notional_usd: _N(Math.abs(pos.Amount) * currentPrice, 2)
});
} else {
// 没有持仓的情况 - 所有字段设为null
allPositions.push({
symbol: coin,
quantity: null, // 关键字段:null表示无持仓
entry_price: null,
current_price: null,
liquidation_price: null,
unrealized_pnl: null,
leverage: null,
exit_plan: null,
confidence: null,
risk_usd: risk_usd, // 仍然返回risk_usd用于开仓计算
sl_oid: null,
tp_oid: null,
wait_for_fill: false,
entry_oid: null,
notional_usd: null
});
}
}
return allPositions;
}
const positions = getAllPositions();
return {positions};
수량필드의 핵심 역할:
quantity = null: 포지션이 없어도 AI가 포지션 오픈을 고려할 수 있음quantity ≠ null: 포지션이 있을 경우 AI는 포지션을 유지하거나 닫을 수만 있고 포지션을 늘릴 수는 없습니다.이러한 설계는 “피라미드” 위험을 피하고 각 통화에 대해 활성 포지션이 하나만 존재하도록 보장합니다.
AI 의사결정에 필요한 완전한 맥락으로 시장 및 위치 데이터를 결합합니다.
// 获取输入数据
const inputData = $input.all();
// 第一个输入是市场数据,第二个是持仓数据
const marketData = inputData[0].json.data;
const positions = inputData[1].json;
// 返回整理后的数据
return [{
json: {
marketData: marketData,
positions: positions
}
}];
간단하고 효율적인 데이터 통합을 통해 AI를 위한 통합된 데이터 인터페이스를 제공합니다.
이것이 전체 시스템의 핵심인 AI 의사결정 엔진입니다. 완전한 시장 및 계좌 정보를 수신하여 구체적인 거래 지침을 도출합니다.

AI 에이전트의 의사결정은 두 가지 유형의 프롬프트에 의존합니다.
1. 시스템 메시지:
2. 텍스트 프롬프트:
“고정된 규칙 + 동적 데이터”의 이중 프롬프트 단어 아키텍처를 통해 AI는 안정적인 의사 결정 프레임워크를 갖추고 실시간 시장 상황에 따라 유연하게 대응할 수 있습니다.
시스템 프롬프트는 AI의 행동 규칙과 의사 결정 프레임워크를 정의하는데, 이는 네 가지 핵심 부분으로 나눌 수 있습니다.
## HARD CONSTRAINTS
### Position Limits
- Tradable coins: {{$vars.coinList}}
- Maximum {{$vars.coinList.split(',').length}} concurrent positions
- No pyramiding or adding to existing positions
- Must be flat before re-entering a coin
### Risk Management
- Maximum risk per trade: 5% of account value
- Leverage range: 5x to 40x
- Minimum risk-reward ratio: 2:1
- Every position must have:
- Stop loss (specific price level)
- Profit target (specific price level)
- Invalidation condition (format: "If price closes below/above [PRICE] on a [TIMEFRAME] candle")
디자인 철학:
## DECISION FRAMEWORK
### Identifying Position Status
A coin has an **active position** if `quantity` is NOT null.
A coin has **no position** if `quantity` is null.
### For Coins WITH Active Positions
Check each position in this order:
1. Invalidation condition triggered? → Close immediately
2. Stop loss or profit target hit? → Close
3. Technical setup still valid? → Hold
4. If uncertain → Hold (trust your exit plan)
Available signals: "hold" or "close" ONLY
### For Coins WITHOUT Positions
Only consider if:
- Current active positions < 6
- Available cash > $1000
- You see a high-probability setup
Available signal: "entry" ONLY
논리적 명확성:
{
"BTC": {
"trade_signal_args": {
"coin": "BTC",
"signal": "entry|hold|close",
"profit_target": 115000.0,
"stop_loss": 112000.0,
"invalidation_condition": "If price closes below 112500 on a 3-minute candle",
"leverage": 15,
"confidence": 0.75,
"risk_usd": 624.38,
"justification": "Reason for this decision"
}
}
}
필드 설명:
signal:거래 신호(진입/보류/종료)profit_target:이익실현 가격stop_loss: 손절가invalidation_condition:고장 조건(자연어 설명)leverage:레버리지 비율(5-40)confidence: 이 신호에 대한 AI의 신뢰도(0-1)risk_usd: 당신이 감수할 수 있는 위험의 양justification: 결정 근거(감사 및 디버깅용)## THINKING PROCESS
Before outputting JSON, think through your decisions step by step:
1. Identify position status for each coin
2. Review coins WITH active positions
3. Review coins WITHOUT positions
4. Output final decisions in JSON
이러한 “생각의 사슬”은 AI가 먼저 분석을 한 다음 출력하도록 하여 의사결정의 안정성과 설명 가능성을 향상시킵니다.
원천:사용자 프롬프트 단어는 템플릿 구문을 사용하여 실시간 데이터를 동적으로 주입합니다.
사용자 프롬프트는 최신 시장 상황과 계정 정보를 기반으로 매번 호출될 때마다 동적으로 생성됩니다.
It has been {{ duringtime }} minutes since you started trading.
The current time is {{ $now.toISO() }}
You've been invoked {{ invoketime }} times.
ALL OF THE PRICE OR SIGNAL DATA BELOW IS ORDERED: OLDEST - NEWEST
Timeframes note: Unless stated otherwise in a section title, intraday series
are provided at 3 minute intervals. If a coin uses a different interval, it is
explicitly stated in that coin's section.
**CURRENT MARKET STATE FOR ALL COINS**
{{ JSON.stringify(marketData) }}
**HERE IS YOUR ACCOUNT INFORMATION & PERFORMANCE**
Current Total Return (percent): {{ totalReturnPercent }}
Available Cash: {{ availableCash }}
Current Account Value: {{ currentAccountValue }}
Current live positions & performance:
{{ JSON.stringify(positions) }}
이 디자인을 통해 AI는 다음을 수행할 때마다 전체 결정 컨텍스트를 얻을 수 있습니다.
시간 인식
duringtime분)$now.toISO())invoketime2류)시장 데이터(“시장 데이터 수집” 노드에서)
계정 상태(매개변수 재설정 노드에서)
totalReturnPercent)availableCash)currentAccountValue)직책 세부 정보(“위치 데이터 수집” 노드에서)
┌─────────────────────────────────────────────────────────────┐
│ AI模型调用时刻 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 系统提示词(固定) │
│ ┌────────────────────────────────────────────┐ │
│ │ You are an expert cryptocurrency trader... │ │
│ │ ## HARD CONSTRAINTS │ │
│ │ - Maximum 6 positions │ │
│ │ - Risk per trade: 5% max │ │
│ │ ## DECISION FRAMEWORK │ │
│ │ - For coins WITH positions: hold/close │ │
│ │ - For coins WITHOUT positions: entry │ │
│ │ ## OUTPUT FORMAT │ │
│ │ - JSON with trade_signal_args │ │
│ └────────────────────────────────────────────┘ │
│ ↓ │
│ 用户提示词(动态,每次不同) │
│ ┌────────────────────────────────────────────┐ │
│ │ Running for 126 minutes, invoked 42 times │ │
│ │ Current Total Return: 3.45% │ │
│ │ Available Cash: $10,345.67 │ │
│ │ │ │
│ │ Market Data: │ │
│ │ { │ │
│ │ "BTC": { │ │
│ │ "current_price": 67234.5, │ │
│ │ "current_ema20": 67150.2, │ │
│ │ "current_macd": -141.87, │ │
│ │ "current_rsi_7": 52.93, │ │
│ │ "intraday_3min": {...}, │ │
│ │ "longer_term_4hour": {...} │ │
│ │ }, │ │
│ │ "ETH": {...}, ... │ │
│ │ } │ │
│ │ │ │
│ │ Positions: │ │
│ │ [ │ │
│ │ { │ │
│ │ "symbol": "BTC", │ │
│ │ "quantity": 0.5, │ │
│ │ "entry_price": 66800.0, │ │
│ │ "unrealized_pnl": 217.25, │ │
│ │ "exit_plan": { │ │
│ │ "stop_loss": 66000.0, │ │
│ │ "profit_target": 68500.0 │ │
│ │ } │ │
│ │ }, │ │
│ │ { │ │
│ │ "symbol": "ETH", │ │
│ │ "quantity": null, // 无持仓 │ │
│ │ ... │ │
│ │ } │ │
│ │ ] │ │
│ └────────────────────────────────────────────┘ │
│ ↓ │
│ AI模型处理和推理 │
│ ↓ │
│ AI输出(JSON格式) │
│ ┌────────────────────────────────────────────┐ │
│ │ { │ │
│ │ "BTC": { │ │
│ │ "trade_signal_args": { │ │
│ │ "signal": "hold", │ │
│ │ "justification": "Position valid..." │ │
│ │ } │ │
│ │ }, │ │
│ │ "ETH": { │ │
│ │ "trade_signal_args": { │ │
│ │ "signal": "entry", │ │
│ │ "profit_target": 2800.0, │ │
│ │ "stop_loss": 2600.0, │ │
│ │ "leverage": 15, │ │
│ │ "risk_usd": 833.33, │ │
│ │ "justification": "Bullish setup..." │ │
│ │ } │ │
│ │ } │ │
│ │ } │ │
│ └────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
↓
传递给"交易执行"节点
이 이중 신호 단어 구조의 장점은 다음과 같습니다.
이는 워크플로의 “손”으로, AI의 결정을 실제 거래소 주문으로 변환하고 수익 실현 및 손실 정지 조건을 지속적으로 모니터링하는 역할을 합니다.
거래 실행 노드는 5개의 기능 모듈로 구분됩니다.
// ========== 工具函数 ==========
function parseAIOutput(output) {
try {
// 清理输出中的代码块标记
const cleaned = output.replace(/```[a-z]*\n?/gi, '').trim();
const start = cleaned.indexOf('{');
const end = cleaned.lastIndexOf('}');
return JSON.parse(cleaned.substring(start, end + 1));
} catch (e) {
return {};
}
}
// 主逻辑
const signals = parseAIOutput($input.first().json.output);
Log(signals)
예외 처리:
// 获取交易对精度信息
function getPrecision(coin) {
try {
const symbol = coin + '_USDT.swap';
const markets = exchange.GetMarkets();
if (markets && markets[symbol]) {
return {
price: markets[symbol].PricePrecision || 0,
amount: markets[symbol].AmountPrecision || 0,
minQty: markets[symbol].MinQty || 5
};
}
return { price: 0, amount: 0, minQty: 5 };
} catch (e) {
Log(`⚠️ 获取${coin}精度失败,使用默认值`);
return { price: 0, amount: 0, minQty: 5 };
}
}
// 计算仓位大小
function calculateQuantity(entryPrice, stopLoss, riskUsd, leverage, precision) {
const riskPerContract = Math.abs(entryPrice - stopLoss);
if (riskPerContract <= 0) return 0;
// 基于风险金额计算数量
const quantity = riskUsd / riskPerContract;
// 限制最大仓位 = (账户余额 × 杠杆 / 6) / 入场价格
const maxQuantity = (exchange.GetAccount().Balance * leverage / 6) / entryPrice;
let finalQuantity = Math.min(quantity, maxQuantity);
// 应用精度和最小数量限制
if (precision) {
finalQuantity = _N(finalQuantity, precision.amount);
if (finalQuantity < precision.minQty) {
Log(`⚠️ 计算数量 ${finalQuantity} 小于最小下单量 ${precision.minQty}`);
return 0;
}
}
return finalQuantity;
}
위치 계산 공식:
风险距离 = |入场价格 - 止损价格|
仓位大小 = 风险金额 ÷ 风险距离
最大仓位 = (账户余额 × 杠杆 ÷ 6) ÷ 入场价格
最终仓位 = min(仓位大小, 最大仓位)
이 계산은 다음을 보장합니다.
function executeEntry(coin, args) {
exchange.SetCurrency(coin + '_USDT');
exchange.SetContractType("swap");
const ticker = exchange.GetTicker();
if (!ticker) return;
const currentPrice = ticker.Last;
if (!validateEntry(coin, currentPrice, args.profit_target, args.stop_loss)) return;
const leverage = args.leverage || 10;
exchange.SetMarginLevel(leverage);
precision = getPrecision(coin);
quantity = calculateQuantity(currentPrice, args.stop_loss, args.risk_usd, leverage, precision);
if (quantity <= 0) {
Log(`⚠️ ${coin}:计算数量无效,跳过开仓`);
return;
}
const isLong = args.profit_target > args.stop_loss;
exchange.SetDirection(isLong ? "buy" : "sell");
const orderId = isLong ? exchange.Buy(-1, quantity) : exchange.Sell(-1, quantity);
if (orderId) {
Sleep(1000);
Log(`✅ ${coin}:开${isLong ? '多' : '空'} 数量=${quantity} 杠杆=${leverage}x 精度=${precision.amount}`);
} else {
Log(`❌ ${coin}:开仓失败`, precision.amount);
}
}
function executeClose(coin) {
exchange.SetCurrency(coin + '_USDT');
exchange.SetContractType("swap");
// 取消所有挂单
const orders = exchange.GetOrders();
orders?.forEach(o => exchange.CancelOrder(o.Id));
// 获取持仓信息
const pos = exchange.GetPositions().find(p =>
p.Symbol.includes(coin) && Math.abs(p.Amount) > 0
);
if (!pos) return;
const isLong = pos.Type === PD_LONG || pos.Type === 0;
const precision = getPrecision(coin);
// 对平仓数量应用精度
const closeAmount = _N(Math.abs(pos.Amount), precision.amount);
exchange.SetDirection(isLong ? "closebuy" : "closesell");
const orderId = isLong ?
exchange.Sell(-1, closeAmount) :
exchange.Buy(-1, closeAmount);
if (orderId) {
Log(`✅ ${coin}:平${isLong ? '多' : '空'}成功,数量=${closeAmount}`);
_G(`exit_plan_${coin}_USDT.swap`, null);
}
}
function monitorPosition(coin) {
exchange.SetCurrency(coin + '_USDT');
exchange.SetContractType("swap");
const pos = exchange.GetPositions().find(p =>
p.Symbol.includes(coin) && Math.abs(p.Amount) > 0
);
if (!pos) return;
const ticker = exchange.GetTicker();
if (!ticker) return;
const isLong = pos.Type === PD_LONG || pos.Type === 0;
const currentPrice = ticker.Last;
// 计算盈亏比例
const pnl = (currentPrice - pos.Price) * (isLong ? 1 : -1) / pos.Price;
// 获取退出计划
const exitPlan = _G(`exit_plan_${coin}_USDT.swap`);
if (!exitPlan?.profit_target || !exitPlan?.stop_loss) {
// 如果没有设置退出计划,使用默认值
if (pnl >= 0.03) return closePosition(coin, pos, isLong, "止盈", pnl);
if (pnl <= -0.01) return closePosition(coin, pos, isLong, "止损", pnl);
return;
}
// 检查止盈条件
const shouldTP = isLong ?
currentPrice >= exitPlan.profit_target :
currentPrice <= exitPlan.profit_target;
// 检查止损条件
const shouldSL = isLong ?
currentPrice <= exitPlan.stop_loss :
currentPrice >= exitPlan.stop_loss;
if (shouldTP) return closePosition(coin, pos, isLong, "止盈", pnl);
if (shouldSL) return closePosition(coin, pos, isLong, "止损", pnl);
}
function closePosition(coin, pos, isLong, reason, pnl) {
const precision = getPrecision(coin);
const closeAmount = _N(Math.abs(pos.Amount), precision.amount);
exchange.SetDirection(isLong ? "closebuy" : "closesell");
isLong ? exchange.Sell(-1, closeAmount) : exchange.Buy(-1, closeAmount);
Log(`${reason === '止盈' ? '✅' : '❌'} ${coin} ${reason} ${(pnl*100).toFixed(2)}%`);
_G(`exit_plan_${coin}_USDT.swap`, null);
}
AI 트레이딩 작업 로직에 대한 이해를 돕기 위해 AI 트레이딩 신호 분석 및 포지션 현황을 시각화합니다.

이 시스템은 3분 주기와 4시간 주기를 모두 사용합니다. 이는 단순한 데이터 중복성이 아닙니다.
사례 시나리오:
이중 사이클 조정:
单笔最大风险 = 账户价值 ÷ 币种数量
最多6个持仓 = 理论最大总风险30%
实际最大风险 < 30%(不会同时触发6个止损)
止损距离 = |入场价 - 止损价| / 入场价
典型设置:2-5%
结合杠杆:10x杠杆下,5%价格波动 = 50%本金波动
示例:"如果价格在3分钟K线上收盘低于$66500"
作用:即使止损没触发,技术形态破坏也要离场
JSON 형식이 필요한 이유는 무엇입니까?
필드의 일관성을 강화하는 이유는 무엇입니까?
긴급 상황을 처리할 수 없음
고정 사이클의 한계
리버리지 위험
AI 모델의 안정성
뉴스 감성 분석 소개
트리거 주파수를 동적으로 조정합니다
다중 모델 투표 메커니즘
백테스팅 검증 추가
이 AI 양적 거래 시스템은 대규모 언어 모델을 실제 금융 거래 시나리오에 적용하는 방법을 보여줍니다. 핵심 장점은 다음과 같습니다.
주요 내용:
이 자세한 기술적 분석이 AI 양적 거래의 작동 논리를 이해하고, 실제 업무에서 더욱 정보에 입각한 결정을 내리는 데 도움이 되기를 바랍니다.
완전한 소스 코드와 실시간 기록:
위험 경고: