Vincent Trading Engine - Strategy-Driven Automated Trading
Use this skill to create and manage automated trading strategies for Polymarket prediction markets and HyperLiquid perpetuals/spot. The Trading Engine combines driver-based monitoring (web search, Twitter, newswire, price feeds) with a signal pipeline and LLM-powered decision-making to automatically trade based on your thesis. It also includes standalone stop-loss, take-profit, and trailing stop rules that work without the LLM.
All commands use the @vincentai/cli package.
How It Works
The Trading Engine is a unified system with two modes:
- 1. LLM-Powered Strategies — Create a versioned strategy with a structured thesis, weighted drivers (web search keywords, Twitter accounts, newswire topics, price triggers), and an escalation policy. When drivers detect new information, signals are scored and batched. When the escalation threshold is met, an LLM (Claude via OpenRouter) evaluates the signals against your thesis and decides whether to trade, update the thesis, set protective orders, or alert you.
- Standalone Trade Rules — Set stop-loss, take-profit, and trailing stop rules on positions. These execute automatically when price conditions are met — no LLM involved.
Architecture:
- - Integrated into the Vincent backend (no separate service to run)
- Strategy endpoints under INLINECODE1
- Trade rule endpoints under INLINECODE2
- HyperLiquid rules use
venue: "hyperliquid" and route through the HL adapter - Uses the same API key as the Polymarket or HyperLiquid skill (depending on venue)
- All trades go through Vincent's policy-enforced pipeline
- LLM costs are metered and deducted from the user's credit balance
- Every LLM invocation is recorded with full audit trail (tokens, cost, actions, duration)
Security Model
- - LLM cannot bypass policies — all trades go through the venue's policy-enforced skill (
polymarketSkill.placeBet() or hyperliquidSkill.trade()) which enforces spending limits, approval thresholds, and allowlists - Backend-side LLM key — the OpenRouter API key never leaves the server. Agents and users cannot invoke the LLM directly
- Credit gating — no LLM invocation without sufficient credit balance
- Tool constraints — the LLM's available tools are controlled by the strategy's
config.tools settings. If canTrade: false, the trade tool is not provided - Rate limiting — max concurrent LLM invocations is capped to prevent runaway costs
- Audit trail — every invocation is recorded with full prompt, response, actions, cost, and duration
- No private keys — the Trading Engine uses the Vincent API for all trades. Private keys stay on Vincent's servers
Part 1: LLM-Powered Strategies
Core Concepts
- - Instrument: A tradeable asset on a venue. Defined by
id, type (stock, perp, swap, binary, option), venue, and optional constraints (leverage, margin, liquidity, fees). - Thesis: Your directional view —
estimate (target price/value), direction (long/short/neutral), confidence (0–1), and reasoning. - Driver: A named information source that feeds the signal pipeline. Each driver has a
weight, direction (bullish/bearish/contextual), and monitoring config (entities, keywords, embedding anchor, sources, polling interval). - Escalation Policy: Controls when the LLM is woken up.
signalScoreThreshold (minimum score to batch), highConfidenceThreshold (score that triggers immediate wake), maxWakeFrequency (e.g. "1 per 15m"), batchWindow (e.g. "5m"). - Trade Rules: Entry rules (min edge, order type), exit rules (thesis invalidation triggers), auto-actions (stop-loss, take-profit, trailing stop, price delta triggers), and sizing rules (method, max position, portfolio %, max trades/day).
Signal Pipeline
Strategies process information through a 6-layer pipeline:
- 1. Ingest — Raw data from driver sources (web search, Twitter, newswire, price feeds, RSS, Reddit, on-chain, filings, options flow)
- Filter — Deduplication and relevance filtering. Drops signals already seen or below quality threshold
- Score — Each signal is scored (0–1) based on driver weight, embedding similarity to the anchor, and entity/keyword matches
- Escalate — Scored signals are batched according to the escalation policy. Low-score signals accumulate in a batch window; high-confidence signals trigger immediate LLM wake
- LLM — The LLM evaluates batched signals against the current thesis. It can update the thesis, issue trade decisions, update driver states, or take no action
- Execute — Trade decisions pass through policy enforcement and are routed to the appropriate venue adapter for execution
Strategy Lifecycle
Strategies follow a versioned lifecycle: DRAFT → ACTIVE → PAUSED → INLINECODE25
- - DRAFT: Can be edited. Not yet monitoring or invoking the LLM.
- ACTIVE: Drivers are running. New signals trigger the pipeline.
- PAUSED: Monitoring is stopped. Can be resumed.
- ARCHIVED: Permanently stopped. Cannot be reactivated.
To iterate on a strategy, duplicate it as a new version (creates a new DRAFT with incremented version number and the same config).
Create a Strategy
CODEBLOCK0
Parameters:
- -
--name: Strategy name - INLINECODE27 : Full strategy config JSON (see Core Concepts above for structure)
- INLINECODE28 : Optional DATA_SOURCES secret ID for driver monitoring API calls
- INLINECODE29 : Polling interval in minutes for driver monitoring (default: 15)
List Strategies
CODEBLOCK1
Get Strategy Details
CODEBLOCK2
Update a Strategy
Update a DRAFT strategy. Pass only the fields you want to change — config is a partial object.
CODEBLOCK3
Parameters:
- -
--strategy-id: Strategy ID (required) - INLINECODE31 : New strategy name
- INLINECODE32 : Partial strategy config JSON — only include fields to update
- INLINECODE33 : DATA_SOURCES secret ID
- INLINECODE34 : New polling interval in minutes
Activate a Strategy
Starts driver monitoring and signal pipeline processing. Strategy must be in DRAFT status.
CODEBLOCK4
Pause a Strategy
Stops monitoring. Strategy must be ACTIVE.
CODEBLOCK5
Resume a Strategy
Resumes monitoring. Strategy must be PAUSED.
CODEBLOCK6
Archive a Strategy
Permanently stops a strategy. Cannot be undone.
CODEBLOCK7
Duplicate a Strategy (New Version)
Creates a new DRAFT with the same config, incremented version number, and a link to the parent version.
CODEBLOCK8
View Version History
See all versions of a strategy lineage.
CODEBLOCK9
View LLM Invocation History
See the LLM decision log for a strategy — what data triggered it, what the LLM decided, what actions were taken, and the cost.
CODEBLOCK10
View Cost Summary
See aggregate LLM costs for all strategies under a secret.
CODEBLOCK11
View Performance Metrics
See performance metrics for a strategy: P&L, win rate, trade count, and per-instrument breakdown.
CODEBLOCK12
Driver Configuration
Web Search Drivers
Add a driver with "sources": ["web_search"]. The engine periodically searches Brave for the driver's keywords and triggers the signal pipeline when new results appear.
CODEBLOCK13
Each keyword is searched independently. Results are deduplicated — the same URLs won't trigger the pipeline twice.
Twitter Drivers
Add a driver with "sources": ["twitter"]. The engine periodically checks the specified entities for new tweets.
CODEBLOCK14
Tweets are deduplicated by tweet ID — only genuinely new tweets trigger the pipeline.
Newswire Drivers (Finnhub)
Add a driver with "sources": ["newswire"]. The engine periodically polls Finnhub's market news API and triggers the pipeline when new headlines matching your keywords appear.
CODEBLOCK15
Headlines and summaries are matched case-insensitively. Articles are deduplicated by headline hash with a sliding window.
Note: Requires a FINNHUB_API_KEY env var on the server. Finnhub's free tier allows 60 API calls/min. No per-call credit deduction.
Price Triggers
Price triggers are evaluated in real-time via the Polymarket WebSocket feed. When a price condition is met, the signal pipeline is invoked with the price data.
Trigger types:
- -
ABOVE — triggers when price exceeds a threshold - INLINECODE40 — triggers when price drops below a threshold
- INLINECODE41 — triggers on a percentage change from reference price
Price triggers are one-shot: once fired, they're marked as consumed. The LLM can create new triggers if needed.
Thesis Best Practices
The thesis is your structured directional view. Good theses include:
- 1. A clear estimate: Target price or value the market should reach
- A confidence level: Start at 0.5–0.7 and let the LLM adjust as new data arrives
- Specific reasoning: "ETF inflows accelerating, halving supply shock imminent" is better than "BTC will go up"
- Explicit invalidation conditions: Use
tradeRules.exit.thesisInvalidation to define what would break your thesis
LLM Available Tools
When the LLM is invoked, it can use these tools (depending on strategy config):
| Tool | Description | Requires |
|---|
| INLINECODE43 | Buy or sell a position | INLINECODE44 in trade rules |
| INLINECODE45 |
Set a stop-loss rule on a position |
canSetRules: true in trade rules |
|
set_take_profit | Set a take-profit rule |
canSetRules: true in trade rules |
|
set_trailing_stop | Set a trailing stop |
canSetRules: true in trade rules |
|
alert_user | Send an alert without trading | Always available |
|
no_action | Do nothing (with reasoning) | Always available |
Cost Tracking
Every LLM invocation is metered:
- - Token costs: Input and output tokens are priced per the model's rate
- Deducted from credit balance: Same pool as data source credits (
dataSourceCreditUsd) - Pre-flight check: If insufficient credit, the invocation is skipped and logged
- Data source costs: Brave Search (~$0.005/call) and Twitter (~$0.005-$0.01/call) are also metered. Finnhub newswire calls are free (no credit deduction)
Typical LLM invocation cost: $0.05–$0.30 depending on context size.
Part 2: Standalone Trade Rules
Trade rules execute automatically when price conditions are met — no LLM involved. These are stop-loss, take-profit, and trailing stop rules that protect your positions.
Check Worker Status
CODEBLOCK16
Create a Stop-Loss Rule
Automatically sell a position if price drops below a threshold:
CODEBLOCK17
Parameters:
- -
--venue: polymarket (default) or INLINECODE56 - INLINECODE57 : Polymarket condition ID, or coin name for HyperLiquid (e.g.
BTC, ETH) - INLINECODE60 : Polymarket outcome token ID, or coin name for HyperLiquid
- INLINECODE61 :
STOP_LOSS (sells if price <= trigger), TAKE_PROFIT (sells if price >= trigger), or INLINECODE64 - INLINECODE65 : Price threshold — 0 to 1 for Polymarket, absolute USD price for HyperLiquid
Create a Take-Profit Rule
Automatically sell a position if price rises above a threshold:
CODEBLOCK18
Create a Trailing Stop Rule
A trailing stop moves the stop price up as the price rises:
CODEBLOCK19
Trailing stop behavior:
- -
--trailing-percent is percent points (e.g. 5 = 5%) - Computes INLINECODE68
- If
candidateStop > current triggerPrice, updates INLINECODE71 - INLINECODE72 never moves down
- Rule triggers when INLINECODE73
List Rules
CODEBLOCK20
Update a Rule
CODEBLOCK21
Cancel a Rule
CODEBLOCK22
View Monitored Positions
CODEBLOCK23
View Event Log
CODEBLOCK24
Event types:
- -
RULE_CREATED — Rule was created - INLINECODE75 — Trailing stop moved triggerPrice upward
- INLINECODE76 — Worker checked the rule against current price
- INLINECODE77 — Trigger condition was met
- INLINECODE78 — Trade requires human approval, rule paused
- INLINECODE79 — Trade executed successfully
- INLINECODE80 — Trade execution failed
- INLINECODE81 — Rule was manually canceled
Rule Statuses
- -
ACTIVE — Rule is live and being monitored - INLINECODE83 — Condition was met, trade executed
- INLINECODE84 — Trade requires human approval; rule paused
- INLINECODE85 — Manually canceled before triggering
- INLINECODE86 — Triggered but trade execution failed
Complete Workflow: Strategy + Trade Rules
Polymarket Workflow
Step 1: Place a bet with the Polymarket skill
CODEBLOCK25
Step 2: Create a strategy to monitor the thesis
CODEBLOCK26
Step 3: Set a standalone stop-loss as immediate protection
CODEBLOCK27
Step 4: Activate the strategy
CODEBLOCK28
Step 5: Monitor activity
CODEBLOCK29
HyperLiquid Workflow
Step 1: Open a perp position with the HyperLiquid skill
CODEBLOCK30
Step 2: Set a stop-loss rule for the position
CODEBLOCK31
Step 3: Set a take-profit rule
CODEBLOCK32
Step 4: Create a strategy to monitor your thesis
CODEBLOCK33
Step 5: Activate and monitor
CODEBLOCK34
Background Workers
The Trading Engine runs two independent background workers:
- 1. Strategy Engine Worker — Ticks every 30s, checks which strategy drivers are due, fetches new data, scores signals, and invokes the LLM when the escalation threshold is met. Hooks into venue WebSocket feeds (Polymarket and HyperLiquid) for real-time price trigger evaluation.
- Trade Rule Worker — Monitors prices in real-time via WebSocket (with polling fallback), evaluates stop-loss/take-profit/trailing stop rules, executes trades when conditions are met. Supports both Polymarket and HyperLiquid venues.
Circuit Breaker: Both workers use a circuit breaker pattern. If a venue API fails 5+ consecutive times, the worker pauses and resumes after a cooldown. Check status with:
CODEBLOCK35
Best Practices
- 1. Start with
confidence: 0.5 and let the LLM adjust — avoid overconfidence in the initial thesis - Weight drivers by importance — a driver with
weight: 3.0 has 3x the signal score contribution of INLINECODE89 - Use
edgeScaled sizing for adaptive position sizes based on thesis confidence and edge - Set
maxPortfolioPct to limit exposure — even high-confidence strategies shouldn't risk the entire portfolio - Set both stop-loss and take-profit on positions for protection (via
autoActions in the config or standalone rules) - Use
thesisInvalidation exit rules to define explicit conditions that should trigger position exits - Monitor invocation costs — check the costs command regularly
- Iterate with versions — duplicate a strategy to tweak the config without losing the original
- Don't set triggers too close to current price — market noise can trigger prematurely
Example User Prompts
When a user says:
- - "Create a strategy to monitor AI tokens" → Create strategy with web search + Twitter drivers
- "Set a stop-loss at 40 cents" → Create STOPLOSS rule
- "What has my strategy been doing?" → Show invocations for the strategy
- "How is my strategy performing?" → Show performance metrics
- "How much has the trading engine cost me?" → Show cost summary
- "Pause my strategy" → Pause the strategy
- "Make a new version with a different thesis" → Duplicate, then update the draft
- "Set a 5% trailing stop" → Create TRAILINGSTOP rule
Output Format
Strategy creation:
CODEBLOCK36
Rule creation:
CODEBLOCK37
LLM invocation log entries:
CODEBLOCK38
Error Handling
| Error | Cause | Resolution |
|---|
| INLINECODE94 | Invalid or missing API key | Check that the key-id is correct; re-link if needed |
| INLINECODE95 |
Trade blocked by server-side policy | User must adjust policies at heyvincent.ai |
|
402 Insufficient Credit | Not enough credit for LLM invocation | User must add credit at heyvincent.ai |
|
INVALID_STATUS_TRANSITION | Strategy can't transition to requested state | Check current status (e.g., only DRAFT can activate) |
|
CIRCUIT_BREAKER_OPEN | Polymarket API failures triggered circuit breaker | Wait for cooldown; check status command |
|
429 Rate Limited | Too many requests or concurrent LLM invocations | Wait and retry with backoff |
|
Key not found | API key was revoked or never created | Re-link with a new token from the wallet owner |
Important Notes
- - Authorization: All endpoints require the API key for the relevant venue (Polymarket or HyperLiquid wallet key)
- Local only: The API listens on
localhost:19000 — only accessible from the same VPS - No private keys: All trades use the Vincent API — your private key stays secure on Vincent's servers
- Policy enforcement: All trades (both LLM and standalone rules) go through Vincent's policy checks
- Idempotency: Rules only trigger once. LLM invocations are deduplicated by driver state.
Vincent 交易引擎 - 策略驱动的自动化交易
使用此技能为 Polymarket 预测市场和 HyperLiquid 永续合约/现货创建和管理自动化交易策略。交易引擎结合了驱动源监控(网络搜索、Twitter、新闻通讯社、价格数据源)与信号管道及 LLM 驱动的决策,基于您的交易论点自动执行交易。它还包含独立的止损、止盈和追踪止损规则,无需 LLM 参与。
所有命令均使用 @vincentai/cli 包。
工作原理
交易引擎是一个统一系统,包含两种模式:
- 1. LLM 驱动策略 — 创建带版本号的策略,包含结构化的交易论点、加权驱动源(网络搜索关键词、Twitter 账户、新闻通讯社话题、价格触发器)和升级策略。当驱动源检测到新信息时,信号会被评分并分批处理。当达到升级阈值时,LLM(通过 OpenRouter 调用 Claude)会根据您的交易论点评估信号,并决定是否交易、更新论点、设置保护订单或向您发出警报。
- 独立交易规则 — 在持仓上设置止损、止盈和追踪止损规则。当价格条件满足时自动执行 — 无需 LLM 参与。
架构:
- - 集成在 Vincent 后端中(无需单独运行服务)
- 策略端点位于 /api/skills/polymarket/strategies/...
- 交易规则端点位于 /api/skills/polymarket/rules/...
- HyperLiquid 规则使用 venue: hyperliquid 并通过 HL 适配器路由
- 使用与 Polymarket 或 HyperLiquid 技能相同的 API 密钥(取决于交易场所)
- 所有交易均通过 Vincent 的策略执行管道
- LLM 成本按量计费并从用户信用余额中扣除
- 每次 LLM 调用均记录完整的审计追踪(代币数、成本、操作、持续时间)
安全模型
- - LLM 无法绕过策略 — 所有交易均通过交易场所的策略执行技能(polymarketSkill.placeBet() 或 hyperliquidSkill.trade()),该技能强制执行支出限额、审批阈值和白名单
- 后端侧 LLM 密钥 — OpenRouter API 密钥永远不会离开服务器。代理和用户无法直接调用 LLM
- 信用门槛 — 没有足够的信用余额则无法进行 LLM 调用
- 工具约束 — LLM 可用的工具由策略的 config.tools 设置控制。如果 canTrade: false,则不提供交易工具
- 速率限制 — 最大并发 LLM 调用次数有上限,以防止成本失控
- 审计追踪 — 每次调用均记录完整的提示、响应、操作、成本和持续时间
- 无私钥 — 交易引擎使用 Vincent API 进行所有交易。私钥保留在 Vincent 的服务器上
第一部分:LLM 驱动策略
核心概念
- - 交易标的:交易场所上的可交易资产。由 id、type(股票、永续合约、掉期、二元期权、期权)、venue 和可选约束(杠杆、保证金、流动性、费用)定义。
- 交易论点:您的方向性观点 — estimate(目标价格/价值)、direction(多头/空头/中性)、confidence(0–1)和 reasoning(推理)。
- 驱动源:为信号管道提供信息的命名数据源。每个驱动源都有 weight(权重)、direction(看涨/看跌/情境性)和 monitoring(监控)配置(实体、关键词、嵌入锚点、数据源、轮询间隔)。
- 升级策略:控制何时唤醒 LLM。signalScoreThreshold(触发分批的最低分数)、highConfidenceThreshold(触发立即唤醒的分数)、maxWakeFrequency(例如每15分钟1次)、batchWindow(例如5分钟)。
- 交易规则:入场规则(最小优势、订单类型)、出场规则(交易论点失效触发器)、自动操作(止损、止盈、追踪止损、价格变动触发器)和仓位规模规则(方法、最大仓位、投资组合百分比、每日最大交易次数)。
信号管道
策略通过 6 层管道处理信息:
- 1. 摄取 — 来自驱动源(网络搜索、Twitter、新闻通讯社、价格数据源、RSS、Reddit、链上数据、文件、期权流)的原始数据
- 过滤 — 去重和相关性过滤。丢弃已见过的信号或低于质量阈值的信号
- 评分 — 每个信号根据驱动源权重、与锚点的嵌入相似度以及实体/关键词匹配进行评分(0–1)
- 升级 — 根据升级策略对评分信号进行分批处理。低分信号在批处理窗口内累积;高置信度信号触发立即唤醒 LLM
- LLM — LLM 根据当前交易论点评估分批信号。它可以更新交易论点、发出交易决策、更新驱动源状态或不采取任何行动
- 执行 — 交易决策通过策略执行并路由到相应的交易场所适配器执行
策略生命周期
策略遵循版本化生命周期:草稿 → 活跃 → 暂停 → 归档
- - 草稿:可编辑。尚未开始监控或调用 LLM。
- 活跃:驱动源正在运行。新信号触发管道。
- 暂停:监控已停止。可恢复。
- 归档:永久停止。无法重新激活。
要迭代策略,请将其复制为新版本(创建新的草稿,版本号递增,配置相同)。
创建策略
bash
npx @vincentai/cli@latest trading-engine create-strategy \
--key-id <密钥ID> \
--name BTC 动量 \
--config {
instruments: [
{ id: btc-usd-perp, type: perp, venue: polymarket },
{ id: BTC, type: perp, venue: hyperliquid }
],
thesis: {
estimate: 105000,
direction: long,
confidence: 0.7,
reasoning: ETF 资金流入加速,减半供应冲击即将到来
},
drivers: [
{
name: ETF 流量监控器,
weight: 2.0,
direction: bullish,
monitoring: {
entities: [贝莱德, 富达],
keywords: [比特币 ETF, BTC 流入],
embeddingAnchor: 比特币 ETF 机构资金流入,
sources: [web_search, newswire]
}
},
{
name: 加密 Twitter,
weight: 1.0,
direction: contextual,
monitoring: {
entities: [@BitcoinMagazine, @saborskycnbc],
keywords: [比特币, BTC],
sources: [twitter]
}
}
],
escalation: {
signalScoreThreshold: 0.3,
highConfidenceThreshold: 0.8,
maxWakeFrequency: 1 per 15m,
batchWindow: 5m
},
tradeRules: {
entry: { minEdge: 0.05, orderType: limit, limitOffset: 0.01 },
autoActions: { stopLoss: -0.10, takeProfit: 0.25, trailingStop: -0.05 },
exit: { thesisInvalidation: [ETF 流出超过 5 亿美元/周] },
sizing: {
method: edgeScaled,
maxPosition: 500,
maxPortfolioPct: 20,
maxTradesPerDay: 5,
minTimeBetweenTrades: 30m
}
},
notifications: {
onTrade: true,
onThesisChange: true,
channel: none
}
}
参数:
- - --name:策略名称
- --config:完整策略配置 JSON(结构见上方核心概念)
- --data-source-secret-id:可选,驱动源监控 API 调用的 DATA_SOURCES 密钥 ID
- --poll-interval:驱动源监控的轮询间隔(分钟)(默认:15)
列出策略
bash
npx @vincentai/cli@latest trading-engine list-strategies --key-id <密钥ID>
获取策略详情
bash
npx @vincentai/cli@latest trading-engine get-strategy --key-id <密钥ID> --strategy-id <策略ID>
更新策略
更新草稿策略。仅传入您想要更改的字段 — config 是部分对象。
bash
npx @vincentai/cli