-
Notifications
You must be signed in to change notification settings - Fork 1
Description
Objective
Build the AI tool that enables users to create stop-loss orders through natural conversation, protecting their assets from significant price drops with automated execution.
Background
Users should be able to set up stop-loss protection naturally, like "Protect my ETH with a stop-loss at $3000" or "Sell my SOL if it drops 10%". The AI needs to:
- Parse stop-loss intent and parameters
- Validate parameters and check current prices
- Guide through wallet/session setup if needed
- Create stop-loss order
- Provide monitoring updates
Acceptance Criteria
- AI tool definition for stop-loss order creation
- Natural language parsing for stop-loss parameters (asset, trigger price/percentage)
- Price context (show current price vs trigger price)
- Validation of parameters (supported tokens, reasonable triggers)
- Integration with embedded wallet and session key flows
- Order creation via backend API
- Status tracking and price monitoring updates
- Support for order queries ("What's my ETH stop-loss?")
- Support for order cancellation and modification
User Experience Flow
User: "Set a stop-loss on my 5 ETH at $3000"
AI: "I'll protect your 5 ETH with a stop-loss at $3,000.
Current ETH Price: $3,250
Stop-Loss Trigger: $3,000
Distance to Trigger: 7.7% down
When triggered, I'll sell 5 ETH for USDC automatically.
[If no embedded wallet/session] First, let's set up automation...
Ready to activate this stop-loss?"
User: "Yes"
AI: "Stop-loss activated!
Order ID: #DEF456
I'm monitoring ETH price continuously.
You'll be notified if the stop-loss triggers.
Current: $3,250 ✓
Trigger: $3,000"
[Later, if triggered]
AI: "🛑 Stop-Loss Triggered!
ETH dropped to $2,995 (below your $3,000 trigger)
Sold 5 ETH for 14,975 USDC
Transaction: 0xABCD...
Your funds are protected."
Technical Context
AI Tool Definition:
interface CreateStopLossTool {
name: 'create_stop_loss'
description: 'Create a stop-loss order to automatically sell an asset when price drops below a threshold'
parameters: {
token: string // symbol or address to protect
amount: string // how much to protect
triggerType: 'price' | 'percentage'
triggerValue: number // absolute price or percentage drop
sellFor?: string // what to receive (default: USDC)
network?: string
}
}Parameter Parsing:
Handle flexible input:
- "Stop-loss my ETH at $3000"
- "Protect my 10 SOL if it drops 15%"
- "Sell my 1000 USDC of BTC if BTC falls below $90k"
Extract:
- Asset to protect
- Amount
- Trigger type (absolute price or percentage)
- Trigger value
- Asset to receive (default to USDC/stablecoin)
Price Context:
Before confirming order, show:
- Current price
- Trigger price
- Percentage difference
- Make user aware of how far price needs to drop
const currentPrice = await getPrice(token, sellFor)
const percentageDiff = ((triggerPrice - currentPrice) / currentPrice) * 100
return {
currentPrice: formatPrice(currentPrice),
triggerPrice: formatPrice(triggerPrice),
distance: `${Math.abs(percentageDiff).toFixed(1)}% ${percentageDiff > 0 ? 'up' : 'down'}`
}Validation:
- Token is supported and has liquidity
- Amount is reasonable (minimum order size)
- Trigger price is below current price (can't stop-loss above market)
- If percentage: value is negative (e.g., -10%, not +10%)
- User owns the asset being protected
Tool Execution Flow:
async function executeStopLossTool(params) {
// 1. Validate and get current price
const currentPrice = await getPrice(params.token, params.sellFor)
if (params.triggerType === 'price' && params.triggerValue >= currentPrice) {
return {
error: 'Trigger price must be below current price',
currentPrice
}
}
// 2. Check wallet and balance
const balance = await getBalance(userId, params.token)
if (balance < params.amount) {
return { error: 'Insufficient balance', available: balance }
}
// 3. Check/create embedded wallet and session key
const sessionKey = await ensureSessionKey(userId, {
permissions: calculateStopLossPermissions(params)
})
// 4. Create stop-loss order
const order = await api.createStopLoss({
sessionKeyId: sessionKey.id,
...params,
entryPrice: currentPrice // for percentage triggers
})
return {
success: true,
orderId: order.id,
currentPrice,
summary: formatStopLossSummary(order)
}
}Session Permissions for Stop-Loss
{
contractAddress: SWAP_ROUTER_ADDRESS,
allowedFunctions: ['swap', 'exactInputSingle'],
maxPerTransaction: params.amount * 1.2, // +20% buffer for price movement
maxTotalAmount: params.amount * 1.2,
duration: 365 * 24 * 3600, // 1 year (user can cancel anytime)
rateLimit: {
count: 3, // Allow retries on failure
period: 3600 // Within 1 hour
}
}Order Status & Monitoring
Status Queries:
- "What's my ETH stop-loss?"
- "Show my stop-loss orders"
- "How far until my stop-loss triggers?"
Response includes:
- Current price
- Trigger price
- Distance to trigger (%)
- Order status (active, triggered, cancelled)
- If triggered: execution details
Price Updates:
Optionally provide periodic updates:
- "Your ETH is at $3,100 (3% from stop-loss)"
- Warning when approaching trigger
- Immediate notification on trigger
Order Management:
Support updates and cancellation:
- "Cancel my ETH stop-loss"
- "Update stop-loss to $2,900"
- "Remove all stop-losses"
Error Handling
Common Issues:
- Trigger price above current price (user error)
- Insufficient balance
- Token not supported
- Session expired when trigger hits
- Execution fails (slippage, liquidity)
- Price feed unavailable
For each:
- Clear explanation
- Suggest fix
- Offer alternatives
Advanced Features (Future)
Trailing Stop-Loss:
"Stop-loss 5% below highest price"
- Automatically adjusts trigger as price rises
- Locks in gains while protecting downside
Conditional Stop-Loss:
"Stop-loss only during market hours"
"Stop-loss with time limit"
Partial Stop-Loss:
"Sell 50% at $3000, remaining 50% at $2800"
Defer these to later iterations.
Testing Scenarios
- Create stop-loss with absolute price
- Create stop-loss with percentage drop
- Create with price above market (should reject)
- Query status while price declining toward trigger
- Cancel order before trigger
- Order triggers and executes
- Order triggers but execution fails
- Multiple stop-losses on different assets
- Stop-loss on asset user doesn't own (reject)
UI Considerations
Clear Communication:
- Show risk/reward (protecting against X% loss)
- Explain trigger conditions clearly
- Visual indicator of distance to trigger
Transparency:
- Current price always visible
- Real-time or recent price data
- Clear execution details when triggered
Files to Create/Modify
- AI tool definition for stop-loss
- Tool execution logic
- Backend API client
- Chat prompt updates
- Price formatting utilities
- Order status formatting
Dependencies
- Requires "Implement Stop-Loss Monitor and Executor"
- Requires "Build Session Key Approval Flow in Chat Interface"
- Requires price feed integration
Metadata
Metadata
Assignees
Labels
Type
Projects
Status