Vincent - Trading Engine
by @glitch003
Strategy-driven automated trading for Polymarket and HyperLiquid. Use this skill when users want to create trading strategies, set stop-loss/take-profit/trai...
clawhub install vincent-trading-engineπ About This Skill
name: Vincent - Trading Engine for agents description: | Strategy-driven automated trading for Polymarket and HyperLiquid. Use this skill when users want to create trading strategies, set stop-loss/take-profit/trailing stop rules, or manage automated trading. Triggers on "trading strategy", "stop loss", "take profit", "trailing stop", "automated trading", "trading engine", "trade rules", "strategy monitor". allowed-tools: Read, Write, Bash(npx:@vincentai/cli*) version: 1.0.0 author: HeyVincent
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. 2. 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:
/api/skills/polymarket/strategies/.../api/skills/polymarket/rules/...venue: "hyperliquid" and route through the HL adapterSecurity Model
polymarketSkill.placeBet() or hyperliquidSkill.trade()) which enforces spending limits, approval thresholds, and allowlistsconfig.tools settings. If canTrade: false, the trade tool is not providedPart 1: LLM-Powered Strategies
Core Concepts
id, type (stock, perp, swap, binary, option), venue, and optional constraints (leverage, margin, liquidity, fees).estimate (target price/value), direction (long/short/neutral), confidence (0β1), and reasoning.weight, direction (bullish/bearish/contextual), and monitoring config (entities, keywords, embedding anchor, sources, polling interval).signalScoreThreshold (minimum score to batch), highConfidenceThreshold (score that triggers immediate wake), maxWakeFrequency (e.g. "1 per 15m"), batchWindow (e.g. "5m").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) 2. Filter β Deduplication and relevance filtering. Drops signals already seen or below quality threshold 3. Score β Each signal is scored (0β1) based on driver weight, embedding similarity to the anchor, and entity/keyword matches 4. 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 5. 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 6. 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 β ARCHIVED
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
npx @vincentai/cli@latest trading-engine create-strategy \
--key-id \
--name "BTC Momentum" \
--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 inflows accelerating, halving supply shock imminent"
},
"drivers": [
{
"name": "ETF Flow Monitor",
"weight": 2.0,
"direction": "bullish",
"monitoring": {
"entities": ["BlackRock", "Fidelity"],
"keywords": ["bitcoin ETF", "BTC inflow"],
"embeddingAnchor": "Bitcoin ETF institutional inflows",
"sources": ["web_search", "newswire"]
}
},
{
"name": "Crypto Twitter",
"weight": 1.0,
"direction": "contextual",
"monitoring": {
"entities": ["@BitcoinMagazine", "@saborskycnbc"],
"keywords": ["bitcoin", "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 outflows exceed $500M/week"] },
"sizing": {
"method": "edgeScaled",
"maxPosition": 500,
"maxPortfolioPct": 20,
"maxTradesPerDay": 5,
"minTimeBetweenTrades": "30m"
}
},
"notifications": {
"onTrade": true,
"onThesisChange": true,
"channel": "none"
}
}'
Parameters:
--name: Strategy name--config: Full strategy config JSON (see Core Concepts above for structure)--data-source-secret-id: Optional DATA_SOURCES secret ID for driver monitoring API calls--poll-interval: Polling interval in minutes for driver monitoring (default: 15)List Strategies
npx @vincentai/cli@latest trading-engine list-strategies --key-id
Get Strategy Details
npx @vincentai/cli@latest trading-engine get-strategy --key-id --strategy-id
Update a Strategy
Update a DRAFT strategy. Pass only the fields you want to change β config is a partial object.
npx @vincentai/cli@latest trading-engine update-strategy --key-id --strategy-id \
--name "Updated Name" --config '{ "thesis": { "confidence": 0.8, "reasoning": "Updated reasoning" } }'
Parameters:
--strategy-id: Strategy ID (required)--name: New strategy name--config: Partial strategy config JSON β only include fields to update--data-source-secret-id: DATA_SOURCES secret ID--poll-interval: New polling interval in minutesActivate a Strategy
Starts driver monitoring and signal pipeline processing. Strategy must be in DRAFT status.
npx @vincentai/cli@latest trading-engine activate --key-id --strategy-id
Pause a Strategy
Stops monitoring. Strategy must be ACTIVE.
npx @vincentai/cli@latest trading-engine pause --key-id --strategy-id
Resume a Strategy
Resumes monitoring. Strategy must be PAUSED.
npx @vincentai/cli@latest trading-engine resume --key-id --strategy-id
Archive a Strategy
Permanently stops a strategy. Cannot be undone.
npx @vincentai/cli@latest trading-engine archive --key-id --strategy-id
Duplicate a Strategy (New Version)
Creates a new DRAFT with the same config, incremented version number, and a link to the parent version.
npx @vincentai/cli@latest trading-engine duplicate-strategy --key-id --strategy-id
View Version History
See all versions of a strategy lineage.
npx @vincentai/cli@latest trading-engine versions --key-id --strategy-id
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.
npx @vincentai/cli@latest trading-engine invocations --key-id --strategy-id --limit 20
View Cost Summary
See aggregate LLM costs for all strategies under a secret.
npx @vincentai/cli@latest trading-engine costs --key-id
View Performance Metrics
See performance metrics for a strategy: P&L, win rate, trade count, and per-instrument breakdown.
npx @vincentai/cli@latest trading-engine performance --key-id --strategy-id
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.
{
"name": "AI News Monitor",
"weight": 1.5,
"direction": "bullish",
"monitoring": {
"keywords": ["AI tokens", "GPU shortage", "prediction market regulation"],
"embeddingAnchor": "AI technology investment trends",
"sources": ["web_search"]
}
}
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.
{
"name": "Crypto Twitter",
"weight": 1.0,
"direction": "contextual",
"monitoring": {
"entities": ["@DeepSeek", "@nvidia", "@OpenAI"],
"keywords": ["AI", "GPU"],
"sources": ["twitter"]
}
}
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.
{
"name": "Market News",
"weight": 1.5,
"direction": "contextual",
"monitoring": {
"keywords": ["artificial intelligence", "GPU shortage", "semiconductor"],
"sources": ["newswire"]
}
}
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 thresholdBELOW β triggers when price drops below a thresholdCHANGE_PCT β triggers on a percentage change from reference pricePrice 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
2. A confidence level: Start at 0.5β0.7 and let the LLM adjust as new data arrives
3. Specific reasoning: "ETF inflows accelerating, halving supply shock imminent" is better than "BTC will go up"
4. 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 |
| ------------------- | ---------------------------------- | ---------------------------------- |
| place_trade | Buy or sell a position | canTrade: true in trade rules |
| set_stop_loss | 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:
dataSourceCreditUsd)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
npx @vincentai/cli@latest trading-engine status --key-id
Returns: worker status, active rules count, last sync time, circuit breaker state
Create a Stop-Loss Rule
Automatically sell a position if price drops below a threshold:
# Polymarket β triggerPrice is 0β1 (outcome token price)
npx @vincentai/cli@latest trading-engine create-rule --key-id \
--market-id 0x123... --token-id 456789 \
--rule-type STOP_LOSS --trigger-price 0.40HyperLiquid β triggerPrice is absolute USD price, marketId and tokenId are the coin name
npx @vincentai/cli@latest trading-engine create-rule --key-id \
--venue hyperliquid --market-id BTC --token-id BTC \
--rule-type STOP_LOSS --trigger-price 95000
Parameters:
--venue: polymarket (default) or hyperliquid--market-id: Polymarket condition ID, or coin name for HyperLiquid (e.g. BTC, ETH)--token-id: Polymarket outcome token ID, or coin name for HyperLiquid--rule-type: STOP_LOSS (sells if price <= trigger), TAKE_PROFIT (sells if price >= trigger), or TRAILING_STOP--trigger-price: Price threshold β 0 to 1 for Polymarket, absolute USD price for HyperLiquidCreate a Take-Profit Rule
Automatically sell a position if price rises above a threshold:
# Polymarket
npx @vincentai/cli@latest trading-engine create-rule --key-id \
--market-id 0x123... --token-id 456789 \
--rule-type TAKE_PROFIT --trigger-price 0.75HyperLiquid
npx @vincentai/cli@latest trading-engine create-rule --key-id \
--venue hyperliquid --market-id ETH --token-id ETH \
--rule-type TAKE_PROFIT --trigger-price 4500
Create a Trailing Stop Rule
A trailing stop moves the stop price up as the price rises:
# Polymarket
npx @vincentai/cli@latest trading-engine create-rule --key-id \
--market-id 0x123... --token-id 456789 \
--rule-type TRAILING_STOP --trigger-price 0.45 --trailing-percent 5HyperLiquid
npx @vincentai/cli@latest trading-engine create-rule --key-id \
--venue hyperliquid --market-id SOL --token-id SOL \
--rule-type TRAILING_STOP --trigger-price 170 --trailing-percent 5
Trailing stop behavior:
--trailing-percent is percent points (e.g. 5 = 5%)candidateStop = currentPrice * (1 - trailingPercent/100)candidateStop > current triggerPrice, updates triggerPricetriggerPrice never moves downcurrentPrice <= triggerPriceList Rules
# All rules
npx @vincentai/cli@latest trading-engine list-rules --key-id Filter by status
npx @vincentai/cli@latest trading-engine list-rules --key-id --status ACTIVE
Update a Rule
npx @vincentai/cli@latest trading-engine update-rule --key-id --rule-id --trigger-price 0.45
Cancel a Rule
npx @vincentai/cli@latest trading-engine delete-rule --key-id --rule-id
View Monitored Positions
npx @vincentai/cli@latest trading-engine positions --key-id
View Event Log
# All events
npx @vincentai/cli@latest trading-engine events --key-id Events for specific rule
npx @vincentai/cli@latest trading-engine events --key-id --rule-id Paginated
npx @vincentai/cli@latest trading-engine events --key-id --limit 50 --offset 100
Event types:
RULE_CREATED β Rule was createdRULE_TRAILING_UPDATED β Trailing stop moved triggerPrice upwardRULE_EVALUATED β Worker checked the rule against current priceRULE_TRIGGERED β Trigger condition was metACTION_PENDING_APPROVAL β Trade requires human approval, rule pausedACTION_EXECUTED β Trade executed successfullyACTION_FAILED β Trade execution failedRULE_CANCELED β Rule was manually canceledRule Statuses
ACTIVE β Rule is live and being monitoredTRIGGERED β Condition was met, trade executedPENDING_APPROVAL β Trade requires human approval; rule pausedCANCELED β Manually canceled before triggeringFAILED β Triggered but trade execution failedComplete Workflow: Strategy + Trade Rules
Polymarket Workflow
Step 1: Place a bet with the Polymarket skill
npx @vincentai/cli@latest polymarket bet --key-id --token-id 123456789 --side BUY --amount 10 --price 0.55
Step 2: Create a strategy to monitor the thesis
npx @vincentai/cli@latest trading-engine create-strategy --key-id \
--name "Bitcoin Bull Thesis" \
--config '{
"instruments": [
{ "id": "123456789", "type": "binary", "venue": "polymarket" }
],
"thesis": {
"estimate": 0.85,
"direction": "long",
"confidence": 0.7,
"reasoning": "Bitcoin is likely to break $100k on ETF inflows"
},
"drivers": [
{
"name": "ETF News",
"weight": 2.0,
"direction": "bullish",
"monitoring": {
"keywords": ["bitcoin ETF inflows", "bitcoin institutional"],
"sources": ["web_search", "newswire"]
}
},
{
"name": "Crypto Twitter",
"weight": 1.0,
"direction": "contextual",
"monitoring": {
"entities": ["@BitcoinMagazine", "@saborskycnbc"],
"sources": ["twitter"]
}
}
],
"escalation": {
"signalScoreThreshold": 0.3,
"highConfidenceThreshold": 0.8,
"maxWakeFrequency": "1 per 15m",
"batchWindow": "5m"
},
"tradeRules": {
"entry": { "minEdge": 0.05 },
"autoActions": { "stopLoss": -0.15, "takeProfit": 0.30, "trailingStop": -0.05 },
"exit": { "thesisInvalidation": ["ETF outflows accelerate above $500M/week"] },
"sizing": { "method": "edgeScaled", "maxPosition": 100, "maxPortfolioPct": 20, "maxTradesPerDay": 5 }
}
}' \
--poll-interval 10
Step 3: Set a standalone stop-loss as immediate protection
npx @vincentai/cli@latest trading-engine create-rule --key-id \
--market-id 0xabc... --token-id 123456789 \
--rule-type STOP_LOSS --trigger-price 0.40
Step 4: Activate the strategy
npx @vincentai/cli@latest trading-engine activate --key-id --strategy-id
Step 5: Monitor activity
# Check strategy invocations
npx @vincentai/cli@latest trading-engine invocations --key-id --strategy-id Check trade rule events
npx @vincentai/cli@latest trading-engine events --key-id Check costs
npx @vincentai/cli@latest trading-engine costs --key-id Check performance
npx @vincentai/cli@latest trading-engine performance --key-id --strategy-id
HyperLiquid Workflow
Step 1: Open a perp position with the HyperLiquid skill
npx @vincentai/cli@latest hyperliquid trade --key-id \
--coin BTC --is-buy true --sz 0.001 --limit-px 106000 --order-type market
Step 2: Set a stop-loss rule for the position
npx @vincentai/cli@latest trading-engine create-rule --key-id \
--venue hyperliquid --market-id BTC --token-id BTC \
--rule-type STOP_LOSS --trigger-price 95000
Step 3: Set a take-profit rule
npx @vincentai/cli@latest trading-engine create-rule --key-id \
--venue hyperliquid --market-id BTC --token-id BTC \
--rule-type TAKE_PROFIT --trigger-price 115000
Step 4: Create a strategy to monitor your thesis
npx @vincentai/cli@latest trading-engine create-strategy --key-id \
--name "BTC Perp Momentum" \
--config '{
"instruments": [
{ "id": "BTC", "type": "perp", "venue": "hyperliquid" }
],
"thesis": {
"estimate": 115000,
"direction": "long",
"confidence": 0.7,
"reasoning": "ETF inflows accelerating, halving supply shock imminent"
},
"drivers": [
{
"name": "ETF News",
"weight": 2.0,
"direction": "bullish",
"monitoring": {
"keywords": ["bitcoin ETF inflows", "bitcoin institutional"],
"sources": ["web_search", "newswire"]
}
}
],
"escalation": {
"signalScoreThreshold": 0.3,
"highConfidenceThreshold": 0.8,
"maxWakeFrequency": "1 per 15m",
"batchWindow": "5m"
},
"tradeRules": {
"entry": { "minEdge": 0.05 },
"autoActions": { "stopLoss": -0.10, "takeProfit": 0.25, "trailingStop": -0.05 },
"sizing": { "method": "edgeScaled", "maxPosition": 500, "maxPortfolioPct": 20, "maxTradesPerDay": 5 }
}
}' \
--poll-interval 10
Step 5: Activate and monitor
npx @vincentai/cli@latest trading-engine activate --key-id --strategy-id
npx @vincentai/cli@latest trading-engine events --key-id
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. 2. 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:
npx @vincentai/cli@latest trading-engine status --key-id
Best Practices
1. Start with confidence: 0.5 and let the LLM adjust β avoid overconfidence in the initial thesis
2. Weight drivers by importance β a driver with weight: 3.0 has 3x the signal score contribution of weight: 1.0
3. Use edgeScaled sizing for adaptive position sizes based on thesis confidence and edge
4. Set maxPortfolioPct to limit exposure β even high-confidence strategies shouldn't risk the entire portfolio
5. Set both stop-loss and take-profit on positions for protection (via autoActions in the config or standalone rules)
6. Use thesisInvalidation exit rules to define explicit conditions that should trigger position exits
7. Monitor invocation costs β check the costs command regularly
8. Iterate with versions β duplicate a strategy to tweak the config without losing the original
9. Don't set triggers too close to current price β market noise can trigger prematurely
Example User Prompts
When a user says:
Output Format
Strategy creation:
{
"strategyId": "strat-123",
"name": "BTC Momentum",
"status": "DRAFT",
"version": 1
}
Rule creation:
{
"ruleId": "rule-456",
"ruleType": "STOP_LOSS",
"triggerPrice": 0.4,
"status": "ACTIVE"
}
LLM invocation log entries:
{
"invocationId": "inv-789",
"strategyId": "strat-123",
"trigger": "web_search",
"actions": ["place_trade"],
"costUsd": 0.12,
"createdAt": "2026-02-26T12:00:00.000Z"
}
Error Handling
| Error | Cause | Resolution |
| --------------------------- | ------------------------------------------------- | ---------------------------------------------------- |
| 401 Unauthorized | Invalid or missing API key | Check that the key-id is correct; re-link if needed |
| 403 Policy Violation | 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
localhost:19000 β only accessible from the same VPSπ Tips & Best Practices
1. Start with confidence: 0.5 and let the LLM adjust β avoid overconfidence in the initial thesis
2. Weight drivers by importance β a driver with weight: 3.0 has 3x the signal score contribution of weight: 1.0
3. Use edgeScaled sizing for adaptive position sizes based on thesis confidence and edge
4. Set maxPortfolioPct to limit exposure β even high-confidence strategies shouldn't risk the entire portfolio
5. Set both stop-loss and take-profit on positions for protection (via autoActions in the config or standalone rules)
6. Use thesisInvalidation exit rules to define explicit conditions that should trigger position exits
7. Monitor invocation costs β check the costs command regularly
8. Iterate with versions β duplicate a strategy to tweak the config without losing the original
9. Don't set triggers too close to current price β market noise can trigger prematurely