Compare commits

..

27 Commits

Author SHA1 Message Date
shokollm
f46cad4379 WIP: Multiple fixes and improvements
Backend:
- Fixed auth issue where get_optional_user wasn't properly extracting tokens
- Added user_id to conversational agent for proper auth context
- Fixed DCA buy logic to support multiple buys on dips
- Fixed sell logic to use amount_percent
- Added comprehensive backtest engine tests
- Fixed kline data validation for bad price data
- Fixed chained tool calls handling

Frontend:
- BotCard now links to chat page instead of bot page
- Chat page handles direct bot loading from dashboard
- Various UI improvements and fixes

Tests:
- Added test_agent.py with mock client tests
- Added test_backtest_engine.py with 7 comprehensive tests
2026-04-15 15:20:42 +00:00
shokollm
1b8761d1f4 feat: frontend conversation-based chat UI (#60)
- Add Conversation, Message, ConversationWithMessages types
- Add conversations API client methods (list, create, get, delete, chat, setBot)
- Create conversationStore for state management
- Create ChatLayout component with left/right panes
- Create ConversationList component for left pane
- Create ChatArea component for messages display
- Create ChatInput component for message input
- Create BotInfoPanel component for right pane
- Create AnonymousBanner component for non-logged users
- Create CandlestickLoader animation component
- Add /home and /chat routes
- Handle anonymous user rate limits (40 warning, 50 max)
- Handle system rate limits (429) and auth limits (403)
2026-04-14 06:36:55 +00:00
958dc3bb1f Merge pull request 'feat: conversation-based chat system with anonymous support' (#65) from fix/issue-59 into main 2026-04-14 08:19:54 +02:00
shokollm
5ae8d76bde feat: implement conversation-based chat system with anonymous support
- Add Conversation model with user/anonymous_token/bot_id fields
- Add Message model linked to conversations
- Add AnonymousUser model for tracking anonymous chat limits
- Create /api/conversations endpoints (list, create, get, delete)
- Add POST /api/conversations/{id}/chat for messaging
- Add POST /api/conversations/{id}/set-bot for linking bot
- Implement rate limiter with system-wide (500/5hrs) and anonymous limits
- Anonymous users: max 50 chats, max 1 bot, max 1 backtest
- Add warning after 40 anonymous messages
- Register conversations router in main.py
- Add create_bot, list_bots, set_bot, get_bot_info tools to registry
2026-04-14 04:25:00 +00:00
a9679bbb5d Merge pull request 'refactor: Split conversational.py into modular structure' (#64) from fix/issue-63 into main 2026-04-14 05:57:16 +02:00
shokollm
b1ddad0808 Fix intermittent UnboundLocalError for 'thinking' variable in ConversationalAgent.chat() - initialize thinking=None before conditional assignment to handle API responses missing message field 2026-04-14 03:34:36 +00:00
shokollm
f705269e34 refactor: Split conversational.py into modular structure (fixes #63)
Split conversational.py (2271 lines) into modular files:
- tools.py: TOOL_REGISTRY, get_tool_registry(), SKILL_EMOJIS
- help.py: format_* functions for slash command help
- client.py: MiniMaxClient, SYSTEM_PROMPT, TOOLS definitions
- agent.py: ConversationalAgent class with all methods
- __init__.py: Public exports from all modules

Updated bots.py import to use new module path.
Deleted conversational.py.
2026-04-14 02:36:23 +00:00
8acce849f4 Merge pull request 'feat: Add slash command help system (#57)' (#62) from fix/issue-57 into main 2026-04-14 04:03:29 +02:00
shokollm
2d125ede22 fix: Also fix price_change field in AI tool execution path
There was duplicate code handling search_tokens in the AI tool calling section.
2026-04-14 01:43:30 +00:00
shokollm
7a64632a63 fix: Correct price_change field fallback logic
Was returning 'N/A' incorrectly when token_price_change_24h was missing.
Now properly checks: price_change_24h OR token_price_change_24h OR 'N/A'
2026-04-14 00:37:48 +00:00
shokollm
bb62e53093 fix: Handle price_change_24h field name in search results
Search API returns 'price_change_24h' not 'token_price_change_24h'. Now checks for both.
2026-04-14 00:33:38 +00:00
shokollm
cf74251ad0 fix: Show token name/symbol in risk analysis and handle unknown honeypot
- Display token name and symbol in risk analysis output
- Handle is_honeypot: -1 as 'Unknown (could not determine)'
- Show risk level (Low/Medium/High) with risk score
- Use risk_level field instead of status
2026-04-14 00:28:15 +00:00
shokollm
1efc0eaba6 feat: Add context awareness for price tool
- Store recent search results in agent instance
- When price returns empty, suggest using /search tool
- Check if user input matches recent search results and use that address
2026-04-14 00:19:42 +00:00
shokollm
f4f6168f68 revert: Keep using price API for price lookups
The price API requires full contract addresses (0x...-bsc format).
Improved error handling and formatting for price responses.
2026-04-14 00:12:46 +00:00
shokollm
62bcd6e099 fix: Use search API for price lookups instead of price API
The price API requires full contract addresses (0x...-bsc), but users typically provide symbols.
Now /price TRADOOR will search for the token and show price info from search results.
2026-04-14 00:03:34 +00:00
shokollm
6b8912a7eb fix: Better error detection for AVE API commands
- Added _is_error_output helper to detect errors in CLI output
- API errors like 'API error 403' now show proper error message instead of 'No price data available'
- Updated all command execution methods to use the helper
2026-04-13 23:55:51 +00:00
shokollm
2c3b6ef073 fix: Show token name and ticker in backtest result
- Added _get_token_info helper to fetch symbol and name
- Backtest result now shows: **PEPE** (Pepe) -
2026-04-13 23:37:17 +00:00
shokollm
613ec0dc1f fix: Provide default empty string for backtest/simulate calls
- Fixed missing message argument when calling direct execution methods
- Both /backtest and /simulate now work without arguments
2026-04-13 23:34:04 +00:00
shokollm
7bdd49a56c fix: Execute backtest and simulate commands directly
- Added _execute_backtest_direct() that extracts params from message or strategy config
- Added _execute_simulate_direct() that extracts params from message or strategy config
- Both commands now execute directly when called with /backtest or /simulate
- If token address is missing, asks user for the parameter
2026-04-13 23:32:08 +00:00
shokollm
e92506a787 feat: Two-step command execution flow
Commands now execute in two steps:
1. User sends /search -> acknowledge and wait for param
2. User sends 'pepe' -> auto-execute search with 'pepe'

Commands without params (/backtest, /simulate, /trending, /strategy) execute directly.

Pending commands tracked via self.pending_command state.
2026-04-13 23:23:01 +00:00
shokollm
696d3934d5 fix: Execute trending command directly when /trending is called
- Added _execute_trending method that runs the trending CLI command
- Returns formatted list of trending tokens on BSC
- Shows error message if no tokens found or command fails
2026-04-13 23:07:43 +00:00
shokollm
466fdf1fe9 fix: Fetch strategy from database when /strategy is called
- Added _get_strategy_response method to query bot's strategy_config from DB
- Shows formatted strategy with conditions, actions, and risk management
- Shows helpful message if no strategy is configured yet
2026-04-13 23:02:49 +00:00
shokollm
39a27caf05 feat: Add slash command system with skill acknowledgments
- Reset conversational.py to pr-58 working AVE integration
- Added TOOL_REGISTRY with all available slash commands
- Added _handle_slash_command for skill activation
- Slash commands show brief acknowledgment when used alone
- Slash commands with args are passed to AI for handling
- Added dropdown menu in ChatInterface for skill discovery
- Menu positions above textarea
- Menu shows filtered tools as user types
2026-04-13 16:21:57 +00:00
shokollm
61b9da295b feat: Add /trending tool for popular tokens 2026-04-13 13:51:17 +00:00
shokollm
38e45b9fd0 fix: Use 'Commands:' instead of 'Usage:' to match issue spec 2026-04-13 13:48:17 +00:00
shokollm
e41d07486b feat: Add slash command help system for conversational interface
Implement slash command help system as described in issue #57:

- Add Tool Registry in backend with metadata for all available tools
- Add command parser for '/' prefix in ConversationalAgent
- Add slash command handling functions:
  - '/' shows list of all available tools
  - '/help' shows general help about Randebu
  - '/<tool-name>' shows detailed help for specific tool
- Update frontend ChatInterface to detect '/' and show formatted help dropdown
- Add keyboard navigation (Arrow keys, Tab, Enter, Escape) for slash menu
2026-04-13 13:05:08 +00:00
7e03101e7b Merge pull request 'feat: Add AVE Cloud Skills as conversational agent tools (#56)' (#58) from fix/issue-56 into main 2026-04-13 14:56:33 +02:00
42 changed files with 8357 additions and 1634 deletions

View File

@@ -1,7 +1,7 @@
from fastapi import APIRouter, Depends, HTTPException, status, Request
from fastapi.security import OAuth2PasswordBearer
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from typing import Annotated
from typing import Optional, Annotated
from ..core.database import get_db
from ..core.security import (
@@ -26,6 +26,14 @@ router = APIRouter()
settings = get_settings()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
# Custom optional token extractor that doesn't raise on missing token
def get_optional_token(request: Request) -> Optional[str]:
"""Extract bearer token from Authorization header, returning None if not present."""
auth_header = request.headers.get("Authorization")
if auth_header and auth_header.startswith("Bearer "):
return auth_header[7:] # Remove "Bearer " prefix
return None
TOKEN_BLACKLIST = set()
@@ -58,6 +66,31 @@ def get_current_user(
return user
def get_optional_user(
request: Request,
db: Session = Depends(get_db),
) -> Optional[User]:
"""Get current user, returning None if not authenticated."""
token = get_optional_token(request)
if not token:
return None
if token in TOKEN_BLACKLIST:
return None
payload = verify_token(token)
if payload is None:
return None
user_id = payload.get("sub")
if user_id is None:
return None
user = db.query(User).filter(User.id == user_id).first()
return user
@router.post(
"/register", response_model=Token, status_code=status.HTTP_201_CREATED
)

View File

@@ -1,16 +1,17 @@
import uuid
import asyncio
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, status, BackgroundTasks
from fastapi import APIRouter, Depends, HTTPException, status, BackgroundTasks, Request
from sqlalchemy.orm import Session
from typing import List, Dict, Any, Optional
from typing import List, Dict, Any, Optional, Union
from concurrent.futures import ThreadPoolExecutor
from .auth import get_current_user
from .auth import get_optional_user, get_current_user
from ..core.database import get_db
from ..core.config import get_settings
from ..db.schemas import BacktestCreate, BacktestResponse
from ..db.models import Bot, Backtest, Signal, User
from ..db.models import Bot, Backtest, Signal, User, AnonymousUser
from ..services.rate_limiter import RateLimiter
router = APIRouter()
@@ -88,18 +89,41 @@ async def start_backtest(
bot_id: str,
config: BacktestCreate,
background_tasks: BackgroundTasks,
current_user: User = Depends(get_current_user),
current_user: Optional[User] = Depends(get_optional_user),
db: Session = Depends(get_db),
request: Request = None,
):
bot = db.query(Bot).filter(Bot.id == bot_id).first()
if not bot:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Bot not found"
)
# Check authorization
if current_user:
# Authenticated user - must own the bot
if bot.user_id != current_user.id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail="Not authorized"
)
else:
# Anonymous user - can only run backtests on anonymous bots (user_id = None)
if bot.user_id is not None:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You need to be logged in to run backtests on this bot"
)
# Rate limit anonymous backtests
anonymous_token = request.cookies.get("anonymous_token") if request else None
if anonymous_token:
try:
RateLimiter.check_anonymous_backtest_limit(db, anonymous_token)
except HTTPException as e:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You've reached the maximum of 1 backtest as an anonymous user. Please login or create an account for unlimited backtests."
)
settings = get_settings()
backtest_id = str(uuid.uuid4())
@@ -134,6 +158,10 @@ async def start_backtest(
db.commit()
db.refresh(backtest)
# Increment anonymous backtest count
if not current_user and anonymous_token:
RateLimiter.increment_backtest_count(db, anonymous_token)
db_url = str(settings.DATABASE_URL)
background_tasks.add_task(
run_backtest_sync, backtest_id, db_url, bot_id, backtest_config

View File

@@ -1,8 +1,8 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Annotated
from typing import List, Annotated, Optional
from .auth import get_current_user
from .auth import get_current_user, get_optional_user
from ..core.database import get_db
from ..core.config import get_settings
from ..db.schemas import (
@@ -16,7 +16,7 @@ from ..db.schemas import (
)
from ..db.models import Bot, BotConversation, User
from ..services.ai_agent.crew import get_trading_crew
from ..services.ai_agent.conversational import get_conversational_agent
from ..services.ai_agent import get_conversational_agent
router = APIRouter()
MAX_BOTS_PER_USER = 3
@@ -71,7 +71,7 @@ def create_bot(
@router.get("/{bot_id}", response_model=BotResponse)
def get_bot(
bot_id: str,
current_user: Annotated[User, Depends(get_current_user)],
current_user: Optional[User] = Depends(get_optional_user),
db: Session = Depends(get_db),
):
bot = db.query(Bot).filter(Bot.id == bot_id).first()
@@ -80,11 +80,22 @@ def get_bot(
status_code=status.HTTP_404_NOT_FOUND,
detail="Bot not found",
)
# Check authorization
if current_user:
# Authenticated user - must own the bot
if bot.user_id != current_user.id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not authorized to access this bot",
)
else:
# Anonymous user - can only access anonymous bots (user_id = None)
if bot.user_id is not None:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not authorized to access this bot",
)
return bot
@@ -163,7 +174,7 @@ def delete_bot(
def chat(
bot_id: str,
request: BotChatRequest,
current_user: Annotated[User, Depends(get_current_user)],
current_user: Optional[User] = Depends(get_optional_user),
db: Session = Depends(get_db),
):
bot = db.query(Bot).filter(Bot.id == bot_id).first()
@@ -172,11 +183,21 @@ def chat(
status_code=status.HTTP_404_NOT_FOUND,
detail="Bot not found",
)
# Check authorization
if current_user:
# Authenticated user - must own the bot
if bot.user_id != current_user.id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not authorized to chat with this bot",
)
else:
# Anonymous user - can only chat with anonymous bots (user_id = None)
if bot.user_id is not None:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not authorized to chat with this bot",
)
conversation_history = (
db.query(BotConversation)
@@ -191,8 +212,17 @@ def chat(
user_message = request.message
import logging
logger = logging.getLogger(__name__)
logger.warning(f"chat endpoint: current_user={current_user}, user_id={current_user.id if current_user else None}")
# Use ConversationalAgent for natural chat with tool-calling
agent = get_conversational_agent(bot_id=bot_id)
agent = get_conversational_agent(
bot_id=bot_id,
user_id=current_user.id if current_user else None
)
logger.warning(f"chat endpoint: agent.user_id={agent.user_id}")
result = agent.chat(user_message, history_for_agent)
assistant_content = result.get("response", "I couldn't process your request.")
@@ -224,7 +254,9 @@ def chat(
strategy_config=bot.strategy_config if result.get("strategy_updated") else None,
success=result.get("success", False),
strategy_needs_confirmation=result.get("strategy_needs_confirmation", False),
strategy_data=result.get("strategy_data") if result.get("strategy_needs_confirmation") else None,
strategy_data=result.get("strategy_data")
if result.get("strategy_needs_confirmation")
else None,
token_search_results=result.get("token_search_results"),
)
@@ -232,7 +264,7 @@ def chat(
@router.get("/{bot_id}/history", response_model=List[BotConversationResponse])
def get_history(
bot_id: str,
current_user: Annotated[User, Depends(get_current_user)],
current_user: Optional[User] = Depends(get_optional_user),
db: Session = Depends(get_db),
):
bot = db.query(Bot).filter(Bot.id == bot_id).first()
@@ -241,11 +273,21 @@ def get_history(
status_code=status.HTTP_404_NOT_FOUND,
detail="Bot not found",
)
# Check authorization
if current_user:
# Authenticated user - must own the bot
if bot.user_id != current_user.id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not authorized to access this bot's history",
)
else:
# Anonymous user - can only access anonymous bots (user_id = None)
if bot.user_id is not None:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not authorized to access this bot's history",
)
conversations = (
db.query(BotConversation)

View File

@@ -0,0 +1,350 @@
import secrets
from fastapi import APIRouter, Depends, HTTPException, status, Request, Response
from sqlalchemy.orm import Session
from typing import List, Optional, Annotated
from ..core.database import get_db
from ..db.models import Conversation, Message, User, AnonymousUser, Bot
from ..db.schemas import ChatRequest
from ..api.auth import get_optional_user
from ..services.rate_limiter import RateLimiter
from ..services.ai_agent import get_conversational_agent
router = APIRouter(prefix="/api/conversations", tags=["conversations"])
def get_or_create_anonymous_token(
request: Request, response: Response, db: Session
) -> str:
token = request.cookies.get("anonymous_token")
if not token:
token = secrets.token_urlsafe(32)
response.set_cookie(
key="anonymous_token",
value=token,
max_age=60 * 60 * 24 * 365,
httponly=True,
)
anon = AnonymousUser(id=token)
db.add(anon)
db.commit()
return token
@router.get("")
def list_conversations(
db: Session = Depends(get_db),
current_user: Optional[User] = Depends(get_optional_user),
):
if current_user:
return (
db.query(Conversation)
.filter(Conversation.user_id == current_user.id)
.order_by(Conversation.updated_at.desc())
.all()
)
return []
@router.post("")
def create_conversation(
db: Session = Depends(get_db),
current_user: Optional[User] = Depends(get_optional_user),
request: Request = None,
response: Response = None,
):
anonymous_token = None
if not current_user and request:
anonymous_token = get_or_create_anonymous_token(request, response, db)
conversation = Conversation(
user_id=current_user.id if current_user else None,
anonymous_token=anonymous_token,
)
db.add(conversation)
db.commit()
db.refresh(conversation)
return conversation
@router.get("/{conversation_id}")
def get_conversation(
conversation_id: str,
db: Session = Depends(get_db),
current_user: Optional[User] = Depends(get_optional_user),
):
conversation = (
db.query(Conversation).filter(Conversation.id == conversation_id).first()
)
if not conversation:
raise HTTPException(status_code=404, detail="Conversation not found")
if conversation.user_id and current_user and conversation.user_id != current_user.id:
raise HTTPException(status_code=403, detail="Access denied")
# Get messages for this conversation
messages = (
db.query(Message)
.filter(Message.conversation_id == conversation_id)
.order_by(Message.created_at)
.all()
)
# Build response with messages
return {
"id": conversation.id,
"user_id": conversation.user_id,
"bot_id": conversation.bot_id,
"title": conversation.title,
"created_at": conversation.created_at.isoformat() if conversation.created_at else None,
"updated_at": conversation.updated_at.isoformat() if conversation.updated_at else None,
"messages": [
{
"id": msg.id,
"conversation_id": msg.conversation_id,
"role": msg.role,
"content": msg.content,
"created_at": msg.created_at.isoformat() if msg.created_at else None,
}
for msg in messages
],
}
@router.delete("/{conversation_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_conversation(
conversation_id: str,
db: Session = Depends(get_db),
current_user: Optional[User] = Depends(get_optional_user),
):
conversation = (
db.query(Conversation).filter(Conversation.id == conversation_id).first()
)
if not conversation:
raise HTTPException(status_code=404, detail="Conversation not found")
if conversation.user_id and current_user and conversation.user_id != current_user.id:
raise HTTPException(status_code=403, detail="Access denied")
db.delete(conversation)
db.commit()
@router.post("/{conversation_id}/set-bot")
def set_bot_for_conversation(
conversation_id: str,
bot_id: str,
db: Session = Depends(get_db),
current_user: Optional[User] = Depends(get_optional_user),
request: Request = None,
):
conversation = (
db.query(Conversation).filter(Conversation.id == conversation_id).first()
)
if not conversation:
raise HTTPException(status_code=404, detail="Conversation not found")
if conversation.user_id and current_user and conversation.user_id != current_user.id:
raise HTTPException(status_code=403, detail="Access denied")
if not current_user:
anonymous_token = request.cookies.get("anonymous_token") if request else None
if anonymous_token:
RateLimiter.check_anonymous_bot_limit(db, anonymous_token)
bot = db.query(Bot).filter(Bot.id == bot_id).first()
if not bot:
raise HTTPException(status_code=404, detail="Bot not found")
if current_user and bot.user_id != current_user.id:
raise HTTPException(status_code=403, detail="Not authorized to use this bot")
conversation.bot_id = bot_id
db.commit()
if not current_user and request:
anonymous_token = request.cookies.get("anonymous_token")
if anonymous_token:
RateLimiter.set_bot_created(db, anonymous_token)
return {"status": "updated", "bot_id": bot_id}
@router.post("/{conversation_id}/chat")
def chat_in_conversation(
conversation_id: str,
body: ChatRequest,
db: Session = Depends(get_db),
current_user: Optional[User] = Depends(get_optional_user),
request: Request = None,
response: Response = None,
):
conversation = (
db.query(Conversation).filter(Conversation.id == conversation_id).first()
)
if not conversation:
raise HTTPException(status_code=404, detail="Conversation not found")
if conversation.user_id and current_user and conversation.user_id != current_user.id:
raise HTTPException(status_code=403, detail="Access denied")
warning = None
user_is_authenticated = current_user is not None
# Get anonymous_token from cookies or from the conversation itself
anonymous_token = None
if not current_user:
RateLimiter.check_system_limit(db)
# First try to get from conversation (more reliable)
anonymous_token = conversation.anonymous_token
# If not on conversation, try cookies
if not anonymous_token and request:
anonymous_token = request.cookies.get("anonymous_token")
# If still not found, create new one
if not anonymous_token:
anonymous_token = get_or_create_anonymous_token(request, response, db)
# Also set it on the conversation for future use
conversation.anonymous_token = anonymous_token
db.commit()
# Debug logging
import logging
logging.info(f"Anonymous chat: token={anonymous_token}, checking limit")
anon = RateLimiter.check_anonymous_limit(db, anonymous_token)
if anon:
logging.info(f"Anonymous user found: chat_count={anon.chat_count}")
else:
logging.info("Anonymous user NOT found in DB")
RateLimiter.increment_chat_count(db, anonymous_token)
if anon and anon.chat_count > 40:
warning = "Your progress is not saved."
# Always save the user's message first
user_msg = Message(
conversation_id=conversation_id,
role="user",
content=body.message,
)
db.add(user_msg)
# Get conversation history for context
conversation_history = (
db.query(Message)
.filter(Message.conversation_id == conversation_id)
.order_by(Message.created_at)
.all()
)
history_for_agent = [
{"role": msg.role, "content": msg.content} for msg in conversation_history[-10:]
]
# Get user_id
user_id = current_user.id if current_user else None
# Debug logging
print(f"DEBUG: conversation_id={conversation_id}")
print(f"DEBUG: conversation.bot_id={conversation.bot_id}")
print(f"DEBUG: conversation.anonymous_token={conversation.anonymous_token[:20] if conversation.anonymous_token else None}")
print(f"DEBUG: anonymous_token variable={anonymous_token[:20] if anonymous_token else None}")
# If no bot is set, use a general-purpose agent (without bot-specific context)
if not conversation.bot_id:
# Use the conversational agent with user context
agent = get_conversational_agent(
user_id=user_id,
conversation_id=conversation_id,
anonymous_token=anonymous_token,
)
result = agent.chat(body.message, history_for_agent)
assistant_content = result.get("response", "I couldn't process your request.")
# Refresh conversation to get updated bot_id (in case agent set it)
db.refresh(conversation)
# Save the assistant's response
assistant_msg = Message(
conversation_id=conversation_id,
role="assistant",
content=assistant_content,
)
db.add(assistant_msg)
db.commit()
# Fetch updated conversation with messages
conversation_history = (
db.query(Message)
.filter(Message.conversation_id == conversation_id)
.order_by(Message.created_at)
.all()
)
return {
"id": conversation.id,
"user_id": conversation.user_id,
"bot_id": conversation.bot_id,
"title": conversation.title,
"created_at": conversation.created_at.isoformat() if conversation.created_at else None,
"updated_at": conversation.updated_at.isoformat() if conversation.updated_at else None,
"messages": [
{
"id": msg.id,
"conversation_id": msg.conversation_id,
"role": msg.role,
"content": msg.content,
"created_at": msg.created_at.isoformat() if msg.created_at else None,
}
for msg in conversation_history
],
}
# Bot is set - process with the AI agent
agent = get_conversational_agent(
bot_id=conversation.bot_id,
user_id=user_id,
conversation_id=conversation_id,
anonymous_token=anonymous_token,
)
result = agent.chat(body.message, history_for_agent)
assistant_content = result.get("response", "I couldn't process your request.")
# Save the assistant's response
assistant_msg = Message(
conversation_id=conversation_id,
role="assistant",
content=assistant_content,
)
db.add(assistant_msg)
db.commit()
# Fetch updated conversation with messages
conversation_history = (
db.query(Message)
.filter(Message.conversation_id == conversation_id)
.order_by(Message.created_at)
.all()
)
return {
"id": conversation.id,
"user_id": conversation.user_id,
"bot_id": conversation.bot_id,
"title": conversation.title,
"created_at": conversation.created_at.isoformat() if conversation.created_at else None,
"updated_at": conversation.updated_at.isoformat() if conversation.updated_at else None,
"messages": [
{
"id": msg.id,
"conversation_id": msg.conversation_id,
"role": msg.role,
"content": msg.content,
"created_at": msg.created_at.isoformat() if msg.created_at else None,
}
for msg in conversation_history
],
}

View File

@@ -10,6 +10,7 @@ from sqlalchemy import (
ForeignKey,
Index,
JSON,
Integer,
)
from sqlalchemy.orm import relationship
from ..core.database import Base
@@ -30,13 +31,16 @@ class User(Base):
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
bots = relationship("Bot", back_populates="user", cascade="all, delete-orphan")
conversations = relationship(
"Conversation", back_populates="user", cascade="all, delete-orphan"
)
class Bot(Base):
__tablename__ = "bots"
id = Column(String, primary_key=True, default=generate_uuid)
user_id = Column(String, ForeignKey("users.id"), nullable=False)
user_id = Column(String, ForeignKey("users.id"), nullable=True) # nullable for anonymous bots
name = Column(String, nullable=False)
description = Column(Text)
strategy_config = Column(JSON, nullable=False)
@@ -47,6 +51,9 @@ class Bot(Base):
user = relationship("User", back_populates="bots")
conversations = relationship(
"Conversation", back_populates="bot", cascade="all, delete-orphan"
)
bot_conversations = relationship(
"BotConversation", back_populates="bot", cascade="all, delete-orphan"
)
backtests = relationship(
@@ -58,6 +65,47 @@ class Bot(Base):
signals = relationship("Signal", back_populates="bot", cascade="all, delete-orphan")
class Conversation(Base):
__tablename__ = "conversations"
id = Column(String, primary_key=True, default=generate_uuid)
user_id = Column(String, ForeignKey("users.id"), nullable=True)
anonymous_token = Column(String(64), nullable=True)
bot_id = Column(String, ForeignKey("bots.id"), nullable=True)
title = Column(String(255), default="New Conversation")
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
user = relationship("User", back_populates="conversations")
bot = relationship("Bot", back_populates="conversations")
messages = relationship(
"Message", back_populates="conversation", cascade="all, delete-orphan"
)
class Message(Base):
__tablename__ = "messages"
id = Column(String, primary_key=True, default=generate_uuid)
conversation_id = Column(String, ForeignKey("conversations.id"), nullable=True)
role = Column(String, nullable=False)
content = Column(Text, nullable=False)
created_at = Column(DateTime, default=datetime.utcnow)
conversation = relationship("Conversation", back_populates="messages")
class AnonymousUser(Base):
__tablename__ = "anonymous_users"
id = Column(String(64), primary_key=True)
chat_count = Column(Integer, default=0)
bot_created = Column(Boolean, default=False)
backtest_count = Column(Integer, default=0)
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
class BotConversation(Base):
__tablename__ = "bot_conversations"
@@ -67,7 +115,7 @@ class BotConversation(Base):
content = Column(Text, nullable=False)
created_at = Column(DateTime, default=datetime.utcnow)
bot = relationship("Bot", back_populates="conversations")
bot = relationship("Bot", back_populates="bot_conversations")
class Backtest(Base):
@@ -118,7 +166,10 @@ class Signal(Base):
Index("idx_bots_user_id", Bot.user_id)
Index("idx_conversations_bot_id", BotConversation.bot_id)
Index("idx_conversations_user_id", Conversation.user_id)
Index("idx_conversations_bot_id", Conversation.bot_id)
Index("idx_messages_conversation_id", Message.conversation_id)
Index("idx_bot_conversations_bot_id", BotConversation.bot_id)
Index("idx_backtests_bot_id", Backtest.bot_id)
Index("idx_simulations_bot_id", Simulation.bot_id)
Index("idx_signals_bot_id", Signal.bot_id)

View File

@@ -54,7 +54,7 @@ class BotUpdate(BaseModel):
class BotResponse(BaseModel):
id: str
user_id: str
user_id: Optional[str] # None for anonymous bots
name: str
description: Optional[str]
strategy_config: dict
@@ -242,3 +242,57 @@ class AveChainSwapRequest(BaseModel):
class AveChainSwapResponse(BaseModel):
swap: Optional[dict] = None
upsell_message: Optional[str] = None
class ConversationResponse(BaseModel):
id: str
user_id: Optional[str]
anonymous_token: Optional[str]
bot_id: Optional[str]
title: str
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True
class MessageResponse(BaseModel):
id: str
conversation_id: Optional[str]
role: str
content: str
created_at: datetime
class Config:
from_attributes = True
class ConversationWithMessagesResponse(BaseModel):
id: str
user_id: Optional[str]
anonymous_token: Optional[str]
bot_id: Optional[str]
title: str
created_at: datetime
updated_at: datetime
messages: List[MessageResponse] = []
class Config:
from_attributes = True
class SetBotRequest(BaseModel):
bot_id: str
class ChatRequest(BaseModel):
message: str
class ChatResponse(BaseModel):
response: str
thinking: Optional[str] = None
strategy_config: Optional[dict] = None
success: bool = False
warning: Optional[str] = None

View File

@@ -4,7 +4,7 @@ from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from slowapi import Limiter
from slowapi.util import get_remote_address
from .api import auth, bots, backtest, simulate, config, ave
from .api import auth, bots, backtest, simulate, config, ave, conversations
from .core.limiter import limiter
from .core.database import engine, Base
@@ -15,7 +15,17 @@ logger = logging.getLogger(__name__)
async def lifespan(app: FastAPI):
"""Initialize database on startup."""
# Import all models to ensure they're registered
from .db.models import User, Bot, BotConversation, Backtest, Simulation, Signal
from .db.models import (
User,
Bot,
BotConversation,
Backtest,
Simulation,
Signal,
Conversation,
Message,
AnonymousUser,
)
# Create tables if they don't exist
Base.metadata.create_all(bind=engine)
@@ -44,6 +54,7 @@ app.add_middleware(
app.include_router(auth.router, prefix="/api/auth", tags=["auth"])
app.include_router(bots.router, prefix="/api/bots", tags=["bots"])
app.include_router(conversations.router, tags=["conversations"])
app.include_router(backtest.router, prefix="/api", tags=["backtest"])
app.include_router(simulate.router, prefix="/api", tags=["simulate"])
app.include_router(config.router, prefix="/api/config", tags=["config"])

View File

@@ -1,4 +1,29 @@
"""AI Agent module for conversational trading."""
from .agent import ConversationalAgent, get_conversational_agent
from .client import MiniMaxClient
from .tools import get_tool_registry, TOOL_REGISTRY
from .help import (
format_tools_list,
format_general_help,
format_tool_help,
format_skill_acknowledgment,
)
from .crew import TradingCrew, get_trading_crew
from .llm_connector import MiniMaxLLM, MiniMaxConnector
__all__ = ["TradingCrew", "get_trading_crew", "MiniMaxLLM", "MiniMaxConnector"]
__all__ = [
"ConversationalAgent",
"get_conversational_agent",
"MiniMaxClient",
"get_tool_registry",
"TOOL_REGISTRY",
"format_tools_list",
"format_general_help",
"format_tool_help",
"format_skill_acknowledgment",
"TradingCrew",
"get_trading_crew",
"MiniMaxLLM",
"MiniMaxConnector",
]

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,451 @@
"""MiniMax API client for the conversational agent."""
import requests
from typing import Dict, Any, Optional, List
SYSTEM_PROMPT = """You are a helpful AI trading assistant named Randebu. You help users manage their trading bots.
IMPORTANT CHAIN LIMITATION:
- We ONLY support BSC (Binance Smart Chain) blockchain
- If user asks about any other chain (Solana, ETH, Base, etc.), respond with: "Currently we only support BSC (Binance Smart Chain). All trading strategies and token searches are performed on BSC."
- Never search or recommend tokens on other chains
- The search_tokens tool defaults to BSC, never change this
Your response must be valid JSON with exactly this structure:
{
"thinking": "Your internal reasoning and analysis (what you're thinking about)",
"response": "Your actual response to the user (be concise and helpful)",
"strategy_update": null or {
"conditions": [{"type": "price_drop" | "price_rise" | "volume_spike" | "price_level", "token": "TOKEN_SYMBOL", "token_address": null, "threshold": number, ...}],
"actions": [{"type": "buy" | "sell" | "hold", "amount_percent": number, ...}],
"risk_management": {"stop_loss_percent": number, "take_profit_percent": number}
}
}
Guidelines:
- "thinking" should be detailed reasoning about the user's request
- "response" should be conversational and clear
- "strategy_update" should be populated ONLY when the user provides specific trading parameters (percentages, tokens, conditions, etc.)
- IMPORTANT: When a token is mentioned, set "token_address": null and ask user to confirm the token address before saving. Your response should say something like: "I need to confirm the token address. Could you provide the contract address for [TOKEN]?"
- If no strategy parameters are provided, set "strategy_update" to null
- Be friendly, concise, and helpful in your response
Example 1 (no strategy update):
User: "What can this bot do?"
{
"thinking": "The user is asking about the bot's capabilities. I should explain the main features.",
"response": "Randebu is your AI trading assistant! It can monitor cryptocurrency prices and execute trades based on your configured strategies. Tell me your trading parameters and I'll set them up for you.",
"strategy_update": null
}
Example 2 (token needs confirmation):
User: "I want to buy PEPE when it drops 10%"
{
"thinking": "User wants to buy PEPE. I need the token contract address to proceed. I should ask for confirmation.",
"response": "I'd be happy to set up a buy order for PEPE! However, I need to confirm the token contract address. Could you provide the BSC contract address for PEPE? (It usually starts with 0x...)",
"strategy_update": {
"conditions": [{"type": "price_drop", "token": "PEPE", "token_address": null, "threshold": 10}],
"actions": [{"type": "buy", "amount_percent": 100}],
"risk_management": null
}
}
Example 3 (with token address provided by user):
User: "Buy 0x6982508145454Ce125dDE157d8d64a26D53f60a2 when it drops 10%"
{
"thinking": "User provided a contract address, I can use it directly.",
"response": "Perfect! I've configured your strategy to buy the token when it drops 10%.",
"strategy_update": {
"conditions": [{"type": "price_drop", "token": "TOKEN", "token_address": "0x6982508145454Ce125dDE157d8d64a26D53f60a2", "threshold": 10}],
"actions": [{"type": "buy", "amount_percent": 100}],
"risk_management": null
}
}"""
TOOLS = [
{
"type": "function",
"function": {
"name": "search_tokens",
"description": "Search for tokens by keyword on BSC blockchain. Use this when user asks to search for a specific token or find tokens by name/symbol.",
"parameters": {
"type": "object",
"properties": {
"keyword": {
"type": "string",
"description": "Token symbol or name to search for (e.g., 'PEPE', 'BTC')",
},
"limit": {
"type": "integer",
"description": "Number of tokens to return (default: 10)",
"default": 10,
},
},
"required": ["keyword"],
},
},
},
{
"type": "function",
"function": {
"name": "get_token",
"description": "Get detailed information about a specific token including price, market cap, and pairs. Use when user asks for token details or wants to find a specific token by contract address.",
"parameters": {
"type": "object",
"properties": {
"address": {
"type": "string",
"description": "Token contract address (e.g., '0x6982508145454Ce125dDE157d8d64a26D53f60a2')",
},
"chain": {
"type": "string",
"description": "Blockchain chain (default: bsc)",
"default": "bsc",
},
},
"required": ["address"],
},
},
},
{
"type": "function",
"function": {
"name": "get_price",
"description": "Get current price(s) for tokens. Use when user asks for token price or wants to compare prices of multiple tokens.",
"parameters": {
"type": "object",
"properties": {
"token_ids": {
"type": "string",
"description": "Comma-separated list of token IDs with chain suffix (e.g., 'PEPE-bsc,TRUMP-bsc')",
}
},
"required": ["token_ids"],
},
},
},
{
"type": "function",
"function": {
"name": "get_risk",
"description": "Get risk analysis for a token contract. Use when user asks about token risk, honeypot analysis, or safety assessment before trading.",
"parameters": {
"type": "object",
"properties": {
"address": {
"type": "string",
"description": "Token contract address (e.g., '0x6982508145454Ce125dDE157d8d64a26D53f60a2')",
},
"chain": {
"type": "string",
"description": "Blockchain chain (default: bsc)",
"default": "bsc",
},
},
"required": ["address"],
},
},
},
{
"type": "function",
"function": {
"name": "get_trending",
"description": "Get trending tokens on a blockchain. Use when user asks what's trending, top tokens, or popular tokens right now.",
"parameters": {
"type": "object",
"properties": {
"chain": {
"type": "string",
"description": "Blockchain chain (default: bsc)",
"default": "bsc",
},
"limit": {
"type": "integer",
"description": "Number of trending tokens to return (default: 10, max: 50)",
"default": 10,
},
},
},
},
},
{
"type": "function",
"function": {
"name": "run_backtest",
"description": "Run a backtest to evaluate how the current trading strategy would have performed historically. Returns key metrics like ROI, win rate, max drawdown, etc. Use this when user asks to backtest, test strategy, or check historical performance.",
"parameters": {
"type": "object",
"properties": {
"token_address": {
"type": "string",
"description": "The BSC contract address of the token to backtest (required)",
},
"timeframe": {
"type": "string",
"description": "Timeframe for klines: '1d' (1 day), '4h' (4 hours), '1h' (1 hour), '15m' (15 minutes)",
"default": "1d",
},
"start_date": {
"type": "string",
"description": "Start date for backtest in YYYY-MM-DD format (e.g., '2024-01-01')",
},
"end_date": {
"type": "string",
"description": "End date for backtest in YYYY-MM-DD format (e.g., '2024-12-01')",
},
},
"required": ["token_address"],
},
},
},
{
"type": "function",
"function": {
"name": "manage_simulation",
"description": "Manage trading simulations: start, stop, or check status. Simulations run on real-time klines and show live portfolio updates. Use when user asks to run simulation, check simulation status, or stop simulation.",
"parameters": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["start", "stop", "status", "results"],
"description": "Action to perform: 'start' (begin new simulation), 'stop' (stop running simulation), 'status' (check if simulation is running), 'results' (get results from current or latest simulation)",
},
"token_address": {
"type": "string",
"description": "Token contract address for simulation (required for 'start' action)",
},
"kline_interval": {
"type": "string",
"description": "Kline interval: '1m', '5m', '15m', '1h' (default: '1m')",
"default": "1m",
},
},
"required": ["action"],
},
},
},
{
"type": "function",
"function": {
"name": "create_bot",
"description": "Create a new trading bot. Use this when user wants to create a new trading bot. Returns the bot ID and confirmation.",
"parameters": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Name for the new bot (required)",
},
"strategy": {
"type": "string",
"description": "Trading strategy description in plain English (optional, can be set later)",
},
},
"required": ["name"],
},
},
},
{
"type": "function",
"function": {
"name": "list_bots",
"description": "List all trading bots owned by the user. Use this when user wants to see their bots or asks which bots they have.",
"parameters": {
"type": "object",
"properties": {},
},
},
},
{
"type": "function",
"function": {
"name": "set_bot",
"description": "Set (associate) a bot with the current conversation. Use this when user wants to switch which bot they're working with.",
"parameters": {
"type": "object",
"properties": {
"bot_id": {
"type": "string",
"description": "ID of the bot to set for this conversation (required)",
},
},
"required": ["bot_id"],
},
},
},
{
"type": "function",
"function": {
"name": "get_bot_info",
"description": "Get details of a specific bot including name, strategy, and status. Use this when user wants to see details of a bot.",
"parameters": {
"type": "object",
"properties": {
"bot_id": {
"type": "string",
"description": "ID of the bot to get info for (optional, defaults to current bot)",
},
},
},
},
},
{
"type": "function",
"function": {
"name": "update_strategy",
"description": "Update (save) the trading strategy for a bot. This SAVES the strategy to the database. ALWAYS call this tool when user wants to configure or update a trading strategy. The strategy will be persisted and used for backtests.",
"parameters": {
"type": "object",
"properties": {
"strategy": {
"type": "string",
"description": "Description of the strategy (e.g., 'Dip buying strategy', 'Mean reversion')",
},
"conditions": {
"type": "array",
"description": "Array of condition objects. Each condition has: type (price_drop, price_rise, volume_spike, price_level), token, token_address, threshold",
"items": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["price_drop", "price_rise", "volume_spike", "price_level"],
"description": "Type of condition"
},
"token": {"type": "string", "description": "Token symbol (e.g., 'SHIB', 'PEPE')"},
"token_address": {"type": "string", "description": "Token contract address on BSC (e.g., '0x...') - REQUIRED"},
"threshold": {"type": "number", "description": "Threshold value (e.g., 5 for 5% drop/rise)"},
},
"required": ["type", "token_address", "threshold"]
}
},
"actions": {
"type": "array",
"description": "Array of action objects. Each action has: type (buy, sell, hold), amount_percent",
"items": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["buy", "sell", "hold"],
"description": "Type of action"
},
"amount_percent": {"type": "number", "description": "Percentage of funds to use (e.g., 20 for 20%)"},
},
"required": ["type", "amount_percent"]
}
},
"stop_loss": {"type": "number", "description": "Stop loss percentage (e.g., 15 for 15% loss)"},
"take_profit": {"type": "number", "description": "Take profit percentage (e.g., 20 for 20% gain)"},
},
"required": ["conditions", "actions"]
},
},
},
]
SYSTEM_PROMPT_WITH_TOOLS = (
SYSTEM_PROMPT
+ """
CRITICAL INSTRUCTIONS:
1. When user asks to run a backtest or simulation, first check if a bot exists using list_bots.
2. If no bot exists, ASK THE USER what they want to name their bot (e.g., "What would you like to name your trading bot?").
3. When user provides a bot name (after being asked), call create_bot with that name.
4. If a bot exists but has NO STRATEGY SET, the user MUST set up a strategy before running backtests. Ask the user for their trading strategy (e.g., "What token should I monitor?", "What price drop percentage should trigger a buy?", "What percentage of funds should be used?"). Help them configure the strategy.
5. IMPORTANT: When configuring a strategy, you MUST call the update_strategy tool with COMPLETE details:
- conditions: Array of {type: "price_drop"|"price_rise"|"volume_spike", token: "SYMBOL", token_address: "0x...", threshold: number}
- actions: Array of {type: "buy"|"sell", amount_percent: number}
- stop_loss: number (e.g., 5 for 5%)
- take_profit: number (e.g., 15 for 15%)
- ALWAYS include the token_address from search results when configuring strategy!
6. IMPORTANT: After executing ANY tool, you MUST incorporate the ACTUAL tool result into your response. Do NOT ignore what the tool returned. If the tool returned an error, you MUST tell the user about the error - do NOT pretend the operation succeeded.
7. NEVER tell users about internal tool names like "create_bot", "list_bots", etc. Use natural language instead.
8. NEVER say "Let me..." or "I'll..." - IMMEDIATELY call the appropriate tool. If user asks for trending tokens, call get_trending NOW. If user asks for token info, call get_token NOW. Do NOT ask for permission or say you will do something - just do it.
9. When asking for information from the user, be specific and actionable (e.g., "What token do you want to backtest?", "What would you like to name your bot?").
10. If user asks you to look up/search/find tokens, IMMEDIATELY call search_tokens or get_trending tool. Do not ask follow-up questions first.
11. IMPORTANT: When user says they want to use a token from search results (e.g., "that main PEPE" or "the first one"), ALWAYS extract the token_address from the search results and include it in update_strategy. Do NOT ask for the address again!
You have access to tools:
- search_tokens(keyword, limit): Search for tokens by keyword/symbol.
- get_token(address, chain): Get detailed token info.
- get_price(token_ids): Get current token prices.
- get_risk(address, chain): Get risk/honeypot analysis.
- get_trending(chain, limit): Get trending tokens.
- run_backtest(token_address, timeframe, start_date, end_date): Run backtest. REQUIRES a bot to be set first.
- manage_simulation(action, token_address, kline_interval): Manage simulations. REQUIRES a bot.
- create_bot(name, strategy): Create a new trading bot.
- list_bots(): List user's bots.
- set_bot(bot_id): Switch bots in conversation.
- get_bot_info(bot_id): Get bot details including strategy conditions and actions.
- update_strategy(conditions, actions, stop_loss, take_profit): Save trading strategy to bot. MUST include token_address in conditions!
Take action immediately. Do not ask for confirmation. Do not describe what you will do - just do it.
"""
)
class MiniMaxClient:
"""Client for MiniMax extended thinking API."""
def __init__(self, api_key: str, model: str = "MiniMax-M2.7"):
self.api_key = api_key
self.model = model
self.endpoint = "https://api.minimax.io/v1/text/chatcompletion_v2"
def chat(
self,
messages: List[Dict[str, str]],
system_prompt: str,
tools: Optional[List[Dict[str, Any]]] = None,
temperature: float = 0.7,
max_tokens: int = 3000,
thinking_budget: int = 1500,
) -> Dict[str, Any]:
"""Send a chat request to MiniMax API."""
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
}
all_messages = [{"role": "system", "content": system_prompt}] + messages
payload = {
"model": self.model,
"messages": all_messages,
"temperature": temperature,
"max_tokens": max_tokens,
"thinking": {"type": "human", "budget_tokens": thinking_budget},
}
if tools:
payload["tools"] = tools
resp = requests.post(self.endpoint, headers=headers, json=payload)
# Check for HTTP errors
if resp.status_code != 200:
error_text = resp.text
print(f"API Error {resp.status_code}: {error_text[:500]}")
return {"error": f"API returned {resp.status_code}: {error_text[:200]}"}
return resp.json() or {}
def check_connection(self) -> bool:
"""Check if API is reachable."""
try:
resp = requests.post(
self.endpoint,
headers={"Authorization": f"Bearer {self.api_key}"},
json={
"model": self.model,
"messages": [{"role": "user", "content": "ping"}],
},
timeout=10,
)
return resp.status_code == 200
except Exception:
return False

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,83 @@
"""Help formatters for slash commands and tool documentation."""
from typing import Optional
from .tools import get_tool_registry, SKILL_EMOJIS
def format_tools_list() -> str:
"""Format the tool registry as a help message."""
message = "📋 Available Tools\n\n"
for category in ["randebu", "ave"]:
tools = get_tool_registry().get(category, [])
if category == "randebu":
message += "🤖 Randebu Built-in:\n"
else:
message += "☁️ AVE Cloud Skills:\n"
for tool in tools:
message += f"{tool['command']} - {tool['description']}\n"
message += "\n"
message = (
message.rstrip() + "\n\nType /<tool-name> for detailed help on a specific tool."
)
return message
def format_skill_acknowledgment(tool_name: str, description: str) -> str:
"""Format a brief acknowledgment when a skill is activated."""
emoji = SKILL_EMOJIS.get(tool_name.lower(), "")
return f"{emoji} **{tool_name}** loaded. Ready for *{description}*, ask me away!"
def format_tool_help(tool_name: str) -> str:
"""Format detailed help for a specific tool."""
tool_name = tool_name.lstrip("/")
for category in ["randebu", "ave"]:
for tool in get_tool_registry().get(category, []):
if tool["name"].lower() == tool_name.lower():
cat_label = (
"Randebu Built-in" if category == "randebu" else "AVE Cloud Skill"
)
details = tool["details"]
message = (
f"🔍 {tool['command']} - {details['description']} ({cat_label})\n\n"
)
message += f"**Description:** {details['description']}\n"
message += f"**Commands:**\n {details['usage']}\n\n"
message += f"**Example:**\n```\n{details['example']}\n```"
return message
return f"Tool '{tool_name}' not found. Type / to see all available tools."
def format_general_help() -> str:
"""Format general help about Randebu."""
return """🤖 **Randebu - AI Trading Assistant**
Randebu is your AI trading assistant that helps you manage your trading bots on BSC (Binance Smart Chain).
**Getting Started:**
1. Create a bot on the dashboard
2. Describe your trading strategy in plain English
3. Run backtests to validate your strategy
4. Start simulations to see live trading
**Example Strategies:**
- "Buy PEPE when it drops 5%"
- "Sell if price rises 10% within 1 hour"
- "Buy when volume spikes by 200%"
**Slash Commands:**
- `/` - Show all available tools
- `/help` - Show this help message
- `/<tool-name>` - Get help on a specific tool
**Natural Language:**
You can also just describe what you want in natural language. For example:
- "What's the price of PEPE?"
- "Run a backtest on 0x... token"
- "Start a simulation on TRUMP"
"""

View File

@@ -0,0 +1,164 @@
"""Mock client for testing the ConversationalAgent without hitting real APIs."""
from typing import List, Dict, Any, Optional
class MockMiniMaxClient:
"""Mock client that returns predefined responses for testing.
Usage:
mock = MockMiniMaxClient()
mock.add_response({\"choices\": [...]}) # Add responses in order
mock.add_response({\"choices\": [...]}) # Second call gets this
agent = ConversationalAgent(client=mock)
result = agent.chat(\"hello\")
"""
def __init__(self, responses: List[Dict[str, Any]] = None):
self.responses = responses or []
self.call_count = 0
self.calls: List[Dict[str, Any]] = [] # Record all calls for assertions
def add_response(self, response: Dict[str, Any]):
"""Add a response to be returned on the next call."""
self.responses.append(response)
def chat(
self,
messages: List[Dict[str, str]],
system_prompt: str,
tools: Optional[List[Dict[str, Any]]] = None,
temperature: float = 0.7,
max_tokens: int = 2000,
thinking_budget: int = 1500,
) -> Dict[str, Any]:
"""Return the next predefined response."""
# Record the call for debugging/tests
self.calls.append({
"messages": messages,
"system_prompt": system_prompt[:100] if system_prompt else None,
"tool_calls_count": len(tools) if tools else 0,
})
if self.call_count < len(self.responses):
response = self.responses[self.call_count]
self.call_count += 1
return response
# Default response if no more predefined responses
return {
"choices": [{
"message": {
"content": "Mock response - no more responses configured",
"role": "assistant",
}
}]
}
def reset(self):
"""Reset call count and calls list."""
self.call_count = 0
self.calls = []
def verify_call(self, call_index: int, expected_messages: int = None, expected_tool_count: int = None):
"""Verify a specific call was made correctly."""
if call_index >= len(self.calls):
raise AssertionError(f"Call {call_index} was not made. Total calls: {len(self.calls)}")
call = self.calls[call_index]
if expected_messages is not None:
actual = len(call["messages"])
if actual != expected_messages:
raise AssertionError(
f"Call {call_index}: expected {expected_messages} messages, got {actual}"
)
if expected_tool_count is not None:
actual = call["tool_calls_count"]
if actual != expected_tool_count:
raise AssertionError(
f"Call {call_index}: expected {expected_tool_count} tools, got {actual}"
)
class MockMiniMaxClientWithToolCall(MockMiniMaxClient):
"""Mock client that generates tool call responses based on message content."""
def __init__(self, tool_handlers: Dict[str, Dict[str, Any]] = None):
"""tool_handlers: dict mapping tool names to their responses."""
super().__init__()
self.tool_handlers = tool_handlers or {}
def chat(
self,
messages: List[Dict[str, str]],
system_prompt: str,
tools: Optional[List[Dict[str, Any]]] = None,
temperature: float = 0.7,
max_tokens: int = 2000,
thinking_budget: int = 1500,
) -> Dict[str, Any]:
"""Check if last message contains a tool call request and return appropriate response."""
self.calls.append({
"messages": messages,
"system_prompt": system_prompt[:100] if system_prompt else None,
"tool_calls_count": len(tools) if tools else 0,
})
# Get the last message
if not messages:
return {"choices": [{"message": {"content": "No messages", "role": "assistant"}}]}
last_msg = messages[-1]
# If it's a tool result, look for the tool that was called
if last_msg.get("role") == "user" and "[TOOL RESULT]" in last_msg.get("content", ""):
# Extract tool name from the content
content = last_msg["content"]
# Format: [TOOL RESULT] tool_name: result
for tool_name in self.tool_handlers:
if f"[TOOL RESULT] {tool_name}:" in content:
return self.tool_handlers[tool_name]
# Check if we should generate a tool call
last_user_msg = ""
for msg in reversed(messages):
if msg.get("role") == "user" and "[TOOL RESULT]" not in msg.get("content", ""):
last_user_msg = msg.get("content", "")
break
# Check each tool's trigger
for tool_name, handler in self.tool_handlers.items():
trigger = handler.get("trigger", "")
if trigger and trigger.lower() in last_user_msg.lower():
return {
"choices": [{
"message": {
"content": handler.get("content", ""),
"role": "assistant",
"tool_calls": [{
"id": f"call_{tool_name}",
"type": "function",
"function": {
"name": tool_name,
"arguments": handler.get("arguments", "{}")
}
}]
}
}]
}
# Default: return first available response or empty
if self.responses:
response = self.responses[0]
self.call_count += 1
return response
return {
"choices": [{
"message": {
"content": "How can I help you with your trading bot?",
"role": "assistant",
}
}]
}

View File

@@ -0,0 +1,172 @@
"""Tool registry and definitions for the conversational agent."""
from typing import Dict, Any, List
TOOL_REGISTRY: Dict[str, Any] = {
"randebu": [
{
"name": "backtest",
"description": "Run strategy backtest",
"category": "Randebu Built-in",
"command": "/backtest",
"details": {
"description": "Run a backtest to evaluate how the current trading strategy would have performed historically.",
"usage": "/backtest [token_address] [--timeframe 1d|4h|1h|15m] [--start YYYY-MM-DD] [--end YYYY-MM-DD]",
"example": "Run a backtest on PEPE for the last 30 days",
},
},
{
"name": "simulate",
"description": "Start/stop simulation",
"category": "Randebu Built-in",
"command": "/simulate",
"details": {
"description": "Start or stop trading simulations that run on real-time klines.",
"usage": "/simulate start|stop|status|results [token_address]",
"example": "Start a simulation on PEPE",
},
},
{
"name": "strategy",
"description": "View/update strategy",
"category": "Randebu Built-in",
"command": "/strategy",
"details": {
"description": "View your current trading strategy or update it with new parameters.",
"usage": "Describe your strategy in plain English, e.g., 'Buy PEPE when price drops 5%'",
"example": "Buy PEPE when it drops 10% within 1 hour",
},
},
{
"name": "create_bot",
"description": "Create a new trading bot",
"category": "Randebu Built-in",
"command": None,
"details": {
"description": "Create a new trading bot linked to the current conversation.",
"usage": "create_bot <name> [--strategy <strategy_desc>]",
"example": "create_bot MyBot --strategy Buy PEPE when it drops 5%",
},
},
{
"name": "list_bots",
"description": "List your trading bots",
"category": "Randebu Built-in",
"command": None,
"details": {
"description": "List all trading bots you own.",
"usage": "list_bots",
"example": "list_bots",
},
},
{
"name": "set_bot",
"description": "Set bot for this conversation",
"category": "Randebu Built-in",
"command": None,
"details": {
"description": "Associate a bot with the current conversation.",
"usage": "set_bot <bot_id>",
"example": "set_bot abc-123-def",
},
},
{
"name": "get_bot_info",
"description": "Get current bot details",
"category": "Randebu Built-in",
"command": None,
"details": {
"description": "Get details of the current bot for display in the right pane.",
"usage": "get_bot_info [bot_id]",
"example": "get_bot_info abc-123-def",
},
},
],
"ave": [
{
"name": "search",
"description": "Token search",
"category": "AVE Cloud Skills",
"command": "/search",
"details": {
"description": "Find tokens by keyword, symbol, or contract address on BSC.",
"usage": "search <keyword> [--chain bsc] [--limit 20]",
"example": "search PEPE\nsearch 0x1234... --chain bsc",
},
},
{
"name": "trending",
"description": "Popular tokens",
"category": "AVE Cloud Skills",
"command": "/trending",
"details": {
"description": "Get list of trending/popular tokens on BSC.",
"usage": "trending [--chain bsc] [--limit 20]",
"example": "trending --chain bsc\ntrending --limit 10",
},
},
{
"name": "risk",
"description": "Honeypot detection",
"category": "AVE Cloud Skills",
"command": "/risk",
"details": {
"description": "Get risk analysis for a token contract including honeypot assessment.",
"usage": "risk <token_address> [--chain bsc]",
"example": "risk 0x6982508145454Ce125dDE157d8d64a26D53f60a2",
},
},
{
"name": "token",
"description": "Token details",
"category": "AVE Cloud Skills",
"command": "/token",
"details": {
"description": "Get detailed information about a specific token including price, market cap, and pairs.",
"usage": "token <address> [--chain bsc]",
"example": "token 0x6982508145454Ce125dDE157d8d64a26D53f60a2",
},
},
{
"name": "price",
"description": "Batch prices",
"category": "AVE Cloud Skills",
"command": "/price",
"details": {
"description": "Get current price(s) for multiple tokens.",
"usage": "price <token_id>,<token_id>,... (e.g., PEPE-bsc,TRUMP-bsc)",
"example": "price PEPE-bsc,TRUMP-bsc",
},
},
],
}
SKILL_EMOJIS: Dict[str, str] = {
"backtest": "📊",
"simulate": "🎮",
"strategy": "📝",
"search": "🔍",
"trending": "📈",
"risk": "📉",
"token": "🪙",
"price": "💰",
}
def get_tool_registry() -> Dict[str, Any]:
"""Return the tool registry for slash command help."""
return TOOL_REGISTRY
def get_tools_by_category(category: str) -> List[Dict[str, Any]]:
"""Get tools filtered by category."""
return TOOL_REGISTRY.get(category, [])
def get_tool_by_name(tool_name: str) -> Dict[str, Any]:
"""Get a tool by its name."""
for category in ["randebu", "ave"]:
for tool in TOOL_REGISTRY.get(category, []):
if tool["name"].lower() == tool_name.lower():
return tool
return None

View File

@@ -93,6 +93,32 @@ class BacktestEngine:
self.results = {"error": "No kline data available"}
return self.results
# Debug: log first and last few klines to verify price data
print(f"DEBUG BacktestEngine: Got {len(klines)} klines for {token_id}")
if klines:
print(f"DEBUG BacktestEngine: First kline: {klines[0]}")
print(f"DEBUG BacktestEngine: Last kline: {klines[-1]}")
# Validate Kline data - check for obviously wrong prices
first_close = float(klines[0].get('close', 0))
last_close = float(klines[-1].get('close', 0))
print(f"DEBUG BacktestEngine: first_close={first_close}, last_close={last_close}")
# If price changes by more than 1000x, data is likely wrong
if first_close > 0 and last_close > 0:
price_ratio = max(first_close, last_close) / min(first_close, last_close)
print(f"DEBUG BacktestEngine: price_ratio={price_ratio:.0f}x")
if price_ratio > 1000:
self.status = "failed"
self.results = {
"error": f"Kline data appears incorrect. Price changed by {price_ratio:.0f}x during the period. "
f"First price: ${first_close:.8f}, Last price: ${last_close:.8f}. "
f"This may be due to incorrect token data from the API. Please try a different token or timeframe."
}
return self.results
await self._process_klines(klines)
self._calculate_metrics()
self.status = "completed"
@@ -139,6 +165,17 @@ class BacktestEngine:
async def _process_klines(self, klines: List[Dict[str, Any]]):
self.total_klines = len(klines)
# Debug: log strategy config
print(f"DEBUG _process_klines: {len(klines)} klines to process")
print(f"DEBUG _process_klines: conditions = {self.conditions}")
print(f"DEBUG _process_klines: actions = {self.actions}")
print(f"DEBUG _process_klines: stop_loss_percent = {self.stop_loss_percent}")
print(f"DEBUG _process_klines: take_profit_percent = {self.take_profit_percent}")
# Count price drops for debugging
dip_opportunities = 0
for i, kline in enumerate(klines):
if not self.running:
break
@@ -149,21 +186,29 @@ class BacktestEngine:
if price <= 0:
continue
self.last_kline_price = price # Track last price for open position valuation
self.last_kline_price = price # Track last price for mark to market
timestamp = kline.get("timestamp", 0)
if self.position > 0 and self.entry_price is not None:
exit_info = self._check_risk_management(price, timestamp)
if exit_info:
print(f"DEBUG: Kline {i} - Risk exit triggered: {exit_info['reason']} at price {price}")
await self._execute_risk_exit(price, timestamp, exit_info)
continue
# Check each condition
for condition in self.conditions:
if self._check_condition(condition, klines, i, price):
cond_result = self._check_condition(condition, klines, i, price)
if cond_result:
dip_opportunities += 1
if self.position == 0:
print(f"DEBUG: Kline {i} - BUY condition triggered: {condition['type']} at price {price}")
await self._execute_actions(price, timestamp, condition)
break
print(f"DEBUG _process_klines: Total dip opportunities: {dip_opportunities}")
@property
def average_entry_price(self) -> Optional[float]:
"""Calculate weighted average entry price based on cost basis."""
@@ -249,6 +294,9 @@ class BacktestEngine:
if prev_price <= 0:
return False
drop_pct = ((prev_price - current_price) / prev_price) * 100
# Debug first few to see what's happening
if current_idx < 5 or drop_pct >= threshold:
print(f"DEBUG _check_condition: idx={current_idx}, prev={prev_price}, curr={current_price}, drop={drop_pct:.4f}%, threshold={threshold}, trigger={drop_pct >= threshold}")
return drop_pct >= threshold
elif cond_type == "price_rise":
@@ -291,6 +339,8 @@ class BacktestEngine:
amount = self.current_balance * (amount_percent / 100)
if action_type == "buy" and self.current_balance >= amount:
# Buy if we have funds available (supports DCA - buy more on each dip)
# position > 0 just means we already have some tokens, we can still buy more
quantity = amount / price
self.position += quantity
self.current_balance -= amount
@@ -298,6 +348,7 @@ class BacktestEngine:
self.position_token = token
self.entry_price = price # Keep last entry price for reference
self.entry_time = timestamp
print(f"DEBUG _execute_actions: BUY - amount=${amount:.2f}, price={price}, quantity={quantity}, position={self.position}")
self.trades.append(
{
"type": "buy",
@@ -324,21 +375,35 @@ class BacktestEngine:
)
elif action_type == "sell" and self.position > 0:
sell_amount = self.position * price
# Sell amount_percent of current position (default 100% if not specified)
sell_percent = action.get("amount_percent", 100) / 100.0
sell_quantity = self.position * sell_percent
sell_amount = sell_quantity * price
self.current_balance += sell_amount
# Proportionally reduce cost_basis
sold_cost_basis = self.cost_basis * sell_percent
self.cost_basis -= sold_cost_basis
print(f"DEBUG _execute_actions: SELL - position={self.position}, sell_percent={sell_percent*100}%, quantity={sell_quantity}, price={price}, sell_amount=${sell_amount:.2f}")
self.trades.append(
{
"type": "sell",
"token": self.position_token,
"price": price,
"amount": sell_amount,
"quantity": self.position,
"quantity": sell_quantity,
"timestamp": timestamp,
"exit_reason": "manual",
}
)
# Update remaining position
self.position -= sell_quantity
if self.position <= 0.00000001: # Account for floating point
self.position = 0
self.entry_price = None
self.cost_basis = 0.0
self.entry_time = None
self.signals.append(
{
@@ -356,21 +421,49 @@ class BacktestEngine:
)
def _calculate_metrics(self):
# Debug: log all trades for analysis
print(f"DEBUG _calculate_metrics: {len(self.trades)} total trades")
buy_trades = [t for t in self.trades if t["type"] == "buy"]
sell_trades = [t for t in self.trades if t["type"] == "sell"]
print(f" Buy trades: {len(buy_trades)}")
print(f" Sell trades: {len(sell_trades)}")
if buy_trades:
print(f" First buy: amount=${buy_trades[0]['amount']:.2f}, price={buy_trades[0]['price']}, quantity={buy_trades[0]['quantity']}")
print(f" Last buy: amount=${buy_trades[-1]['amount']:.2f}, price={buy_trades[-1]['price']}, quantity={buy_trades[-1]['quantity']}")
if sell_trades:
print(f" First sell: amount=${sell_trades[0]['amount']:.2f}, price={sell_trades[0]['price']}, exit_reason={sell_trades[0].get('exit_reason')}")
print(f" Last sell: amount=${sell_trades[-1]['amount']:.2f}, price={sell_trades[-1]['price']}, exit_reason={sell_trades[-1].get('exit_reason')}")
# For open positions, use the last kline price to mark to market
# If no last kline price, fall back to entry price
position_price = self.last_kline_price
if position_price is None and self.trades and self.position > 0:
position_price = self.trades[-1]["price"] # Fall back to entry price
# Debug logging
print(f"DEBUG _calculate_metrics:")
print(f" initial_balance: {self.initial_balance}")
print(f" current_balance: {self.current_balance}")
print(f" position: {self.position}")
print(f" position_price: {position_price}")
print(f" last_kline_price: {self.last_kline_price}")
# Calculate final balance: use marked-to-market value if position open, otherwise current balance
if self.position > 0 and position_price:
final_balance = self.current_balance + self.position * position_price
else:
final_balance = self.current_balance
print(f" final_balance calculated: {final_balance}")
total_return = (
(final_balance - self.initial_balance) / self.initial_balance
) * 100
print(f" total_return calculated: {total_return}%")
buy_trades = [t for t in self.trades if t["type"] == "buy"]
sell_trades = [t for t in self.trades if t["type"] == "sell"]
total_trades = len(buy_trades) + len(sell_trades)

View File

@@ -0,0 +1,95 @@
import os
from datetime import datetime, timedelta
from sqlalchemy import func
from fastapi import HTTPException
from ..db.models import Message, AnonymousUser
MAX_CHATS_PER_5HOURS = int(os.getenv("MAX_CHATS_PER_5HOURS", "500"))
MAX_ANONYMOUS_CHATS = 50
MAX_ANONYMOUS_BOTS = 1
MAX_ANONYMOUS_BACKTESTS = 1
class RateLimiter:
@staticmethod
def check_system_limit(db):
cutoff = datetime.utcnow() - timedelta(hours=5)
count = (
db.query(func.count(Message.id))
.filter(Message.created_at >= cutoff)
.scalar()
)
if count >= MAX_CHATS_PER_5HOURS:
raise HTTPException(
status_code=429,
detail="Rate limited from the agent service. Please come back later.",
)
@staticmethod
def check_anonymous_limit(db, anonymous_token: str):
anon = (
db.query(AnonymousUser).filter(AnonymousUser.id == anonymous_token).first()
)
if anon and anon.chat_count >= MAX_ANONYMOUS_CHATS:
raise HTTPException(
status_code=403,
detail="You've reached the limit. Please create an account to continue.",
)
return anon
@staticmethod
def check_anonymous_bot_limit(db, anonymous_token: str):
anon = (
db.query(AnonymousUser).filter(AnonymousUser.id == anonymous_token).first()
)
if anon and anon.bot_created:
raise HTTPException(
status_code=403,
detail="You've reached the limit. Please create an account to continue.",
)
@staticmethod
def check_anonymous_backtest_limit(db, anonymous_token: str):
anon = (
db.query(AnonymousUser).filter(AnonymousUser.id == anonymous_token).first()
)
if anon and anon.backtest_count >= MAX_ANONYMOUS_BACKTESTS:
raise HTTPException(
status_code=403,
detail="You've reached the limit. Please create an account to continue.",
)
@staticmethod
def increment_chat_count(db, anonymous_token: str):
anon = (
db.query(AnonymousUser).filter(AnonymousUser.id == anonymous_token).first()
)
if anon:
anon.chat_count += 1
db.commit()
@staticmethod
def set_bot_created(db, anonymous_token: str):
anon = (
db.query(AnonymousUser).filter(AnonymousUser.id == anonymous_token).first()
)
if anon:
anon.bot_created = True
db.commit()
@staticmethod
def increment_backtest_count(db, anonymous_token: str):
anon = (
db.query(AnonymousUser).filter(AnonymousUser.id == anonymous_token).first()
)
if anon:
anon.backtest_count += 1
db.commit()

View File

@@ -0,0 +1,609 @@
"""Tests for ConversationalAgent using mock client."""
import pytest
import sys
import os
# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app.services.ai_agent.agent import ConversationalAgent
from app.services.ai_agent.mock_client import MockMiniMaxClient, MockMiniMaxClientWithToolCall
class TestConversationalAgent:
"""Test ConversationalAgent with mocked MiniMax API."""
def test_greeting_response(self):
"""Test that agent responds to greeting."""
mock = MockMiniMaxClient()
mock.add_response({
"choices": [{
"message": {
"content": "Hello! How can I help you with your trading today?",
"role": "assistant",
}
}]
})
agent = ConversationalAgent(client=mock)
result = agent.chat("Hello")
assert "Hello" in result.get("response", "")
assert mock.call_count == 1
def test_api_error_returns_error_message(self):
"""Test that when API returns an error (like 529 overloaded), we return an error message."""
mock = MockMiniMaxClient()
# API returns an error on all 3 retry attempts
for _ in range(3):
mock.add_response({
"error": "API returned 529: Server overloaded"
})
agent = ConversationalAgent(client=mock)
result = agent.chat("Hello")
# Should return error message, not empty string
response = result.get("response", "")
print(f"Response: {response}")
print(f"Call count: {mock.call_count}")
assert response != "", "Response should not be empty when API errors"
assert "trouble" in response.lower() or "error" in response.lower() or "sorry" in response.lower(), \
f"Response should mention error: {response}"
assert result.get("success") == False
def test_api_empty_choices_returns_error_message(self):
"""Test that when API returns choices=None (like 520 error), we return an error message."""
mock = MockMiniMaxClient()
# API returns empty choices on all 3 retry attempts
for _ in range(3):
mock.add_response({
"id": "test-id",
"choices": None, # Empty choices = API error
"model": "MiniMax-M2.7",
"base_resp": {"status_code": 1000, "status_msg": "unknown error, 520"}
})
agent = ConversationalAgent(client=mock)
result = agent.chat("Hello")
# Should return error message, not empty string
response = result.get("response", "")
print(f"Response: {response}")
print(f"Call count: {mock.call_count}")
assert response != "", "Response should not be empty when API returns empty choices"
assert "trouble" in response.lower() or "error" in response.lower() or "sorry" in response.lower(), \
f"Response should mention error: {response}"
assert result.get("success") == False
def test_tool_call_list_bots(self):
"""Test that agent calls list_bots tool when asked about bots."""
mock = MockMiniMaxClient()
# First call: model decides to call list_bots
mock.add_response({
"choices": [{
"finish_reason": "tool_calls",
"message": {
"content": "",
"role": "assistant",
"tool_calls": [{
"id": "call_1",
"type": "function",
"function": {
"name": "list_bots",
"arguments": "{}"
}
}]
}
}]
})
# Second call: after tool result, model gives final response
mock.add_response({
"choices": [{
"message": {
"content": "You don't have any bots yet. Would you like to create one?",
"role": "assistant",
}
}]
})
# Pass anonymous_token so _execute_list_bots doesn't return error
agent = ConversationalAgent(client=mock, anonymous_token="test-token")
result = agent.chat("What bots do I have?")
assert mock.call_count == 2
# The response should be from the second call
assert "bot" in result.get("response", "").lower()
def test_tool_result_with_empty_content_returns_tool_result(self):
"""Test that if second API call returns empty content but has tool_calls, we fallback to tool result."""
mock = MockMiniMaxClient()
# First call: model calls list_bots
mock.add_response({
"choices": [{
"finish_reason": "tool_calls",
"message": {
"content": "",
"role": "assistant",
"tool_calls": [{
"id": "call_1",
"type": "function",
"function": {
"name": "list_bots",
"arguments": "{}"
}
}]
}
}]
})
# Second call: model calls ANOTHER tool (not providing text)
mock.add_response({
"choices": [{
"finish_reason": "tool_calls",
"message": {
"content": "\n", # Whitespace only
"role": "assistant",
"tool_calls": [{
"id": "call_2",
"type": "function",
"function": {
"name": "get_bot_info",
"arguments": "{}"
}
}]
}
}]
})
agent = ConversationalAgent(client=mock)
result = agent.chat("What bots do I have?")
# Should fallback to the tool result text, not empty string
assert result.get("response", "") != ""
def test_content_with_tool_calls_returns_content(self):
"""Test that if second API call returns BOTH content AND tool_calls, we return the content.
This tests the exact scenario from production:
- Tool result: 'Backtest failed: Token address not found...'
- Model response: 'Got it! Running the backtest now.' (with tool_calls)
- Expected: Since tool result is an ERROR, we should return the error, NOT model content
"""
mock = MockMiniMaxClient()
# First call: model calls run_backtest
mock.add_response({
"choices": [{
"finish_reason": "tool_calls",
"message": {
"content": "",
"role": "assistant",
"tool_calls": [{
"id": "call_1",
"type": "function",
"function": {
"name": "run_backtest",
"arguments": '{"token_address": "0x..."}'
}
}]
}
}]
})
# Second call: model returns misleading positive content AND has tool_calls
# But tool result was an ERROR, so we should return the error
mock.add_response({
"choices": [{
"finish_reason": "tool_calls",
"message": {
"content": "Got it! Running the backtest now.", # Misleading!
"role": "assistant",
"tool_calls": [{
"id": "call_2",
"type": "function",
"function": {
"name": "get_bot_info",
"arguments": "{}"
}
}]
}
}]
})
agent = ConversationalAgent(
client=mock,
conversation_id="test-conv",
anonymous_token="test-token"
)
result = agent.chat("Run backtest on SHIB")
# Since tool result is an error, we should return the ERROR, not model content
response = result.get("response", "")
print(f"Response: '{response}'")
# The key assertion: tool result was an error, so we should return the error
assert "not found" in response.lower() or "error" in response.lower() or "couldn't" in response.lower(), \
f"Expected error from tool result, got: {response}"
assert "Got it" not in response, f"Should NOT return misleading positive content"
def test_content_without_tool_calls_returns_content(self):
"""Test that if second API call returns content WITHOUT tool_calls, we return the content.
Note: This test uses list_bots which returns a friendly message, not an error."""
mock = MockMiniMaxClient()
# First call: model calls list_bots
mock.add_response({
"choices": [{
"finish_reason": "tool_calls",
"message": {
"content": "",
"role": "assistant",
"tool_calls": [{
"id": "call_1",
"type": "function",
"function": {
"name": "list_bots",
"arguments": '{}'
}
}]
}
}]
})
# Second call: model returns ONLY content, no tool_calls
# Tool result was "You don't have any bots yet" (not an error keyword), use model content
mock.add_response({
"choices": [{
"finish_reason": "stop",
"message": {
"content": "You don't have any bots. Would you like to create one?", # Content only
"role": "assistant",
}
}]
})
agent = ConversationalAgent(
client=mock,
conversation_id="test-conv",
anonymous_token="test-token"
)
result = agent.chat("What bots do I have?")
response = result.get("response", "")
print(f"Response: '{response}'")
assert "You don't have any bots" in response
def test_second_api_call_error_returns_tool_result(self):
"""Test that if second API call (in _send_tool_result_to_model) returns error, we return tool result."""
mock = MockMiniMaxClient()
# First call: model calls run_backtest
mock.add_response({
"choices": [{
"finish_reason": "tool_calls",
"message": {
"content": "",
"role": "assistant",
"tool_calls": [{
"id": "call_1",
"type": "function",
"function": {
"name": "run_backtest",
"arguments": '{}'
}
}]
}
}]
})
# Second call: API returns error on all 3 retry attempts
for _ in range(3):
mock.add_response({
"error": "API returned 529: Server overloaded"
})
agent = ConversationalAgent(
client=mock,
conversation_id="test-conv",
anonymous_token="test-token"
)
result = agent.chat("Run backtest")
# Should fallback to tool result (backtest not found message), not empty string
response = result.get("response", "")
print(f"Response: '{response}'")
print(f"Call count: {mock.call_count}")
assert response != "", "Response should not be empty when second API errors"
# The tool result should be "I couldn't find the bot..."
assert "bot" in response.lower() or "couldn't find" in response.lower(), \
f"Response should contain tool result: {response}"
def test_chained_tool_calls_with_empty_content(self):
"""Test that if model returns empty content but has tool_calls, we execute the next tool.
This is the exact scenario from production:
- User asks about bots
- Model calls list_bots tool
- Tool returns bot list
- Model responds with EMPTY content but has get_bot_info tool call
- We should execute get_bot_info and continue, NOT return empty string
"""
mock = MockMiniMaxClient()
# First call: model decides to call list_bots
mock.add_response({
"choices": [{
"finish_reason": "tool_calls",
"message": {
"content": "",
"role": "assistant",
"tool_calls": [{
"id": "call_1",
"type": "function",
"function": {
"name": "list_bots",
"arguments": "{}"
}
}]
}
}]
})
# Second call: model returns EMPTY content but wants to call get_bot_info
# This is the BUG scenario - model just wants to do more tool calls
mock.add_response({
"choices": [{
"finish_reason": "tool_calls",
"message": {
"content": "", # Empty content!
"role": "assistant",
"tool_calls": [{
"id": "call_2",
"type": "function",
"function": {
"name": "get_bot_info",
"arguments": '{"bot_id": "test-bot-123"}'
}
}]
}
}]
})
# Third call: after get_bot_info, model finally returns content
mock.add_response({
"choices": [{
"message": {
"content": "I found your bot 'Test Bot' with 2 strategy conditions configured.",
"role": "assistant",
}
}]
})
agent = ConversationalAgent(client=mock, anonymous_token="test-token")
result = agent.chat("Tell me about my bots")
response = result.get("response", "")
print(f"Response: '{response}'")
print(f"Call count: {mock.call_count}")
# Should NOT return empty string - should continue with tool calls
assert response != "", "Response should not be empty when model has more tool calls"
# get_bot_info returns error since bot doesn't exist in DB, but we continued the chain
# (which is the key behavior we're testing - it didn't return empty string)
assert "" in response or "bot" in response.lower(), f"Response should mention bot or error: {response}"
def test_json_response_extraction(self):
"""Test that JSON-formatted responses are properly extracted."""
mock = MockMiniMaxClient()
# Model returns JSON in code block with response field
mock.add_response({
"choices": [{
"message": {
"content": "```json\n{\n \"thinking\": \"The user wants a bot. Creating one now.\",\n \"response\": \"✅ Bot created successfully!\"\n}\n```",
"role": "assistant",
}
}]
})
agent = ConversationalAgent(client=mock)
result = agent.chat("create a bot")
response = result.get("response", "")
print(f"Response: '{response}'")
# Should extract the response field, not show JSON
assert "✅ Bot created successfully!" in response, f"Should contain bot message: {response}"
assert "thinking" not in response.lower() or "json" not in response.lower(), f"Should not contain raw JSON: {response}"
assert "```json" not in response, f"Should not contain code block markers: {response}"
def test_retry_succeeds_on_second_attempt(self):
"""Test that if first API call fails but second succeeds, we use the successful response."""
mock = MockMiniMaxClient()
# First attempt fails with error
mock.add_response({"error": "API returned 529: Server overloaded"})
# Second attempt succeeds
mock.add_response({
"choices": [{
"message": {
"content": "Hello! How can I help you?",
"role": "assistant",
}
}]
})
agent = ConversationalAgent(client=mock)
result = agent.chat("Hello")
response = result.get("response", "")
print(f"Response: '{response}'")
print(f"Call count: {mock.call_count}")
# Should use the successful response from 2nd attempt
assert "Hello" in response
assert "trouble" not in response.lower()
assert mock.call_count == 2 # Two calls: 1 error + 1 success
def test_model_json_response_is_parsed(self):
"""Test that if model returns JSON-formatted response in _send_tool_result_to_model, we extract only the response field."""
mock = MockMiniMaxClient()
# User message triggers tool call
mock.add_response({
"choices": [{
"finish_reason": "tool_calls",
"message": {
"content": "",
"role": "assistant",
"tool_calls": [{
"id": "call_1",
"type": "function",
"function": {
"name": "create_bot",
"arguments": '{"name": "TestBot"}'
}
}]
}
}]
})
# Model's second response is JSON (this is the bug scenario)
mock.add_response({
"choices": [{
"message": {
# Model returns JSON instead of plain text
"content": '{"thinking": "Bot created", "response": "Your bot TestBot is ready! What strategy?", "strategy_update": null}',
"role": "assistant",
}
}]
})
agent = ConversationalAgent(
client=mock,
conversation_id="test-conv",
anonymous_token="test-token"
)
result = agent.chat("Create a bot named TestBot")
# The response should NOT contain JSON
response_text = result.get("response", "")
print(f"Response: {response_text}")
# Should NOT contain JSON artifacts
assert "{\"thinking\":" not in response_text
assert "\"strategy_update\":" not in response_text
assert "```json" not in response_text
# Should contain the actual response text
assert "bot TestBot is ready" in response_text or "strategy" in response_text.lower()
def test_create_bot_flow(self):
"""Test the full flow of creating a bot."""
mock = MockMiniMaxClient()
# First call: model asks for bot name
mock.add_response({
"choices": [{
"message": {
"content": "I'd be happy to help you create a trading bot! What would you like to name it?",
"role": "assistant",
}
}]
})
# Second call: user provides name, model calls create_bot
mock.add_response({
"choices": [{
"finish_reason": "tool_calls",
"message": {
"content": "",
"role": "assistant",
"tool_calls": [{
"id": "call_create",
"type": "function",
"function": {
"name": "create_bot",
"arguments": '{"name": "TestBot"}'
}
}]
}
}]
})
# Third call: after create_bot result, model gives PLAIN TEXT response (not JSON)
mock.add_response({
"choices": [{
"message": {
"content": "✅ Your bot 'TestBot' has been created! Now let's set up your trading strategy.",
"role": "assistant",
}
}]
})
agent = ConversationalAgent(
client=mock,
conversation_id="test-conv-123",
anonymous_token="test-token"
)
# First message - greeting
result1 = agent.chat("I want to run a backtest")
assert mock.call_count == 1
# Second message - bot name
result2 = agent.chat("MyBot")
assert mock.call_count == 3 # Two calls due to tool execution
assert "bot" in result2.get("response", "").lower()
class TestMockMiniMaxClient:
"""Test the mock client itself."""
def test_add_and_retrieve_responses(self):
"""Test that responses are returned in order."""
mock = MockMiniMaxClient()
mock.add_response({"result": "first"})
mock.add_response({"result": "second"})
assert mock.chat({}, "") == {"result": "first"}
assert mock.chat({}, "") == {"result": "second"}
def test_calls_are_recorded(self):
"""Test that all calls are recorded."""
mock = MockMiniMaxClient()
mock.add_response({"result": "ok"})
mock.chat(["msg1"], "system")
mock.chat(["msg2"], "system")
assert len(mock.calls) == 2
assert mock.calls[0]["messages"] == ["msg1"]
assert mock.calls[1]["messages"] == ["msg2"]
def test_default_response_when_exhausted(self):
"""Test default response when all predefined responses are used."""
mock = MockMiniMaxClient()
mock.add_response({"result": "only"})
result1 = mock.chat([], "")
result2 = mock.chat([], "") # No more responses
assert result1 == {"result": "only"}
assert "Mock response" in result2["choices"][0]["message"]["content"]
if __name__ == "__main__":
pytest.main([__file__, "-v"])

View File

@@ -1,457 +1,505 @@
"""
Unit tests for BacktestEngine
Tests stop loss, take profit, and max drawdown calculations
"""
import pytest
import asyncio
from datetime import datetime
import sys
import os
# Add the backend directory to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'app'))
from app.services.backtest.engine import BacktestEngine
class TestBacktestEngine:
"""Test suite for BacktestEngine"""
def create_klines(start_price, num_klines, interval=1.0, volatility=0.01):
"""Helper to create kline data with predictable price movements.
def _run_backtest(self, config, klines):
"""Helper to run backtest with given klines"""
engine = BacktestEngine(config)
result = asyncio.run(engine.run_with_klines(klines))
return engine, result
def _trace_portfolio(self, engine, initial_balance):
"""Print portfolio trace for debugging"""
running_balance = initial_balance
running_position = 0.0
print("\nPortfolio Trace:")
for i, trade in enumerate(engine.trades):
if trade["type"] == "buy":
running_position = trade["quantity"]
running_balance -= trade["amount"]
portfolio = running_balance + (running_position * trade["price"])
print(f" BUY #{i+1}: @${trade['price']} - portfolio=${portfolio:.2f}")
else:
running_balance += trade["amount"]
running_position = 0
portfolio = running_balance
print(f" SELL #{i+1}: @${trade['price']} ({trade.get('exit_reason', '')}) - portfolio=${portfolio:.2f}")
if engine.position > 0 and engine.last_kline_price:
final = running_balance + (engine.position * engine.last_kline_price)
print(f" FINAL: position={engine.position:.2f} @ ${engine.last_kline_price} = ${final:.2f}")
print()
def test_stop_loss_triggers_correctly(self):
"""Test stop loss triggers at configured percentage"""
config = {
"bot_id": "test",
"strategy_config": {
"conditions": [{"type": "price_drop", "token": "TEST", "token_address": "0x123", "threshold": 5}],
"actions": [{"type": "buy", "amount_percent": 100}],
"risk_management": {"stop_loss_percent": 5, "take_profit_percent": 10}
},
"ave_api_key": "test",
"ave_api_plan": "free",
"initial_balance": 10000.0,
}
# Price sequence that triggers buy then stop loss:
# $110 -> $100 (9% drop, BUY)
# $100 -> $95 (5% drop, STOP LOSS at 5% from $100 = $95)
klines = [
{"close": "110.0", "timestamp": 1000, "open": "110.0", "high": "110.0", "low": "110.0", "volume": "1000"},
{"close": "100.0", "timestamp": 2000, "open": "100.0", "high": "100.0", "low": "100.0", "volume": "1000"},
{"close": "95.0", "timestamp": 3000, "open": "95.0", "high": "95.0", "low": "95.0", "volume": "1000"},
]
engine, result = self._run_backtest(config, klines)
self._trace_portfolio(engine, 10000.0)
print(f"Results:")
print(f" Trades: {len(engine.trades)} (expected 2)")
print(f" Max drawdown: {result['max_drawdown']}%")
print(f" Total return: {result['total_return']}%")
assert len(engine.trades) == 2
assert engine.trades[0]["type"] == "buy"
assert engine.trades[1]["type"] == "sell"
assert engine.trades[1]["exit_reason"] == "stop_loss"
# Max drawdown should be ~5% (stop loss percentage)
assert 3 < result['max_drawdown'] < 8
# Total return should be ~-5%
assert -8 < result['total_return'] < -3
def test_take_profit_triggers(self):
"""Test take profit triggers at configured percentage"""
config = {
"bot_id": "test",
"strategy_config": {
"conditions": [{"type": "price_drop", "token": "TEST", "token_address": "0x123", "threshold": 5}],
"actions": [{"type": "buy", "amount_percent": 100}],
"risk_management": {"stop_loss_percent": 5, "take_profit_percent": 10}
},
"ave_api_key": "test",
"ave_api_plan": "free",
"initial_balance": 10000.0,
}
# $100 -> $95 (5% drop, BUY) -> $104.5 (10% rise, TAKE PROFIT)
klines = [
{"close": "100.0", "timestamp": 1000, "open": "100.0", "high": "100.0", "low": "100.0", "volume": "1000"},
{"close": "95.0", "timestamp": 2000, "open": "95.0", "high": "95.0", "low": "95.0", "volume": "1000"},
{"close": "104.5", "timestamp": 3000, "open": "104.5", "high": "104.5", "low": "104.5", "volume": "1000"},
]
engine, result = self._run_backtest(config, klines)
self._trace_portfolio(engine, 10000.0)
print(f"Results:")
print(f" Trades: {len(engine.trades)} (expected 2)")
print(f" Max drawdown: {result['max_drawdown']}%")
print(f" Total return: {result['total_return']}%")
assert len(engine.trades) == 2
assert engine.trades[1]["exit_reason"] == "take_profit"
assert result['total_return'] > 0
def test_max_drawdown_bounded_by_stop_loss(self):
"""Test that max drawdown is bounded by stop loss when position is properly closed"""
config = {
"bot_id": "test",
"strategy_config": {
"conditions": [{"type": "price_drop", "token": "TEST", "token_address": "0x123", "threshold": 5}],
"actions": [{"type": "buy", "amount_percent": 100}],
"risk_management": {"stop_loss_percent": 5, "take_profit_percent": 10}
},
"ave_api_key": "test",
"ave_api_plan": "free",
"initial_balance": 10000.0,
}
# $110 -> $100 -> $95 (BUY) -> $90 (STOP LOSS)
klines = [
{"close": "110.0", "timestamp": 1000, "open": "110.0", "high": "110.0", "low": "110.0", "volume": "1000"},
{"close": "100.0", "timestamp": 2000, "open": "100.0", "high": "100.0", "low": "100.0", "volume": "1000"},
{"close": "95.0", "timestamp": 3000, "open": "95.0", "high": "95.0", "low": "95.0", "volume": "1000"},
{"close": "90.0", "timestamp": 4000, "open": "90.0", "high": "90.0", "low": "90.0", "volume": "1000"},
]
engine, result = self._run_backtest(config, klines)
self._trace_portfolio(engine, 10000.0)
print(f"Results:")
print(f" Trades: {len(engine.trades)}")
print(f" Max drawdown: {result['max_drawdown']}%")
print(f" Total return: {result['total_return']}%")
# With 5% stop loss, max drawdown should be around 5%
assert 3 < result['max_drawdown'] < 8
def test_open_position_not_closed(self):
"""Test scenario where last kline has an open position"""
config = {
"bot_id": "test",
"strategy_config": {
"conditions": [{"type": "price_drop", "token": "TEST", "token_address": "0x123", "threshold": 10}],
"actions": [{"type": "buy", "amount_percent": 100}],
"risk_management": {"stop_loss_percent": 5, "take_profit_percent": 10}
},
"ave_api_key": "test",
"ave_api_plan": "free",
"initial_balance": 10000.0,
}
# $100 -> $90 (10% drop, BUY) - and backtest ends here
# Position is open, marked to market at $90
klines = [
{"close": "100.0", "timestamp": 1000, "open": "100.0", "high": "100.0", "low": "100.0", "volume": "1000"},
{"close": "90.0", "timestamp": 2000, "open": "90.0", "high": "90.0", "low": "90.0", "volume": "1000"},
]
engine, result = self._run_backtest(config, klines)
self._trace_portfolio(engine, 10000.0)
print(f"Results:")
print(f" Trades: {len(engine.trades)}")
print(f" Position open: {engine.position > 0}")
print(f" Entry price: ${engine.entry_price}")
print(f" Last kline price: ${engine.last_kline_price}")
print(f" Max drawdown: {result['max_drawdown']}%")
print(f" Total return: {result['total_return']}%")
# Position should be open
assert engine.position > 0
# Entry should be $90
assert engine.entry_price == 90.0
# Since entry = last kline price, no unrealized loss
# Max drawdown should be 0%
assert result['max_drawdown'] == 0.0
def test_open_position_with_loss(self):
"""Test open position where price dropped but stop loss didn't trigger"""
config = {
"bot_id": "test",
"strategy_config": {
"conditions": [{"type": "price_drop", "token": "TEST", "token_address": "0x123", "threshold": 10}],
"actions": [{"type": "buy", "amount_percent": 100}],
"risk_management": {"stop_loss_percent": 5, "take_profit_percent": 10}
},
"ave_api_key": "test",
"ave_api_plan": "free",
"initial_balance": 10000.0,
}
# $100 -> $90 (10% drop, BUY at $90) -> $85 (stop loss at 5% from $90 = $85.5)
# $85 > $85.5? No, $85 < $85.5, so stop loss WOULD trigger
# Let me use $86 instead - $86 > $85.5 so no stop loss
klines = [
{"close": "100.0", "timestamp": 1000, "open": "100.0", "high": "100.0", "low": "100.0", "volume": "1000"},
{"close": "90.0", "timestamp": 2000, "open": "90.0", "high": "90.0", "low": "90.0", "volume": "1000"},
{"close": "86.0", "timestamp": 3000, "open": "86.0", "high": "86.0", "low": "86.0", "volume": "1000"},
]
engine, result = self._run_backtest(config, klines)
self._trace_portfolio(engine, 10000.0)
print(f"Results:")
print(f" Trades: {len(engine.trades)}")
print(f" Position open: {engine.position > 0}")
print(f" Entry price: ${engine.entry_price}")
print(f" Last kline price: ${engine.last_kline_price}")
print(f" Max drawdown: {result['max_drawdown']}%")
print(f" Total return: {result['total_return']}%")
# Position should be open
assert engine.position > 0
# Entry = $90, stop = $85.50, last = $86 (above stop)
# Portfolio: $0 + position * $86
# Position: 10000/90 = 111.11 tokens
# Portfolio at $86: 111.11 * 86 = $9,555.56
# But we only track portfolio at trade points, so max was $10,000
# drawdown = (10000 - 9555.56) / 10000 = 4.44%
print(f" Expected max drawdown: ~4.4% (marked to market at $86)")
def test_multiple_buy_sell_cycles(self):
"""Test multiple buy/sell cycles"""
config = {
"bot_id": "test",
"strategy_config": {
"conditions": [{"type": "price_drop", "token": "TEST", "token_address": "0x123", "threshold": 5}],
"actions": [{"type": "buy", "amount_percent": 50}], # 50% of balance
"risk_management": {"stop_loss_percent": 5, "take_profit_percent": 10}
},
"ave_api_key": "test",
"ave_api_plan": "free",
"initial_balance": 10000.0,
}
# $100 -> $95 (BUY) -> $104.5 (TAKE PROFIT) -> $95 (BUY) -> $90 (STOP LOSS)
klines = [
{"close": "100.0", "timestamp": 1000, "open": "100.0", "high": "100.0", "low": "100.0", "volume": "1000"},
{"close": "95.0", "timestamp": 2000, "open": "95.0", "high": "95.0", "low": "95.0", "volume": "1000"}, # BUY at $95
{"close": "104.5", "timestamp": 3000, "open": "104.5", "high": "104.5", "low": "104.5", "volume": "1000"}, # TAKE PROFIT
{"close": "95.0", "timestamp": 4000, "open": "95.0", "high": "95.0", "low": "95.0", "volume": "1000"}, # 9% drop - no buy
{"close": "90.0", "timestamp": 5000, "open": "90.0", "high": "90.0", "low": "90.0", "volume": "1000"}, # 10.5% drop from $100 - BUY at $90
{"close": "85.5", "timestamp": 6000, "open": "85.5", "high": "85.5", "low": "85.5", "volume": "1000"}, # STOP LOSS at 5% from $90 = $85.5
]
engine, result = self._run_backtest(config, klines)
self._trace_portfolio(engine, 10000.0)
print(f"Results:")
print(f" Trades: {len(engine.trades)}")
print(f" Buy count: {len([t for t in engine.trades if t['type'] == 'buy'])}")
print(f" Sell count: {len([t for t in engine.trades if t['type'] == 'sell'])}")
print(f" Max drawdown: {result['max_drawdown']}%")
print(f" Total return: {result['total_return']}%")
def run_tests():
tests = TestBacktestEngine()
print("=" * 60)
print("TEST 1: Stop Loss Triggers Correctly")
print("=" * 60)
try:
tests.test_stop_loss_triggers_correctly()
print("PASSED\n")
except AssertionError as e:
print(f"FAILED: {e}\n")
print("=" * 60)
print("TEST 2: Take Profit Triggers")
print("=" * 60)
try:
tests.test_take_profit_triggers()
print("PASSED\n")
except AssertionError as e:
print(f"FAILED: {e}\n")
print("=" * 60)
print("TEST 3: Max Drawdown Bounded by Stop Loss")
print("=" * 60)
try:
tests.test_max_drawdown_bounded_by_stop_loss()
print("PASSED\n")
except AssertionError as e:
print(f"FAILED: {e}\n")
print("=" * 60)
print("TEST 4: Open Position Not Closed")
print("=" * 60)
try:
tests.test_open_position_not_closed()
print("PASSED\n")
except AssertionError as e:
print(f"FAILED: {e}\n")
print("=" * 60)
print("TEST 5: Open Position With Loss")
print("=" * 60)
try:
tests.test_open_position_with_loss()
print("PASSED\n")
except AssertionError as e:
print(f"FAILED: {e}\n")
print("=" * 60)
print("TEST 6: Multiple Buy/Sell Cycles")
print("=" * 60)
try:
tests.test_multiple_buy_sell_cycles()
print("PASSED\n")
except AssertionError as e:
print(f"FAILED: {e}\n")
def test_dca_multiple_buys():
"""Test that DCA with multiple consecutive buys uses weighted average for stop loss."""
print("\n" + "=" * 60)
print("TEST 7: DCA With Multiple Consecutive Buys")
print("=" * 60)
config = {
"bot_id": "test",
"strategy_config": {
"conditions": [{"type": "price_drop", "threshold": 2, "token": "TEST", "token_address": "0x123"}],
"actions": [{"type": "buy", "amount_percent": 20}],
"risk_management": {"stop_loss_percent": 5, "take_profit_percent": 5},
},
"initial_balance": 10000.0,
"ave_api_key": "test",
"ave_api_plan": "free",
}
# 3 consecutive 2% drops = 3 buys at $0.58, $0.57, $0.56
# Then drop to $0.50 which is below 5% from average (~$0.57 * 0.95 = $0.54)
klines = [
{"close": "0.60", "timestamp": 1000, "open": "0.60", "high": "0.60", "low": "0.60", "volume": "1000"},
{"close": "0.588", "timestamp": 2000}, # 2% drop -> BUY 1 @ $0.588
{"close": "0.576", "timestamp": 3000}, # 2% drop -> BUY 2 @ $0.576
{"close": "0.565", "timestamp": 4000}, # 2% drop -> BUY 3 @ $0.565
{"close": "0.50", "timestamp": 5000}, # Below 5% from avg -> STOP LOSS
]
test = TestBacktestEngine()
engine, result = test._run_backtest(config, klines)
test._trace_portfolio(engine, 10000.0)
print(f"\nResults:")
print(f" Trades: {len(engine.trades)} (expected 3: 2 buys + stop loss)")
print(f" Max drawdown: {result['max_drawdown']}%")
print(f" Total return: {result['total_return']}%")
# Verify: 2 buys + 1 sell (stop loss) = 3 trades
# The 3rd buy @ $0.565 doesn't happen because stop loss triggers at $0.5 first
assert len(engine.trades) == 3, f"Expected 3 trades, got {len(engine.trades)}"
# Verify last trade is stop loss
last_trade = engine.trades[-1]
assert last_trade["type"] == "sell", "Last trade should be sell"
assert last_trade.get("exit_reason") == "stop_loss", f"Last trade should be stop_loss, got {last_trade.get('exit_reason')}"
# Verify max drawdown is reasonable (close to stop loss %)
# Actual loss should be around 5% from weighted average
assert result['max_drawdown'] < 10, f"Max drawdown {result['max_drawdown']}% is too high for 5% stop loss"
# Position is now 0 after stop loss, so avg_entry_price is None
print(f" Position closed: {engine.position == 0}")
print(f" Final balance: ${engine.current_balance:.2f}")
print("PASSED")
return True
def test_stop_loss_always_results_in_loss():
"""Test that stop loss ALWAYS results in a loss, never a gain.
This tests the scenario where:
- You start with $10,000
- Price keeps dropping, triggering multiple buys
- Stop loss triggers, selling your entire position
- Final balance MUST be less than initial balance
Args:
start_price: Starting price
num_klines: Number of klines to create
interval: Price change per kline (can be positive or negative)
volatility: Random noise factor (0.01 = 1%)
"""
print("\n" + "=" * 60)
print("TEST 8: Stop Loss Always Results In Loss")
print("=" * 60)
import random
klines = []
price = start_price
base_time = 1704067200 # 2024-01-01 00:00:00 UTC
config = {
"bot_id": "test",
"strategy_config": {
"conditions": [{"type": "price_drop", "threshold": 2, "token": "TEST", "token_address": "0x123"}],
"actions": [{"type": "buy", "amount_percent": 20}],
"risk_management": {"stop_loss_percent": 5, "take_profit_percent": 5},
},
"initial_balance": 10000.0,
"ave_api_key": "test",
for i in range(num_klines):
# Add some randomness
noise = (random.random() - 0.5) * 2 * volatility * price
price = max(0.00000001, price + interval + noise)
open_price = price - (random.random() * volatility * price)
close_price = price
high_price = max(open_price, close_price) + (random.random() * volatility * price)
low_price = min(open_price, close_price) - (random.random() * volatility * price)
klines.append({
"open": str(open_price),
"high": str(high_price),
"low": str(low_price),
"close": str(close_price),
"volume": str(1000 + random.random() * 100),
"amount": str(1000 * price),
"time": base_time + (i * 3600) # 1 hour intervals
})
return klines
class MockAveClient:
"""Mock AVE client that returns test klines."""
def __init__(self, klines):
self.klines = klines
async def get_klines(self, token_id, interval, limit, start_time=None, end_time=None):
return self.klines
class TestBacktestEngine:
"""Test cases for BacktestEngine."""
@pytest.fixture
def base_config(self):
"""Base config for backtest."""
return {
"bot_id": "test-bot-123",
"token": "0xtest",
"chain": "bsc",
"timeframe": "1h",
"start_date": "2024-01-01",
"end_date": "2024-01-02",
"ave_api_key": "test-key",
"ave_api_plan": "free",
"initial_balance": 10000.0,
}
# Price scenario: drops each kline, triggering multiple buys
# Final drop triggers stop loss
#
# $0.60 -> $0.588 (2% drop) -> BUY 1 @ $0.588
# $0.588 -> $0.576 (2% drop) -> BUY 2 @ $0.576
# $0.576 -> $0.565 (2% drop) -> BUY 3 @ $0.565
# $0.565 -> $0.535 (5.3% drop) -> STOP LOSS @ $0.535 (5% from weighted avg ~$0.576)
klines = [
{"close": "0.60", "timestamp": 1000},
{"close": "0.588", "timestamp": 2000}, # BUY 1
{"close": "0.576", "timestamp": 3000}, # BUY 2
{"close": "0.565", "timestamp": 4000}, # BUY 3
{"close": "0.535", "timestamp": 5000}, # STOP LOSS
]
@pytest.fixture
def simple_strategy(self):
"""Simple strategy: buy on 1% drop, no auto sell."""
return {
"conditions": [
{"type": "price_drop", "token": "TEST", "token_address": "0xtest", "threshold": 1.0}
],
"actions": [
{"type": "buy", "amount_percent": 10}
],
"risk_management": {}
}
test = TestBacktestEngine()
engine, result = test._run_backtest(config, klines)
@pytest.fixture
def partial_sell_strategy(self):
"""Strategy with partial sells: buy on 1% drop, sell 50% on rise (via risk management take profit)."""
return {
"conditions": [
{"type": "price_drop", "token": "TEST", "token_address": "0xtest", "threshold": 1.0}
],
"actions": [
{"type": "buy", "amount_percent": 10}
],
"risk_management": {
"take_profit_percent": 1.5 # 1.5% take profit to trigger on price rise
}
}
print(f"\nSetup:")
print(f" Initial balance: $10,000")
print(f" Stop loss: 5%")
print(f" Each buy: 20% of current balance")
print(f"\nTrades:")
for i, trade in enumerate(engine.trades):
exit_info = f" ({trade.get('exit_reason', '')})" if 'exit_reason' in trade else ""
print(f" {i+1}. {trade['type']} @ ${trade['price']} - ${trade['amount']:.2f}{exit_info}")
@pytest.fixture
def stop_loss_strategy(self):
"""Strategy with stop loss and take profit."""
return {
"conditions": [
{"type": "price_drop", "token": "TEST", "token_address": "0xtest", "threshold": 1.0}
],
"actions": [
{"type": "buy", "amount_percent": 10}
],
"risk_management": {
"stop_loss_percent": 5, # 5% stop loss
"take_profit_percent": 10 # 10% take profit
}
}
print(f"\nResults:")
print(f" Final balance: ${engine.current_balance:.2f}")
print(f" Total return: {result['total_return']:.2f}%")
print(f" Max drawdown: {result['max_drawdown']:.2f}%")
def test_single_buy_and_hold(self, base_config, simple_strategy):
"""Test buying once and holding (no sell triggers)."""
# Create klines that drop 0.5% each (below 1% threshold, no buy)
# Then rise 0.5% each (still no sell since no position)
klines = create_klines(100, 10, interval=0.5) # Rising trend
# CRITICAL ASSERTION: Stop loss MUST result in loss
assert engine.current_balance < 10000.0, \
f"BUG: Stop loss resulted in GAIN! Balance went from $10,000 to ${engine.current_balance:.2f}"
config = {**base_config, "strategy_config": simple_strategy}
engine = BacktestEngine(config)
engine.ave_client = MockAveClient(klines)
# Also verify total return is negative
assert result['total_return'] < 0, \
f"BUG: Total return is positive ({result['total_return']:.2f}%) after stop loss!"
results = asyncio.run(engine.run())
# Max drawdown should reflect the actual loss (close to stop loss %)
assert result['max_drawdown'] < 10, \
f"Max drawdown ({result['max_drawdown']:.2f}%) seems too high"
print(f"Results: {results}")
# Should have 0 trades since price never dropped 1%
assert results.get("total_trades") == 0
assert results.get("final_balance") == 10000.0
print(f"\n✓ PASSED: Stop loss correctly resulted in ${10000 - engine.current_balance:.2f} loss")
return True
def test_multiple_dips_multiple_buys(self, base_config, simple_strategy):
"""Test multiple dips triggering multiple buys (DCA)."""
# Create price that drops 1.5% then rises 0.5%, repeats
# This should trigger buy on each drop
klines = []
price = 100.0
base_time = 1704067200
for i in range(20):
if i % 3 == 0:
# Drop by 1.5%
price = price * 0.985 # 1.5% drop
else:
# Rise by 0.5%
price = price * 1.005
klines.append({
"open": str(price * 0.99),
"high": str(price * 1.01),
"low": str(price * 0.98),
"close": str(price),
"volume": "1000",
"amount": str(1000 * price),
"time": base_time + (i * 3600)
})
config = {**base_config, "strategy_config": simple_strategy}
engine = BacktestEngine(config)
engine.ave_client = MockAveClient(klines)
results = asyncio.run(engine.run())
print(f"Results: {results}")
print(f"Trades: {engine.trades}")
# Should have multiple buys (6-7 dips at 1.5% threshold out of ~7 drops)
assert results.get("total_trades") >= 6
buy_trades = [t for t in engine.trades if t["type"] == "buy"]
assert len(buy_trades) >= 6
# Should end with position > 0 (still holding since no sell triggers)
assert engine.position > 0
def test_partial_sells(self, base_config, partial_sell_strategy):
"""Test partial sells - selling some portion via take profit."""
# Create: drop 1.5% (buy), rise 1.5% (sell via take profit), drop 1.5% (buy), rise 1.5% (sell via take profit)
klines = []
price = 100.0
base_time = 1704067200
for i in range(8):
if i % 2 == 0:
# Even: drop 1.5% (should trigger buy)
price = price * 0.985
else:
# Odd: rise 1.5% (should trigger take profit sell)
price = price * 1.015
klines.append({
"open": str(price * 0.99),
"high": str(price * 1.01),
"low": str(price * 0.98),
"close": str(price),
"volume": "1000",
"amount": str(1000 * price),
"time": base_time + (i * 3600)
})
config = {**base_config, "strategy_config": partial_sell_strategy}
engine = BacktestEngine(config)
engine.ave_client = MockAveClient(klines)
results = asyncio.run(engine.run())
print(f"Results: {results}")
print(f"Trades: {engine.trades}")
# Multiple cycles happen due to price oscillation
# At minimum we should have some trades
assert results.get("total_trades") >= 2
buy_trades = [t for t in engine.trades if t["type"] == "buy"]
sell_trades = [t for t in engine.trades if t["type"] == "sell"]
# Should have executed some trades
assert len(buy_trades) >= 1
assert len(sell_trades) >= 1
# Should have made profit from the sells
assert results.get("total_return") > 0
def test_stop_loss_trigger(self, base_config, stop_loss_strategy):
"""Test stop loss triggers correctly."""
# Create: buy, then continue dropping to trigger stop loss
klines = []
base_time = 1704067200
# Kline 0: reference price (skipped due to idx=0 check)
klines.append({
"open": "100",
"high": "101",
"low": "99",
"close": "100",
"volume": "1000",
"amount": "100000",
"time": base_time
})
# Kline 1: drop triggers buy at 98.5
klines.append({
"open": "100",
"high": "101",
"low": "98",
"close": "98.5", # 1.5% drop from 100
"volume": "1000",
"amount": "98500",
"time": base_time + 3600
})
# Kline 2: price rises slightly, no condition trigger
klines.append({
"open": "98.5",
"high": "100",
"low": "98",
"close": "99",
"volume": "1000",
"amount": "99000",
"time": base_time + 7200
})
# Kline 3: price drops below stop loss
# Entry was 98.5, stop loss is 5%, so SL = 98.5 * 0.95 = 93.575
# This close (92) is below SL
klines.append({
"open": "99",
"high": "100",
"low": "90", # Well below stop loss
"close": "92", # Below stop loss (93.575)
"volume": "1000",
"amount": "92000",
"time": base_time + 10800
})
config = {**base_config, "strategy_config": stop_loss_strategy}
engine = BacktestEngine(config)
engine.ave_client = MockAveClient(klines)
results = asyncio.run(engine.run())
print(f"Results: {results}")
print(f"Trades: {engine.trades}")
print(f"DEBUG: stop_loss_percent = {engine.stop_loss_percent}")
print(f"DEBUG: take_profit_percent = {engine.take_profit_percent}")
# Should have 2 trades: 1 buy, 1 sell (stop loss)
assert results.get("total_trades") == 2
sell_trades = [t for t in engine.trades if t["type"] == "sell"]
assert len(sell_trades) == 1
assert sell_trades[0]["exit_reason"] == "stop_loss"
# Should have lost money (stop loss triggered)
assert results.get("total_return") < 0
assert results.get("final_balance") < 10000.0
sell_trades = [t for t in engine.trades if t["type"] == "sell"]
assert len(sell_trades) == 1
assert sell_trades[0]["exit_reason"] == "stop_loss"
# Should have lost money (stop loss triggered)
assert results.get("total_return") < 0
assert results.get("final_balance") < 10000.0
def test_take_profit_trigger(self, base_config, stop_loss_strategy):
"""Test take profit triggers correctly."""
# Create: buy, then price rises to trigger take profit
klines = []
base_time = 1704067200
# Kline 0: reference price (skipped due to idx=0)
klines.append({
"open": "100",
"high": "101",
"low": "99",
"close": "100",
"volume": "1000",
"amount": "100000",
"time": base_time
})
# Kline 1: drop triggers buy at 98.5 (1.5% drop from 100)
klines.append({
"open": "100",
"high": "101",
"low": "98",
"close": "98.5",
"volume": "1000",
"amount": "98500",
"time": base_time + 3600
})
# Kline 2: price stays roughly flat
klines.append({
"open": "98.5",
"high": "99",
"low": "98",
"close": "98.8",
"volume": "1000",
"amount": "98800",
"time": base_time + 7200
})
# Kline 3: price rises above take profit
# Entry was 98.5, take profit is 10%, so TP = 98.5 * 1.10 = 108.35
klines.append({
"open": "98.8",
"high": "120", # Way above TP
"low": "98",
"close": "115", # Above 108.35
"volume": "1000",
"amount": "115000",
"time": base_time + 10800
})
config = {**base_config, "strategy_config": stop_loss_strategy}
engine = BacktestEngine(config)
engine.ave_client = MockAveClient(klines)
results = asyncio.run(engine.run())
print(f"Results: {results}")
print(f"Trades: {engine.trades}")
print(f"DEBUG: stop_loss_percent = {engine.stop_loss_percent}")
print(f"DEBUG: take_profit_percent = {engine.take_profit_percent}")
# Should have 2 trades: 1 buy, 1 sell (take profit)
assert results.get("total_trades") == 2
sell_trades = [t for t in engine.trades if t["type"] == "sell"]
assert len(sell_trades) == 1
assert sell_trades[0]["exit_reason"] == "take_profit"
# Should have made profit (take profit triggered)
assert results.get("total_return") > 0
assert results.get("final_balance") > 10000.0
def test_full_cycle_dip_buy_sell(self, base_config):
"""Test a complete cycle: buy on dip, then sell via take profit."""
# Strategy: buy 10% on 1% dip, take profit 2% to sell
strategy = {
"conditions": [
{"type": "price_drop", "token": "TEST", "token_address": "0xtest", "threshold": 1.0}
],
"actions": [
{"type": "buy", "amount_percent": 10}
],
"risk_management": {
"take_profit_percent": 2.0 # Sell when price rises 2%
}
}
klines = []
base_time = 1704067200
# Klines:
# 0: price 100 (reference)
# 1: price 98.5 - 1.5% drop, triggers buy at 98.5
# 2: price 100.5 - 2% rise from 98.5 = 100.47, triggers take profit
klines.append({
"open": "100", "high": "101", "low": "99", "close": "100",
"volume": "1000", "amount": "100000", "time": base_time
})
klines.append({
"open": "100", "high": "101", "low": "97.5", "close": "98.5",
"volume": "1000", "amount": "98500", "time": base_time + 3600
})
klines.append({
"open": "98.5", "high": "101", "low": "98", "close": "100.5",
"volume": "1000", "amount": "100500", "time": base_time + 7200
})
config = {**base_config, "strategy_config": strategy}
engine = BacktestEngine(config)
engine.ave_client = MockAveClient(klines)
results = asyncio.run(engine.run())
print(f"Results: {results}")
print(f"Trades: {engine.trades}")
# Should have 2 trades: 1 buy, 1 sell (take profit)
assert results.get("total_trades") == 2
buy_trades = [t for t in engine.trades if t["type"] == "buy"]
sell_trades = [t for t in engine.trades if t["type"] == "sell"]
assert len(buy_trades) == 1
assert len(sell_trades) == 1
assert sell_trades[0]["exit_reason"] == "take_profit"
# Should have made profit
assert results.get("total_return") > 0
def test_multiple_buys_then_multiple_sells(self, base_config):
"""Test multiple buys followed by multiple sells via take profit."""
# Create strategy: buy 10% on 2% dip, take profit 2% to sell
strategy = {
"conditions": [
{"type": "price_drop", "token": "TEST", "token_address": "0xtest", "threshold": 2.0}
],
"actions": [
{"type": "buy", "amount_percent": 10}
],
"risk_management": {
"take_profit_percent": 2.5 # Sell when price rises 2.5% (slightly above entry drop)
}
}
# Price pattern: drop 2.5% (buy), rise 2.5% (take profit sells), repeat 3 times
klines = []
base_time = 1704067200
price = 100.0
for i in range(12):
if i % 2 == 0:
price = price * 0.975 # Drop 2.5% - triggers buy
else:
price = price * 1.026 # Rise 2.5% - triggers take profit sell
klines.append({
"open": str(price * 0.99),
"high": str(price * 1.01),
"low": str(price * 0.98),
"close": str(price),
"volume": "1000",
"amount": str(1000 * price),
"time": base_time + (i * 3600)
})
config = {**base_config, "strategy_config": strategy}
engine = BacktestEngine(config)
engine.ave_client = MockAveClient(klines)
results = asyncio.run(engine.run())
print(f"Results: {results}")
print(f"Trades: {engine.trades}")
# Price oscillates creating multiple dip/sell cycles
# Should have 10 trades: 5 buys, 5 sells (via take profit)
assert results.get("total_trades") == 10
buy_trades = [t for t in engine.trades if t["type"] == "buy"]
sell_trades = [t for t in engine.trades if t["type"] == "sell"]
assert len(buy_trades) == 5
assert len(sell_trades) == 5
# Position should be 0 after all sells
assert engine.position == 0
# Should have profitable trades
assert results.get("total_return") > 0
if __name__ == "__main__":
run_tests()
test_dca_multiple_buys()
test_stop_loss_always_results_in_loss()
pytest.main([__file__, "-v"])

View File

@@ -8,7 +8,10 @@ import type {
AuthResponse,
BotChatRequest,
BotChatResponse,
StrategyConfig
StrategyConfig,
Conversation,
ConversationWithMessages,
Message
} from './types';
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000/api';
@@ -18,6 +21,16 @@ function getAuthHeaders(): HeadersInit {
return token ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' } : { 'Content-Type': 'application/json' };
}
class ApiError extends Error {
status: number;
constructor(message: string, status: number) {
super(message);
this.name = 'ApiError';
this.status = status;
}
}
async function handleResponse<T>(response: Response): Promise<T> {
if (!response.ok) {
const error = await response.json().catch(() => ({ detail: 'An error occurred' }));
@@ -34,7 +47,7 @@ async function handleResponse<T>(response: Response): Promise<T> {
errorMessage = `HTTP error ${response.status}`;
}
throw new Error(errorMessage);
throw new ApiError(errorMessage, response.status);
}
return response.json();
}
@@ -237,5 +250,58 @@ export const api = {
});
return handleResponse<{ symbol: string; chain: string; name: string }[]>(response);
}
},
conversations: {
async list(): Promise<Conversation[]> {
const response = await fetch(`${API_URL}/conversations`, {
headers: getAuthHeaders()
});
return handleResponse<Conversation[]>(response);
},
async create(): Promise<Conversation> {
const response = await fetch(`${API_URL}/conversations`, {
method: 'POST',
headers: getAuthHeaders()
});
return handleResponse<Conversation>(response);
},
async get(id: string): Promise<ConversationWithMessages> {
const response = await fetch(`${API_URL}/conversations/${id}`, {
headers: getAuthHeaders()
});
return handleResponse<ConversationWithMessages>(response);
},
async delete(id: string): Promise<void> {
const response = await fetch(`${API_URL}/conversations/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
},
async chat(id: string, message: string, signal?: AbortSignal): Promise<ConversationWithMessages> {
const response = await fetch(`${API_URL}/conversations/${id}/chat`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify({ message }),
signal
});
return handleResponse<ConversationWithMessages>(response);
},
async setBot(id: string, botId: string): Promise<Conversation> {
const response = await fetch(`${API_URL}/conversations/${id}/set-bot`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify({ bot_id: botId })
});
return handleResponse<Conversation>(response);
}
}
};

View File

@@ -186,3 +186,24 @@ export interface TokenSearchResult {
address: string;
chain: string;
}
export interface Conversation {
id: string;
user_id: string | null;
bot_id: string | null;
title: string;
created_at: string;
updated_at: string;
}
export interface Message {
id: string;
conversation_id: string;
role: 'user' | 'assistant';
content: string;
created_at: string;
}
export interface ConversationWithMessages extends Conversation {
messages: Message[];
}

View File

@@ -0,0 +1,68 @@
<script lang="ts">
interface Props {
chatCount?: number;
}
let { chatCount = 0 }: Props = $props();
const showWarning = chatCount >= 40;
const limit = 50;
</script>
<div class="anonymous-banner" class:warning={showWarning}>
<div class="banner-content">
{#if showWarning}
<span class="icon">⚠️</span>
<span>
Warning: You've used {chatCount}/{limit} messages.
<a href="/login" class="link">Login to continue</a>
</span>
{:else}
<span class="icon">💬</span>
<span>
Your progress is not saved.
<a href="/login" class="link">Login to save</a>
</span>
{/if}
</div>
</div>
<style>
.anonymous-banner {
padding: 0.5rem 1rem;
background: rgba(251, 191, 36, 0.1);
border-bottom: 1px solid rgba(251, 191, 36, 0.2);
}
.anonymous-banner.warning {
background: rgba(220, 38, 38, 0.15);
border-bottom-color: rgba(220, 38, 38, 0.2);
}
.banner-content {
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
font-size: 0.85rem;
color: #fbbf24;
}
.warning .banner-content {
color: #fca5a5;
}
.icon {
font-size: 1rem;
}
.link {
color: inherit;
text-decoration: underline;
font-weight: 500;
}
.link:hover {
opacity: 0.8;
}
</style>

View File

@@ -0,0 +1,115 @@
<script lang="ts">
import { isAuthenticated, logout, userStore } from '$lib/stores';
import { goto } from '$app/navigation';
function handleLogout() {
logout();
goto('/');
}
</script>
<header class="app-header">
<div class="header-left">
<a href="/home" class="logo">
<span class="logo-text">Randebu</span>
</a>
{#if $isAuthenticated}
<a href="/dashboard" class="nav-link">Dashboard</a>
{/if}
</div>
<div class="header-right">
{#if $isAuthenticated}
<span class="user-info">{$userStore?.username || 'User'}</span>
<button class="btn btn-ghost" onclick={handleLogout}>
Logout
</button>
{:else}
<a href="/login" class="btn btn-ghost">Login</a>
<a href="/register" class="btn btn-primary">Register</a>
{/if}
</div>
</header>
<style>
.app-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 1.25rem;
height: 56px;
background: rgba(0, 0, 0, 0.5);
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
flex-shrink: 0;
}
.header-left {
display: flex;
align-items: center;
gap: 1.5rem;
}
.logo {
text-decoration: none;
}
.logo-text {
font-size: 1.25rem;
font-weight: 700;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.nav-link {
color: #888;
text-decoration: none;
font-size: 0.9rem;
transition: color 0.2s;
}
.nav-link:hover {
color: #fff;
}
.header-right {
display: flex;
align-items: center;
gap: 1rem;
}
.user-info {
color: #888;
font-size: 0.9rem;
}
.btn {
padding: 0.5rem 1rem;
border-radius: 8px;
font-size: 0.9rem;
font-weight: 500;
text-decoration: none;
cursor: pointer;
transition: all 0.2s;
border: none;
}
.btn-ghost {
background: transparent;
color: #888;
}
.btn-ghost:hover {
color: #fff;
}
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.btn-primary:hover {
transform: translateY(-2px);
}
</style>

View File

@@ -3,24 +3,21 @@
interface Props {
bot: Bot;
onOpen?: (botId: string) => void;
onDelete?: (botId: string) => void;
showActions?: boolean;
}
let { bot, onOpen, onDelete, showActions = true }: Props = $props();
function handleOpen() {
onOpen?.(bot.id);
}
let { bot, onDelete, showActions = true }: Props = $props();
function handleDelete(e: Event) {
e.preventDefault();
e.stopPropagation();
onDelete?.(bot.id);
}
</script>
<div class="bot-card" onclick={handleOpen} role="button" tabindex="0" onkeydown={(e) => e.key === 'Enter' && handleOpen()}>
<div class="bot-card">
<a href="/chat/{bot.id}" class="bot-card-link" data-sveltekit-preload-data="hover" aria-label="Open {bot.name}"></a>
<div class="bot-info">
<h3>{bot.name}</h3>
{#if bot.description}
@@ -29,8 +26,8 @@
<span class="bot-status status-{bot.status}">{bot.status}</span>
</div>
{#if showActions}
<div class="bot-actions" onclick={(e) => e.stopPropagation()} role="group">
<button class="btn btn-primary" onclick={handleOpen}>Open</button>
<div class="bot-actions" role="group">
<a href="/chat/{bot.id}" class="btn btn-primary" data-sveltekit-preload-data="hover">Open</a>
<button class="btn btn-danger" onclick={handleDelete}>Delete</button>
</div>
{/if}
@@ -38,11 +35,11 @@
<style>
.bot-card {
position: relative;
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 12px;
padding: 1.5rem;
cursor: pointer;
transition: transform 0.2s, border-color 0.2s;
}
@@ -51,13 +48,17 @@
border-color: rgba(255, 255, 255, 0.2);
}
.bot-card:focus {
outline: 2px solid #667eea;
outline-offset: 2px;
.bot-card-link {
position: absolute;
inset: 0;
border-radius: 12px;
z-index: 0;
}
.bot-info {
margin-bottom: 1rem;
position: relative;
z-index: 1;
}
.bot-info h3 {
@@ -98,6 +99,8 @@
.bot-actions {
display: flex;
gap: 0.75rem;
position: relative;
z-index: 2;
}
.btn {
@@ -108,6 +111,7 @@
cursor: pointer;
border: none;
transition: transform 0.2s, opacity 0.2s;
text-decoration: none;
}
.btn-primary {

View File

@@ -0,0 +1,434 @@
<script lang="ts">
import type { Bot, Condition, Action, RiskManagement } from '$lib/api';
interface Props {
bot?: Bot | null;
onSelectBot?: () => void;
onBacktest?: () => void;
onSimulate?: () => void;
}
let { bot = null, onSelectBot, onBacktest, onSimulate }: Props = $props();
// Helper to get human-readable condition name
function getConditionLabel(condition: Condition): string {
const labels: Record<string, string> = {
'price_drop': 'Price Drop',
'price_rise': 'Price Rise',
'volume_spike': 'Volume Spike',
'price_level': 'Price Level'
};
return labels[condition.type] || condition.type;
}
// Format condition to readable string
function formatCondition(condition: Condition): string {
const parts: string[] = [getConditionLabel(condition)];
if (condition.token) {
parts.push(condition.token.toUpperCase());
}
if (condition.direction) {
parts.push(condition.direction);
}
if (condition.threshold) {
parts.push(`>${condition.threshold}%`);
}
if (condition.price) {
parts.push(`$${condition.price}`);
}
if (condition.timeframe) {
parts.push(`(${condition.timeframe})`);
}
return parts.join(' ');
}
// Format action to readable string
function formatAction(action: Action): string {
const parts: string[] = [];
if (action.type === 'buy') {
parts.push('Buy');
if (action.amount_percent) {
parts.push(`${action.amount_percent}%`);
}
if (action.token) {
parts.push(`of ${action.token.toUpperCase()}`);
}
} else if (action.type === 'sell') {
parts.push('Sell');
if (action.amount_percent) {
parts.push(`${action.amount_percent}%`);
}
} else {
parts.push('Hold');
}
return parts.join(' ');
}
let hasStrategy = $derived(
bot?.strategy_config &&
((bot.strategy_config.conditions && bot.strategy_config.conditions.length > 0) ||
(bot.strategy_config.actions && bot.strategy_config.actions.length > 0) ||
bot.strategy_config.risk_management)
);
</script>
<div class="bot-info-panel">
<h3>Bot Details</h3>
{#if !bot}
<div class="no-bot">
<p>No bot selected</p>
{#if onSelectBot}
<button class="btn btn-secondary" onclick={onSelectBot}>
Select Bot
</button>
{/if}
</div>
{:else}
<div class="bot-details">
<div class="bot-name">{bot.name}</div>
<div class="detail-row">
<span class="label">Status:</span>
<span class="value" class:active={bot.status === 'active'}>
{bot.status}
</span>
</div>
</div>
<div class="strategy-section">
<h4>Strategy</h4>
{#if hasStrategy}
{#if bot.strategy_config?.conditions && bot.strategy_config.conditions.length > 0}
<div class="strategy-group">
<div class="strategy-group-label">When:</div>
{#each bot.strategy_config.conditions as condition}
<div class="condition-item">
<span class="condition-icon">📊</span>
{formatCondition(condition)}
</div>
{/each}
</div>
{/if}
{#if bot.strategy_config?.actions && bot.strategy_config.actions.length > 0}
<div class="strategy-group">
<div class="strategy-group-label">Then:</div>
{#each bot.strategy_config.actions as action}
<div class="action-item">
<span class="action-icon">{action.type === 'buy' ? '🟢' : action.type === 'sell' ? '🔴' : '⏸️'}</span>
{formatAction(action)}
</div>
{/each}
</div>
{/if}
{#if bot.strategy_config?.risk_management}
<div class="strategy-group">
<div class="strategy-group-label">Risk:</div>
<div class="risk-item">
{#if bot.strategy_config.risk_management.stop_loss_percent}
<span class="risk-tag loss">Stop Loss: {bot.strategy_config.risk_management.stop_loss_percent}%</span>
{/if}
{#if bot.strategy_config.risk_management.take_profit_percent}
<span class="risk-tag profit">Take Profit: {bot.strategy_config.risk_management.take_profit_percent}%</span>
{/if}
</div>
</div>
{/if}
{:else}
<div class="no-strategy">
<div class="no-strategy-icon">⚙️</div>
<p>No strategy configured</p>
<span class="no-strategy-hint">Chat with the bot to set up your trading strategy</span>
</div>
{/if}
</div>
{#if onSelectBot}
<button class="btn btn-outline" onclick={onSelectBot}>
Change Bot
</button>
{/if}
<div class="action-buttons">
<h4>Tools</h4>
<div class="button-row">
<button
class="btn btn-tool btn-backtest"
onclick={onBacktest}
disabled={!bot || !hasStrategy}
>
📊 Backtest
</button>
<button
class="btn btn-tool btn-simulate"
onclick={onSimulate}
disabled={!bot || !hasStrategy}
>
🎮 Simulate
</button>
</div>
{#if !hasStrategy}
<p class="tool-hint">Configure a strategy first to use these tools</p>
{/if}
</div>
{/if}
</div>
<style>
.bot-info-panel {
padding: 1.25rem;
height: 100%;
overflow-y: auto;
}
h3 {
font-size: 0.85rem;
text-transform: uppercase;
letter-spacing: 0.5px;
color: #888;
margin: 0 0 1rem;
font-weight: 600;
}
h4 {
font-size: 0.8rem;
text-transform: uppercase;
letter-spacing: 0.5px;
color: #666;
margin: 1rem 0 0.75rem;
font-weight: 600;
}
.no-bot {
text-align: center;
padding: 1rem 0;
}
.no-bot p {
color: #666;
margin: 0 0 1rem;
}
.bot-details {
margin-bottom: 0.5rem;
}
.bot-name {
font-size: 1.25rem;
font-weight: 600;
color: #fff;
margin-bottom: 1rem;
}
.detail-row {
display: flex;
justify-content: space-between;
padding: 0.5rem 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}
.label {
color: #888;
font-size: 0.9rem;
}
.value {
color: #ccc;
font-size: 0.9rem;
}
.value.active {
color: #3fb950;
}
.strategy-section {
background: rgba(255, 255, 255, 0.03);
border-radius: 8px;
padding: 1rem;
margin-top: 0.5rem;
}
.strategy-group {
margin-bottom: 0.75rem;
}
.strategy-group:last-child {
margin-bottom: 0;
}
.strategy-group-label {
font-size: 0.75rem;
color: #667eea;
font-weight: 600;
text-transform: uppercase;
margin-bottom: 0.25rem;
}
.condition-item,
.action-item {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.35rem 0;
font-size: 0.85rem;
color: #ccc;
}
.condition-icon,
.action-icon {
font-size: 0.9rem;
}
.risk-item {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
}
.risk-tag {
font-size: 0.75rem;
padding: 0.25rem 0.5rem;
border-radius: 4px;
font-weight: 500;
}
.risk-tag.loss {
background: rgba(248, 81, 73, 0.2);
color: #f85149;
}
.risk-tag.profit {
background: rgba(63, 185, 80, 0.2);
color: #3fb950;
}
.no-strategy {
text-align: center;
padding: 1rem 0.5rem;
}
.no-strategy-icon {
font-size: 2rem;
margin-bottom: 0.5rem;
opacity: 0.5;
}
.no-strategy p {
color: #888;
margin: 0 0 0.25rem;
font-size: 0.9rem;
}
.no-strategy-hint {
font-size: 0.75rem;
color: #666;
}
.action-buttons {
margin-top: 1.5rem;
padding-top: 1rem;
border-top: 1px solid rgba(255, 255, 255, 0.1);
}
.action-buttons h4 {
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.5px;
color: #666;
margin: 0 0 0.75rem;
font-weight: 600;
}
.button-row {
display: flex;
gap: 0.5rem;
}
.btn-tool {
flex: 1;
padding: 0.6rem 0.5rem;
border-radius: 6px;
font-size: 0.8rem;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
gap: 0.35rem;
}
.btn-tool:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.btn-backtest {
background: rgba(102, 126, 234, 0.15);
color: #667eea;
border: 1px solid rgba(102, 126, 234, 0.3);
}
.btn-backtest:hover:not(:disabled) {
background: rgba(102, 126, 234, 0.25);
}
.btn-simulate {
background: rgba(63, 185, 80, 0.15);
color: #3fb950;
border: 1px solid rgba(63, 185, 80, 0.3);
}
.btn-simulate:hover:not(:disabled) {
background: rgba(63, 185, 80, 0.25);
}
.tool-hint {
font-size: 0.7rem;
color: #555;
margin: 0.5rem 0 0;
text-align: center;
}
.btn {
width: 100%;
padding: 0.75rem 1rem;
border-radius: 8px;
font-size: 0.9rem;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
margin-top: 1rem;
}
.btn-secondary {
background: rgba(255, 255, 255, 0.1);
color: #fff;
border: 1px solid rgba(255, 255, 255, 0.2);
}
.btn-secondary:hover {
background: rgba(255, 255, 255, 0.15);
}
.btn-outline {
background: transparent;
color: #667eea;
border: 1px solid #667eea;
}
.btn-outline:hover {
background: rgba(102, 126, 234, 0.1);
}
</style>

View File

@@ -0,0 +1,47 @@
<script lang="ts">
let { class: className = '' } = $props();
const bars = [0, 1, 2, 3];
const heights = ['12px', '18px', '14px', '20px'];
const delays = ['0s', '0.15s', '0.3s', '0.45s'];
</script>
<div class="flex items-center gap-1 h-8 {className}">
{#each bars as i}
<div
class="w-2 bg-green-500 rounded-sm animate-pulse"
style="height: {heights[i]}; animation-delay: {delays[i]};"
></div>
{/each}
</div>
<style>
.flex {
display: flex;
}
.items-center {
align-items: center;
}
.gap-1 {
gap: 0.25rem;
}
.h-8 {
height: 2rem;
}
.w-2 {
width: 0.5rem;
}
.bg-green-500 {
background-color: rgb(34 197 94);
}
.rounded-sm {
border-radius: 0.125rem;
}
.animate-pulse {
animation: pulse 1.5s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% { opacity: 0.4; transform: scaleY(1); }
50% { opacity: 1; transform: scaleY(1.2); }
}
</style>

View File

@@ -0,0 +1,188 @@
<script lang="ts">
import type { Message } from '$lib/api';
import { parseMarkdown, type ParsedSegment } from '$lib/utils/markdown';
import CandlestickLoader from './CandlestickLoader.svelte';
interface Props {
conversationId?: string;
messages?: Message[];
isLoading?: boolean;
}
let { conversationId, messages = [], isLoading = false }: Props = $props();
let chatContainer: HTMLDivElement;
function renderContent(content: string): ParsedSegment[] {
return parseMarkdown(content);
}
$effect(() => {
if (messages.length && chatContainer) {
setTimeout(() => {
chatContainer.scrollTop = chatContainer.scrollHeight;
}, 50);
}
});
</script>
<div class="chat-area" bind:this={chatContainer}>
{#if !conversationId}
<div class="empty-state">
Select a conversation or start a new one
</div>
{:else if messages.length === 0 && !isLoading}
<div class="empty-state">
Send a message to start the conversation
</div>
{:else}
<div class="messages">
{#each messages as msg (msg.id)}
<div class="message" class:user={msg.role === 'user'} class:assistant={msg.role === 'assistant'}>
<div class="message-content">
{#each renderContent(msg.content) as segment}
{#if segment.type === 'bold'}
<strong>{segment.content}</strong>
{:else if segment.type === 'italic'}
<em>{segment.content}</em>
{:else if segment.type === 'code'}
<code class="inline-code">{segment.content}</code>
{:else if segment.type === 'codeBlock'}
<pre class="code-block"><code>{segment.content}</code></pre>
{:else if segment.type === 'link'}
<a href={segment.content} target="_blank" rel="noopener noreferrer">{segment.content}</a>
{:else if segment.type === 'list' && segment.items}
<ul>
{#each segment.items as item}
<li>{item}</li>
{/each}
</ul>
{:else if segment.type === 'lineBreak'}
<br />
{:else}
{segment.content}
{/if}
{/each}
</div>
<div class="message-time">
{new Date(msg.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
</div>
</div>
{/each}
</div>
{/if}
{#if isLoading}
<div class="message assistant">
<div class="message-content">
<CandlestickLoader />
</div>
</div>
{/if}
</div>
<style>
.chat-area {
flex: 1;
overflow-y: auto;
padding: 1.5rem;
padding-bottom: 0.5rem;
}
.empty-state {
height: 100%;
display: flex;
align-items: center;
justify-content: center;
color: #666;
font-size: 1rem;
}
.messages {
display: flex;
flex-direction: column;
gap: 1rem;
}
.message {
display: flex;
flex-direction: column;
max-width: 75%;
}
.message.user {
align-self: flex-end;
align-items: flex-end;
}
.message.assistant {
align-self: flex-start;
align-items: flex-start;
}
.message-content {
padding: 0.875rem 1rem;
border-radius: 12px;
line-height: 1.6;
font-size: 0.95rem;
}
.message.user .message-content {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border-bottom-right-radius: 4px;
}
.message.assistant .message-content {
background: rgba(255, 255, 255, 0.08);
color: #e0e0e0;
border-bottom-left-radius: 4px;
}
.message-time {
font-size: 0.7rem;
color: #555;
margin-top: 0.25rem;
padding: 0 0.5rem;
}
.inline-code {
background: rgba(0, 0, 0, 0.3);
padding: 0.15rem 0.4rem;
border-radius: 4px;
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
font-size: 0.85em;
}
.code-block {
background: rgba(0, 0, 0, 0.4);
padding: 0.75rem;
border-radius: 8px;
overflow-x: auto;
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
font-size: 0.85rem;
margin: 0.5rem 0;
}
pre.code-block code {
white-space: pre;
}
ul {
margin: 0.5rem 0;
padding-left: 1.25rem;
}
li {
margin: 0.25rem 0;
}
a {
color: #667eea;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
</style>

View File

@@ -0,0 +1,113 @@
<script lang="ts">
interface Props {
onSend: (message: string) => void;
disabled?: boolean;
placeholder?: string;
}
let { onSend, disabled = false, placeholder = "Type a message..." }: Props = $props();
let messageInput = $state('');
let textarea: HTMLTextAreaElement;
function handleSend() {
if (!messageInput.trim() || disabled) return;
onSend(messageInput);
messageInput = '';
if (textarea) {
textarea.style.height = 'auto';
}
}
function handleKeydown(e: KeyboardEvent) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
}
function handleInput() {
if (textarea) {
textarea.style.height = 'auto';
textarea.style.height = Math.min(textarea.scrollHeight, 150) + 'px';
}
}
</script>
<div class="chat-input">
<textarea
bind:this={textarea}
bind:value={messageInput}
onkeydown={handleKeydown}
oninput={handleInput}
{placeholder}
{disabled}
rows="1"
></textarea>
<button onclick={handleSend} {disabled}>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/>
</svg>
</button>
</div>
<style>
.chat-input {
display: flex;
gap: 0.75rem;
padding: 1rem 1.25rem;
border-top: 1px solid rgba(255, 255, 255, 0.1);
background: rgba(0, 0, 0, 0.3);
flex-shrink: 0;
}
textarea {
flex: 1;
padding: 0.875rem 1rem;
border-radius: 12px;
border: 1px solid rgba(255, 255, 255, 0.2);
background: rgba(255, 255, 255, 0.05);
color: #fff;
font-size: 1rem;
font-family: inherit;
resize: none;
min-height: 48px;
max-height: 150px;
}
textarea:focus {
outline: none;
border-color: #667eea;
}
textarea::placeholder {
color: #666;
}
textarea:disabled {
opacity: 0.5;
cursor: not-allowed;
}
button {
padding: 0.75rem 1.25rem;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
border-radius: 12px;
cursor: pointer;
transition: transform 0.2s, opacity 0.2s;
display: flex;
align-items: center;
justify-content: center;
}
button:hover:not(:disabled) {
transform: translateY(-2px);
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
</style>

View File

@@ -3,12 +3,53 @@
import type { ChatMessage } from '$lib/stores/chatStore';
import { parseMarkdown, parseInlineElements, type InlineSegment } from '$lib/utils/markdown';
interface ToolGroup {
category: string;
label: string;
requiresBot: boolean;
tools: ToolItem[];
}
interface ToolItem {
name: string;
description: string;
command: string;
}
const TOOLS: ToolGroup[] = [
{
category: 'randebu',
label: '🤖 Randebu Built-in',
requiresBot: true,
tools: [
{ name: 'backtest', description: 'Run strategy backtest', command: '/backtest' },
{ name: 'simulate', description: 'Start/stop simulation', command: '/simulate' },
{ name: 'strategy', description: 'View/update strategy', command: '/strategy' },
]
},
{
category: 'ave',
label: '☁️ AVE Cloud Skills',
requiresBot: false,
tools: [
{ name: 'search', description: 'Token search', command: '/search' },
{ name: 'trending', description: 'Popular tokens', command: '/trending' },
{ name: 'risk', description: 'Honeypot detection', command: '/risk' },
{ name: 'token', description: 'Token details', command: '/token' },
{ name: 'price', description: 'Batch prices', command: '/price' },
]
}
];
interface Props {
bot: Bot | null;
messages: ChatMessage[];
isSending?: boolean;
isBlocked?: boolean;
blockedReason?: string | null;
onSendMessage: (message: string) => void;
onSelectBot?: (botId: string) => void;
onLogin?: () => void;
availableBots?: Bot[];
showBotSelector?: boolean;
}
@@ -17,8 +58,11 @@
bot,
messages,
isSending = false,
isBlocked = false,
blockedReason = null,
onSendMessage,
onSelectBot,
onLogin,
availableBots = [],
showBotSelector = false
}: Props = $props();
@@ -26,9 +70,33 @@
let messageInput = $state('');
let chatContainer: HTMLDivElement;
let expandedThinking: Record<string, boolean> = $state({});
let showSlashMenu = $state(false);
let slashMenuPosition = $state({ top: 0, left: 0 });
let selectedIndex = $state(0);
// Use $derived for filteredTools
// Filter tools based on whether user has a bot
let availableTools = $derived(
TOOLS.flatMap(t => !t.requiresBot || bot ? t.tools : [])
);
let filteredTools = $derived(
messageInput.startsWith('/')
? availableTools.filter(tool =>
tool.name.toLowerCase().startsWith(messageInput.slice(1).toLowerCase()) ||
tool.command.toLowerCase().startsWith(messageInput.slice(1).toLowerCase())
)
: []
);
// Get visible tool groups for the menu
let visibleGroups = $derived(
TOOLS.filter(group => !group.requiresBot || bot)
);
function handleSend() {
if (!messageInput.trim()) return;
showSlashMenu = false;
onSendMessage(messageInput);
messageInput = '';
}
@@ -36,8 +104,55 @@
function handleKeydown(e: KeyboardEvent) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
if (showSlashMenu && filteredTools.length > 0) {
selectTool(filteredTools[selectedIndex]);
} else {
handleSend();
}
} else if (e.key === 'ArrowDown' && showSlashMenu) {
e.preventDefault();
selectedIndex = Math.min(selectedIndex + 1, filteredTools.length - 1);
} else if (e.key === 'ArrowUp' && showSlashMenu) {
e.preventDefault();
selectedIndex = Math.max(selectedIndex - 1, 0);
} else if (e.key === 'Escape' && showSlashMenu) {
showSlashMenu = false;
} else if (e.key === 'Tab' && showSlashMenu && filteredTools.length > 0) {
e.preventDefault();
selectTool(filteredTools[selectedIndex]);
}
}
function handleInput(e: Event) {
const target = e.target as HTMLTextAreaElement;
const value = target.value;
messageInput = value;
if (value.startsWith('/')) {
selectedIndex = 0;
showSlashMenu = filteredTools.length > 0;
if (showSlashMenu) {
// Position menu above the textarea
const rect = target.getBoundingClientRect();
const menuHeight = 300;
slashMenuPosition = {
top: Math.max(10, rect.top - menuHeight),
left: rect.left
};
}
} else {
showSlashMenu = false;
}
}
function selectTool(tool: ToolItem) {
messageInput = tool.command + ' ';
showSlashMenu = false;
const textarea = document.querySelector('.input-container textarea') as HTMLTextAreaElement;
if (textarea) {
textarea.focus();
}
}
function handleBotChange(e: Event) {
@@ -74,8 +189,17 @@
}
}).join('');
}
function handleClickOutside(e: MouseEvent) {
const target = e.target as HTMLElement;
if (!target.closest('.slash-menu') && !target.closest('.input-container textarea')) {
showSlashMenu = false;
}
}
</script>
<svelte:window on:click={handleClickOutside} />
<div class="chat-interface">
{#if showBotSelector && availableBots.length > 0}
<div class="bot-selector">
@@ -213,21 +337,74 @@
{/if}
</div>
{#if bot}
<div class="input-container">
<textarea
bind:value={messageInput}
onkeydown={handleKeydown}
placeholder="Describe your trading strategy..."
rows="1"
></textarea>
<button onclick={handleSend}>
Send
{#if isBlocked}
<div class="blocked-message">
<div class="blocked-icon">🚫</div>
<div class="blocked-text">
{#if blockedReason === 'message_limit'}
<p><strong>Message Limit Reached</strong></p>
<p>You've used all 50 messages as an anonymous user.</p>
<p>Login to continue chatting with unlimited messages.</p>
{:else if blockedReason === 'bot_limit'}
<p><strong>Bot Limit Reached</strong></p>
<p>You've created the maximum of 1 bot as an anonymous user.</p>
<p>Login to create more bots.</p>
{:else if blockedReason === 'backtest_limit'}
<p><strong>Backtest Limit Reached</strong></p>
<p>You've run the maximum of 1 backtest as an anonymous user.</p>
<p>Login to run more backtests.</p>
{:else}
<p><strong>Action Blocked</strong></p>
<p>Please login to continue.</p>
{/if}
<button class="login-button" onclick={() => onLogin?.()}>
Login to Continue
</button>
</div>
</div>
{:else}
{#if showSlashMenu && filteredTools.length > 0}
<div class="slash-menu" style="top: {slashMenuPosition.top}px; left: {slashMenuPosition.left}px;">
<div class="slash-menu-header">Available Commands</div>
{#each visibleGroups as group}
{#if group.tools.some(t => filteredTools.includes(t))}
<div class="slash-menu-category">{group.label}</div>
{#each group.tools.filter(t => filteredTools.includes(t)) as tool, i}
<button
class="slash-menu-item"
class:selected={filteredTools.indexOf(tool) === selectedIndex}
onclick={() => selectTool(tool)}
>
<span class="slash-command">{tool.command}</span>
<span class="slash-description">{tool.description}</span>
</button>
{/each}
{/if}
{/each}
<div class="slash-menu-hint">
{#if !bot}
Login to access bot commands
{:else}
Press Tab to select, Enter to send
{/if}
</div>
</div>
{/if}
<textarea
value={messageInput}
oninput={handleInput}
onkeydown={handleKeydown}
placeholder="Describe your trading strategy... (or type / for commands)"
rows="1"
disabled={isSending}
></textarea>
<button onclick={handleSend} disabled={isSending || !messageInput.trim()}>
Send
</button>
{/if}
</div>
</div>
<style>
.chat-interface {
display: flex;
@@ -511,6 +688,56 @@
}
}
.blocked-message {
display: flex;
align-items: center;
gap: 1rem;
padding: 1rem;
background: rgba(251, 191, 36, 0.1);
border: 1px solid rgba(251, 191, 36, 0.3);
border-radius: 12px;
width: 100%;
}
.blocked-icon {
font-size: 2rem;
}
.blocked-text {
flex: 1;
}
.blocked-text p {
margin: 0.25rem 0;
font-size: 0.9rem;
color: #fbbf24;
}
.blocked-text p:first-child {
margin-top: 0;
}
.blocked-text p:last-child {
margin-bottom: 0;
}
.login-button {
padding: 0.75rem 1.5rem;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
border-radius: 8px;
font-size: 0.9rem;
font-weight: 500;
cursor: pointer;
transition: transform 0.2s;
white-space: nowrap;
}
.login-button:hover {
transform: translateY(-2px);
}
.input-container {
display: flex;
gap: 0.75rem;
@@ -555,4 +782,76 @@
opacity: 0.5;
cursor: not-allowed;
}
.slash-menu {
position: fixed;
background: rgba(20, 20, 20, 0.98);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 12px;
padding: 0.5rem;
min-width: 280px;
max-width: 400px;
max-height: 300px;
overflow-y: auto;
z-index: 1000;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
}
.slash-menu-header {
font-size: 0.75rem;
color: #888;
padding: 0.5rem 0.75rem;
text-transform: uppercase;
letter-spacing: 0.5px;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
margin-bottom: 0.5rem;
}
.slash-menu-category {
font-size: 0.75rem;
color: #666;
padding: 0.5rem 0.75rem 0.25rem;
}
.slash-menu-item {
display: flex;
flex-direction: column;
align-items: flex-start;
width: 100%;
padding: 0.5rem 0.75rem;
background: transparent;
border: none;
border-radius: 8px;
cursor: pointer;
text-align: left;
transition: background 0.15s;
margin: 0.15rem 0;
}
.slash-menu-item:hover,
.slash-menu-item.selected {
background: rgba(102, 126, 234, 0.2);
}
.slash-command {
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
font-size: 0.9rem;
color: #667eea;
font-weight: 500;
}
.slash-description {
font-size: 0.8rem;
color: #888;
margin-top: 0.15rem;
}
.slash-menu-hint {
font-size: 0.7rem;
color: #555;
padding: 0.5rem 0.75rem;
border-top: 1px solid rgba(255, 255, 255, 0.1);
margin-top: 0.5rem;
text-align: center;
}
</style>

View File

@@ -0,0 +1,82 @@
<script lang="ts">
import type { Component } from 'svelte';
interface Props {
leftPane?: Component;
rightPane?: Component;
rightPaneProps?: Record<string, any>;
children?: any;
}
let { leftPane: LeftPane, rightPane: RightPane, rightPaneProps = {}, children }: Props = $props();
</script>
<div class="chat-layout">
{#if LeftPane}
<aside class="sidebar-left">
<LeftPane />
</aside>
{/if}
<main class="main-content">
{#if children}
{@render children()}
{/if}
</main>
{#if RightPane}
<aside class="sidebar-right">
<RightPane {...rightPaneProps} />
</aside>
{/if}
</div>
<style>
.chat-layout {
display: flex;
height: 100%;
width: 100%;
}
.sidebar-left {
width: 280px;
border-right: 1px solid rgba(255, 255, 255, 0.1);
flex-shrink: 0;
overflow: hidden;
}
.main-content {
flex: 1;
display: flex;
flex-direction: column;
min-width: 0;
overflow: hidden;
background: #0f0f0f;
}
.sidebar-right {
width: 300px;
border-left: 1px solid rgba(255, 255, 255, 0.1);
flex-shrink: 0;
overflow-y: auto;
background: rgba(0, 0, 0, 0.2);
}
@media (max-width: 1024px) {
.sidebar-right {
display: none;
}
}
@media (max-width: 768px) {
.sidebar-left {
width: 100%;
position: absolute;
left: 0;
top: 0;
bottom: 0;
z-index: 100;
background: #0f0f0f;
}
}
</style>

View File

@@ -0,0 +1,178 @@
<script lang="ts">
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { page } from '$app/stores';
import { api } from '$lib/api';
import { conversationStore, setConversations, addConversation } from '$lib/stores';
let conversations = $state<any[]>([]);
let loading = $state(true);
let error = $state<string | null>(null);
$effect(() => {
const unsub = conversationStore.subscribe(state => {
conversations = state.conversations;
});
return unsub;
});
onMount(async () => {
await loadConversations();
});
async function loadConversations() {
loading = true;
error = null;
try {
const data = await api.conversations.list();
setConversations(data);
} catch (e) {
error = e instanceof Error ? e.message : 'Failed to load conversations';
setConversations([]);
} finally {
loading = false;
}
}
async function createConversation() {
try {
const newConv = await api.conversations.create();
addConversation(newConv);
goto(`/chat/${newConv.id}`);
} catch (e) {
console.error('Failed to create conversation:', e);
}
}
function formatDate(dateStr: string): string {
const date = new Date(dateStr);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMs / 3600000);
const diffDays = Math.floor(diffMs / 86400000);
if (diffMins < 1) return 'just now';
if (diffMins < 60) return `${diffMins}m ago`;
if (diffHours < 24) return `${diffHours}h ago`;
if (diffDays < 7) return `${diffDays}d ago`;
return date.toLocaleDateString();
}
function isActiveConversation(convId: string): boolean {
return $page.params.conversationId === convId;
}
</script>
<div class="conversation-list">
<div class="header">
<button class="new-chat-btn" onclick={createConversation}>
+ New Chat
</button>
</div>
<div class="list">
{#if loading}
<div class="loading">Loading...</div>
{:else if error}
<div class="error">{error}</div>
{:else if conversations.length === 0}
<div class="empty">No conversations yet</div>
{:else}
{#each conversations as conv (conv.id)}
<button
class="conversation-item"
class:active={isActiveConversation(conv.id)}
onclick={() => goto(`/chat/${conv.id}`)}
>
<div class="conv-title">{conv.title || 'New Chat'}</div>
<div class="conv-date">{formatDate(conv.updated_at)}</div>
</button>
{/each}
{/if}
</div>
</div>
<style>
.conversation-list {
height: 100%;
display: flex;
flex-direction: column;
background: #0f0f0f;
}
.header {
padding: 0.75rem;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.new-chat-btn {
width: 100%;
padding: 0.75rem;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
border-radius: 8px;
font-size: 0.95rem;
font-weight: 500;
cursor: pointer;
transition: transform 0.2s;
}
.new-chat-btn:hover {
transform: translateY(-2px);
}
.list {
flex: 1;
overflow-y: auto;
}
.loading,
.error,
.empty {
padding: 1.5rem;
text-align: center;
color: #666;
font-size: 0.9rem;
}
.error {
color: #f87171;
}
.conversation-item {
width: 100%;
padding: 0.875rem 1rem;
background: transparent;
border: none;
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
text-align: left;
cursor: pointer;
transition: background 0.15s;
}
.conversation-item:hover {
background: rgba(255, 255, 255, 0.05);
}
.conversation-item.active {
background: rgba(102, 126, 234, 0.15);
border-left: 3px solid #667eea;
}
.conv-title {
color: #e0e0e0;
font-size: 0.95rem;
font-weight: 500;
margin-bottom: 0.25rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.conv-date {
color: #666;
font-size: 0.75rem;
}
</style>

View File

@@ -9,3 +9,11 @@ export { default as BacktestChart } from './BacktestChart.svelte';
export { default as ProUpgradeBanner } from './ProUpgradeBanner.svelte';
export { default as TokenPicker } from './TokenPicker.svelte';
export { default as ConditionBuilder } from './ConditionBuilder.svelte';
export { default as ChatLayout } from './ChatLayout.svelte';
export { default as ConversationList } from './ConversationList.svelte';
export { default as ChatArea } from './ChatArea.svelte';
export { default as ChatInput } from './ChatInput.svelte';
export { default as BotInfoPanel } from './BotInfoPanel.svelte';
export { default as AnonymousBanner } from './AnonymousBanner.svelte';
export { default as CandlestickLoader } from './CandlestickLoader.svelte';
export { default as AppHeader } from './AppHeader.svelte';

View File

@@ -10,7 +10,7 @@ export interface ChatMessage {
}
// Fallback UUID generator for environments where crypto.randomUUID is not available
function generateId(): string {
export function generateId(): string {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return crypto.randomUUID();
}

View File

@@ -0,0 +1,96 @@
import { writable, derived } from 'svelte/store';
import type { Conversation, Message } from '$lib/api';
export interface ConversationState {
conversations: Conversation[];
currentConversationId: string | null;
messages: Message[];
isLoading: boolean;
error: string | null;
anonymousChatCount: number;
}
const initialState: ConversationState = {
conversations: [],
currentConversationId: null,
messages: [],
isLoading: false,
error: null,
anonymousChatCount: 0
};
export const conversationStore = writable<ConversationState>(initialState);
export function setConversations(conversations: Conversation[]) {
conversationStore.update(state => ({ ...state, conversations }));
}
export function addConversation(conversation: Conversation) {
conversationStore.update(state => ({
...state,
conversations: [conversation, ...state.conversations]
}));
}
export function removeConversation(conversationId: string) {
conversationStore.update(state => ({
...state,
conversations: state.conversations.filter(c => c.id !== conversationId),
currentConversationId: state.currentConversationId === conversationId ? null : state.currentConversationId
}));
}
export function setCurrentConversation(conversationId: string | null) {
conversationStore.update(state => ({
...state,
currentConversationId: conversationId,
messages: []
}));
}
export function setMessages(messages: Message[]) {
conversationStore.update(state => ({ ...state, messages }));
}
export function addMessage(message: Message) {
conversationStore.update(state => ({
...state,
messages: [...state.messages, message]
}));
}
export function setLoading(isLoading: boolean) {
conversationStore.update(state => ({ ...state, isLoading }));
}
export function setError(error: string | null) {
conversationStore.update(state => ({ ...state, error }));
}
export function incrementAnonymousChatCount() {
conversationStore.update(state => ({
...state,
anonymousChatCount: state.anonymousChatCount + 1
}));
}
export function resetAnonymousChatCount() {
conversationStore.update(state => ({
...state,
anonymousChatCount: 0
}));
}
export function updateConversationTitle(conversationId: string, title: string) {
conversationStore.update(state => ({
...state,
conversations: state.conversations.map(c =>
c.id === conversationId ? { ...c, title, updated_at: new Date().toISOString() } : c
)
}));
}
export const currentConversation = derived(
conversationStore,
$state => $state.conversations.find(c => c.id === $state.currentConversationId) ?? null
);

View File

@@ -28,3 +28,18 @@ export {
register,
logout
} from './authStore';
export {
conversationStore,
setConversations,
addConversation,
removeConversation,
setCurrentConversation,
setMessages as setConversationMessages,
addMessage as addConversationMessage,
setLoading as setConversationLoading,
setError as setConversationError,
incrementAnonymousChatCount,
resetAnonymousChatCount,
updateConversationTitle,
currentConversation
} from './conversationStore';

View File

@@ -14,7 +14,7 @@ export interface ParsedSegment {
content: string;
items?: string[];
headers?: InlineSegment[][];
rows?: InlineSegment[][];
rows?: InlineSegment[][][];
}
export function parseMarkdown(text: string): ParsedSegment[] {

View File

@@ -7,6 +7,13 @@
onMount(() => {
initAuth();
// Reset anonymous counts on layout load (for debugging)
const count = localStorage.getItem('anonymous_chat_count');
if (count && parseInt(count) >= 50) {
console.log('Resetting anonymous_chat_count from', count, 'to 0');
localStorage.setItem('anonymous_chat_count', '0');
}
});
</script>

View File

@@ -16,8 +16,7 @@
<h1>Randebu</h1>
<p class="tagline">Create trading bots through conversation with AI</p>
<div class="cta">
<a href="/register" class="btn btn-primary">Get Started</a>
<a href="/login" class="btn btn-secondary">Login</a>
<a href="/chat" class="btn btn-primary">Try Now - Free</a>
</div>
</div>

View File

@@ -53,7 +53,7 @@
isSending = true;
// Add user's message immediately so it shows even before API response
addMessage({ role: 'user', content: message });
addMessage({ role: 'user', content: message, thinking: null });
try {
// Add timeout to prevent hanging requests

View File

@@ -0,0 +1,110 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { api } from '$lib/api';
import { isAuthenticated } from '$lib/stores';
import ChatLayout from '$lib/components/ChatLayout.svelte';
import ConversationList from '$lib/components/ConversationList.svelte';
import AnonymousBanner from '$lib/components/AnonymousBanner.svelte';
import AppHeader from '$lib/components/AppHeader.svelte';
let anonymousChatCount = $state(0);
async function createNewChat() {
try {
const conv = await api.conversations.create();
goto(`/chat/${conv.id}`);
} catch (e) {
console.error('Failed to create conversation:', e);
}
}
</script>
<svelte:head>
<title>Chat - Randebu</title>
</svelte:head>
<main>
<AppHeader />
{#if !$isAuthenticated}
<AnonymousBanner chatCount={anonymousChatCount} />
{/if}
<div class="content">
<ChatLayout leftPane={ConversationList}>
<div class="empty-state">
<div class="empty-content">
<h2>Start a Conversation</h2>
<p>Select a conversation from the sidebar or create a new one</p>
<button class="btn btn-primary" onclick={createNewChat}>
+ New Chat
</button>
</div>
</div>
</ChatLayout>
</div>
</main>
<style>
:global(body) {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #0f0f0f;
color: #fff;
}
main {
height: 100vh;
display: flex;
flex-direction: column;
}
.content {
flex: 1;
display: flex;
overflow: hidden;
}
.empty-state {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #0f0f0f 0%, #1a1a2e 100%);
}
.empty-content {
text-align: center;
}
h2 {
font-size: 1.5rem;
margin: 0 0 0.5rem;
color: #fff;
}
p {
font-size: 1rem;
color: #888;
margin: 0 0 1.5rem;
}
.btn {
padding: 0.75rem 1.5rem;
border-radius: 12px;
font-size: 1rem;
font-weight: 500;
cursor: pointer;
border: none;
transition: transform 0.2s;
}
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.btn:hover {
transform: translateY(-2px);
}
</style>

View File

@@ -0,0 +1,585 @@
<script lang="ts">
import { page } from '$app/stores';
import { goto } from '$app/navigation';
import { api } from '$lib/api';
import { isAuthenticated } from '$lib/stores';
import type { Message, Bot, ConversationWithMessages } from '$lib/api';
import { generateId, type ChatMessage } from '$lib/stores/chatStore';
import ChatLayout from '$lib/components/ChatLayout.svelte';
import ConversationList from '$lib/components/ConversationList.svelte';
import ChatInterface from '$lib/components/ChatInterface.svelte';
import BotInfoPanel from '$lib/components/BotInfoPanel.svelte';
import AnonymousBanner from '$lib/components/AnonymousBanner.svelte';
import AppHeader from '$lib/components/AppHeader.svelte';
import CandlestickLoader from '$lib/components/CandlestickLoader.svelte';
let conversationId = $derived($page.params.conversationId);
let messages = $state<ChatMessage[]>([]);
let currentBot = $state<Bot | null>(null);
let isLoading = $state(false);
let error = $state<string | null>(null);
let isSending = $state(false);
let anonymousChatCount = $state(0);
let hasShownLoginPrompt = $state(false); // Track if we've already shown the login prompt
let isBlocked = $state(false); // Track if user is blocked due to limits
let blockedReason = $state<string | null>(null); // Reason for being blocked
// Initialize from localStorage
$effect(() => {
const storedCount = localStorage.getItem('anonymous_chat_count');
if (storedCount) {
anonymousChatCount = parseInt(storedCount, 10);
}
const shownPrompt = localStorage.getItem('shown_login_prompt');
hasShownLoginPrompt = shownPrompt === 'true';
});
let currentConversation = $state<ConversationWithMessages | null>(null);
let showBacktestModal = $state(false); // Show backtest configuration modal
let showSimulateModal = $state(false); // Show simulation configuration modal
// Convert Message[] to ChatMessage[] for ChatInterface
function convertMessages(apiMessages: Message[]): ChatMessage[] {
return apiMessages.map(msg => ({
id: msg.id,
role: msg.role,
content: msg.content,
thinking: null,
timestamp: new Date(msg.created_at)
}));
}
$effect(() => {
if (conversationId) {
loadConversation(conversationId);
} else {
messages = [];
currentBot = null;
}
});
async function loadConversation(id: string) {
isLoading = true;
error = null;
try {
// First, try to load as bot ID (direct bot link from dashboard)
try {
const bot = await api.bots.get(id);
currentBot = bot;
messages = [];
currentConversation = null;
isLoading = false;
return;
} catch {
// Not a bot, continue to try conversation
}
// Try to load as conversation
const conv = await api.conversations.get(id);
currentConversation = conv;
messages = convertMessages(conv.messages);
if (conv.bot_id) {
try {
currentBot = await api.bots.get(conv.bot_id);
} catch (e) {
console.error('Failed to load bot:', e);
currentBot = null;
}
} else {
currentBot = null;
}
} catch (e) {
error = e instanceof Error ? e.message : 'Failed to load conversation';
messages = [];
currentBot = null;
} finally {
isLoading = false;
}
}
async function handleSendMessage(message: string) {
if (!conversationId) return;
if (!$isAuthenticated) {
if (anonymousChatCount >= 50) {
// Show confirmation dialog before redirecting
isBlocked = true;
blockedReason = 'message_limit';
error = 'You have reached the maximum of 50 messages. Login to continue with unlimited messages.';
return; // Don't redirect automatically, show blocked state instead
}
// Show login prompt only once when reaching warning threshold (40 messages)
if (anonymousChatCount >= 40 && !hasShownLoginPrompt) {
hasShownLoginPrompt = true;
localStorage.setItem('shown_login_prompt', 'true');
const proceed = confirm('You are about to reach your message limit (40/50). Login now to save your progress and continue chatting.');
if (proceed) {
goto('/login');
return;
}
}
}
isSending = true;
error = null;
// Optimistically add user's message to the chat
const userMessage: ChatMessage = {
id: generateId(),
role: 'user',
content: message,
thinking: null,
timestamp: new Date()
};
messages = [...messages, userMessage];
try {
let updatedConv;
// If we have a bot loaded directly (from dashboard), use bot chat
// Otherwise, use conversation chat
console.log('handleSendMessage: currentBot=', currentBot, 'conversationId=', conversationId);
if (currentBot) {
console.log('Using bot chat for bot:', currentBot.id);
updatedConv = await api.bots.chat(currentBot.id, message);
// Bot chat returns the assistant response directly
const assistantMessage: ChatMessage = {
id: generateId(),
role: 'assistant',
content: updatedConv.response,
thinking: updatedConv.thinking || null,
timestamp: new Date()
};
messages = [...messages, assistantMessage];
} else {
updatedConv = await api.conversations.chat(conversationId, message);
messages = convertMessages(updatedConv.messages);
currentConversation = updatedConv;
if (updatedConv.bot_id && (!currentBot || currentBot.id !== updatedConv.bot_id)) {
try {
currentBot = await api.bots.get(updatedConv.bot_id);
} catch (e) {
console.error('Failed to load bot:', e);
}
}
}
if (!$isAuthenticated) {
anonymousChatCount++;
localStorage.setItem('anonymous_chat_count', String(anonymousChatCount));
}
} catch (e: any) {
console.error('=== CHAT ERROR CAUGHT ===', e);
console.error('Error status:', e.status);
console.error('Error message:', e.message);
// Remove the optimistic user message if the request failed
messages = messages.filter(m => m.id !== userMessage.id);
const status = e.status || (e.response && e.response.status);
const errorMsg = e.message || (e.response && e.response.data && e.response.data.detail) || 'Unknown error';
if (status === 429) {
error = 'Rate limited from the agent service. Please come back later.';
} else if (status === 403 || status === 401) {
// Check which limit was hit based on error message
if (errorMsg.includes('bot')) {
isBlocked = true;
blockedReason = 'bot_limit';
error = "You've reached the maximum number of bots (1) as an anonymous user. Login to create more bots.";
} else if (errorMsg.includes('backtest')) {
isBlocked = true;
blockedReason = 'backtest_limit';
error = "You've reached the maximum number of backtests (1) as an anonymous user. Login to run more.";
} else {
isBlocked = true;
blockedReason = 'message_limit';
error = "You've reached the maximum number of messages (50) as an anonymous user. Login to continue chatting.";
}
} else {
error = errorMsg || 'Failed to send message';
}
} finally {
isSending = false;
}
}
function handleSelectBot() {
goto('/dashboard');
}
function handleBacktest() {
showBacktestModal = true;
}
function handleSimulate() {
showSimulateModal = true;
}
async function runBacktest(config: { token_address: string; timeframe: string; start_date: string; end_date: string }) {
if (!currentBot) return;
isSending = true;
error = null;
showBacktestModal = false;
// Add user message
const userMessage: ChatMessage = {
id: generateId(),
role: 'user',
content: `/backtest ${config.token_address} ${config.timeframe} ${config.start_date} ${config.end_date}`,
timestamp: new Date()
};
messages = [...messages, userMessage];
try {
const result = await api.backtest.start(currentBot.id, {
token: config.token_address,
timeframe: config.timeframe,
start_date: config.start_date,
end_date: config.end_date
});
// Add bot response
const botMessage: ChatMessage = {
id: generateId(),
role: 'assistant',
content: `Backtest started! ID: ${result.id}\nStatus: ${result.status}`,
timestamp: new Date()
};
messages = [...messages, botMessage];
} catch (e: any) {
messages = messages.filter(m => m.id !== userMessage.id);
error = e.message || 'Failed to start backtest';
} finally {
isSending = false;
}
}
async function runSimulate(config: { token_address: string; kline_interval: string; action: string }) {
if (!currentBot) return;
isSending = true;
error = null;
showSimulateModal = false;
// Add user message
const userMessage: ChatMessage = {
id: generateId(),
role: 'user',
content: `/simulate ${config.action} ${config.token_address} ${config.kline_interval}`,
timestamp: new Date()
};
messages = [...messages, userMessage];
try {
const result = await api.simulate.start(currentBot.id, {
token: config.token_address,
kline_interval: config.kline_interval
});
// Add bot response
const botMessage: ChatMessage = {
id: generateId(),
role: 'assistant',
content: `Simulation ${config.action}! Token: ${config.token_address}\nInterval: ${config.kline_interval}`,
timestamp: new Date()
};
messages = [...messages, botMessage];
} catch (e: any) {
messages = messages.filter(m => m.id !== userMessage.id);
error = e.message || 'Failed to ${config.action} simulation';
} finally {
isSending = false;
}
}
</script>
<svelte:head>
<title>Chat - Randebu</title>
</svelte:head>
<main>
<AppHeader />
{#if !$isAuthenticated}
<AnonymousBanner chatCount={anonymousChatCount} />
{/if}
<div class="content">
<ChatLayout
leftPane={ConversationList}
rightPane={BotInfoPanel}
rightPaneProps={{
bot: currentBot,
onSelectBot: handleSelectBot,
onBacktest: handleBacktest,
onSimulate: handleSimulate
}}
>
{#if error}
<div class="error-banner">
{error}
</div>
{/if}
{#if isLoading}
<div class="loading">
<CandlestickLoader />
</div>
{:else if conversationId}
<ChatInterface
bot={currentBot}
messages={messages}
isSending={isSending}
isBlocked={isBlocked}
blockedReason={blockedReason}
onSendMessage={handleSendMessage}
onSelectBot={handleSelectBot}
onLogin={() => goto('/login')}
/>
{:else}
<div class="empty-state">
Select a conversation or start a new one
</div>
{/if}
</ChatLayout>
<!-- Backtest Modal -->
{#if showBacktestModal}
<div class="modal-overlay" onclick={() => showBacktestModal = false}>
<div class="modal" onclick={(e) => e.stopPropagation()}>
<h3>Run Backtest</h3>
<form onsubmit={(e) => {
e.preventDefault();
const form = e.target as HTMLFormElement;
const fd = new FormData(form);
runBacktest({
token_address: fd.get('token_address') as string,
timeframe: fd.get('timeframe') as string,
start_date: fd.get('start_date') as string,
end_date: fd.get('end_date') as string
});
}}>
<div class="form-group">
<label for="bt-token">Token Contract Address</label>
<input type="text" id="bt-token" name="token_address" required placeholder="0x..." />
</div>
<div class="form-row">
<div class="form-group">
<label for="bt-timeframe">Timeframe</label>
<select id="bt-timeframe" name="timeframe">
<option value="1d">1 Day</option>
<option value="4h">4 Hours</option>
<option value="1h">1 Hour</option>
<option value="15m">15 Minutes</option>
</select>
</div>
<div class="form-group">
<label for="bt-start">Start Date</label>
<input type="date" id="bt-start" name="start_date" value="2025-01-01" />
</div>
<div class="form-group">
<label for="bt-end">End Date</label>
<input type="date" id="bt-end" name="end_date" value="2026-01-01" />
</div>
</div>
<div class="modal-buttons">
<button type="button" class="btn-cancel" onclick={() => showBacktestModal = false}>Cancel</button>
<button type="submit" class="btn-submit">Run Backtest</button>
</div>
</form>
</div>
</div>
{/if}
<!-- Simulation Modal -->
{#if showSimulateModal}
<div class="modal-overlay" onclick={() => showSimulateModal = false}>
<div class="modal" onclick={(e) => e.stopPropagation()}>
<h3>Run Simulation</h3>
<form onsubmit={(e) => {
e.preventDefault();
const form = e.target as HTMLFormElement;
const fd = new FormData(form);
runSimulate({
token_address: fd.get('token_address') as string,
kline_interval: fd.get('kline_interval') as string,
action: 'start'
});
}}>
<div class="form-group">
<label for="sim-token">Token Contract Address</label>
<input type="text" id="sim-token" name="token_address" required placeholder="0x..." />
</div>
<div class="form-group">
<label for="sim-interval">Kline Interval</label>
<select id="sim-interval" name="kline_interval">
<option value="1m">1 Minute</option>
<option value="5m">5 Minutes</option>
<option value="15m">15 Minutes</option>
<option value="1h">1 Hour</option>
<option value="4h">4 Hours</option>
</select>
</div>
<div class="modal-buttons">
<button type="button" class="btn-cancel" onclick={() => showSimulateModal = false}>Cancel</button>
<button type="submit" class="btn-submit">Start Simulation</button>
</div>
</form>
</div>
</div>
{/if}
</div>
</main>
<style>
:global(body) {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #0f0f0f;
color: #fff;
}
main {
height: 100vh;
display: flex;
flex-direction: column;
}
.content {
flex: 1;
display: flex;
overflow: hidden;
}
.modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.7);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.modal {
background: #1a1a1a;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 12px;
padding: 1.5rem;
width: 400px;
max-width: 90vw;
}
.modal h3 {
margin: 0 0 1.25rem;
font-size: 1.1rem;
color: #fff;
}
.form-group {
margin-bottom: 1rem;
}
.form-group label {
display: block;
font-size: 0.8rem;
color: #888;
margin-bottom: 0.35rem;
}
.form-group input,
.form-group select {
width: 100%;
padding: 0.6rem 0.75rem;
background: #0f0f0f;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 6px;
color: #fff;
font-size: 0.9rem;
box-sizing: border-box;
}
.form-group input:focus,
.form-group select:focus {
outline: none;
border-color: #667eea;
}
.form-row {
display: flex;
gap: 0.75rem;
}
.form-row .form-group {
flex: 1;
}
.modal-buttons {
display: flex;
gap: 0.75rem;
margin-top: 1.25rem;
}
.btn-cancel {
flex: 1;
padding: 0.7rem;
background: transparent;
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 6px;
color: #ccc;
cursor: pointer;
font-size: 0.9rem;
}
.btn-cancel:hover {
background: rgba(255, 255, 255, 0.05);
}
.btn-submit {
flex: 1;
padding: 0.7rem;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: none;
border-radius: 6px;
color: white;
cursor: pointer;
font-size: 0.9rem;
font-weight: 500;
}
.btn-submit:hover {
opacity: 0.9;
}
.error-banner {
padding: 0.75rem 1rem;
background: rgba(220, 38, 38, 0.2);
border-bottom: 1px solid rgba(220, 38, 38, 0.3);
color: #fca5a5;
font-size: 0.9rem;
}
.loading {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
}
.empty-state {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
color: #888;
font-size: 1rem;
}
</style>

View File

@@ -40,7 +40,7 @@
showCreateModal = false;
newBotName = '';
newBotDescription = '';
goto(`/bot/${bot.id}`);
goto(`/chat/${bot.id}`);
} catch (e) {
createError = e instanceof Error ? e.message : 'Failed to create bot';
} finally {
@@ -96,7 +96,7 @@
{:else}
<div class="bots-grid">
{#each $botsStore as bot}
<BotCard {bot} onOpen={(id) => goto(`/bot/${id}`)} onDelete={deleteBot} />
<BotCard {bot} onDelete={deleteBot} />
{/each}
</div>
{/if}

View File

@@ -0,0 +1,166 @@
<script lang="ts">
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { api } from '$lib/api';
import { isAuthenticated } from '$lib/stores';
import ChatLayout from '$lib/components/ChatLayout.svelte';
import ConversationList from '$lib/components/ConversationList.svelte';
import AnonymousBanner from '$lib/components/AnonymousBanner.svelte';
import AppHeader from '$lib/components/AppHeader.svelte';
let anonymousChatCount = $state(0);
onMount(async () => {
// Check if there's an anonymous token in cookies
const cookies = document.cookie.split(';');
const anonToken = cookies.find(c => c.trim().startsWith('anonymous_token='));
if (anonToken) {
// Count would be tracked server-side, for now just track locally
const stored = localStorage.getItem('anonymous_chat_count');
anonymousChatCount = stored ? parseInt(stored, 10) : 0;
}
});
</script>
<svelte:head>
<title>Randebu - AI Trading Bot Platform</title>
</svelte:head>
<main>
<AppHeader />
{#if !$isAuthenticated}
<AnonymousBanner chatCount={anonymousChatCount} />
{/if}
<div class="content">
<ChatLayout leftPane={ConversationList}>
<div class="welcome-screen">
<div class="welcome-content">
<h1>Welcome to Randebu</h1>
<p class="subtitle">Create trading bots through conversation with AI</p>
<div class="steps">
<div class="step">
<div class="step-number">1</div>
<div class="step-content">
<h3>Describe Your Strategy</h3>
<p>Tell our AI what kind of trading you want in plain English</p>
</div>
</div>
<div class="step">
<div class="step-number">2</div>
<div class="step-content">
<h3>Backtest & Validate</h3>
<p>Test your strategy against historical data</p>
</div>
</div>
<div class="step">
<div class="step-number">3</div>
<div class="step-content">
<h3>Simulate & Monitor</h3>
<p>Run real-time simulations and watch for signals</p>
</div>
</div>
</div>
<p class="hint">Select a conversation from the left or start a new one to begin</p>
</div>
</div>
</ChatLayout>
</div>
</main>
<style>
:global(body) {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #0f0f0f;
color: #fff;
}
main {
height: 100vh;
display: flex;
flex-direction: column;
}
.content {
flex: 1;
display: flex;
overflow: hidden;
}
.welcome-screen {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #0f0f0f 0%, #1a1a2e 100%);
}
.welcome-content {
text-align: center;
max-width: 500px;
padding: 2rem;
}
h1 {
font-size: 2.5rem;
margin: 0 0 0.5rem;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.subtitle {
font-size: 1.2rem;
color: #888;
margin: 0 0 2.5rem;
}
.steps {
display: flex;
flex-direction: column;
gap: 1.5rem;
text-align: left;
}
.step {
display: flex;
align-items: flex-start;
gap: 1rem;
}
.step-number {
width: 32px;
height: 32px;
border-radius: 50%;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
display: flex;
align-items: center;
justify-content: center;
font-weight: 600;
flex-shrink: 0;
}
.step-content h3 {
margin: 0 0 0.25rem;
font-size: 1.1rem;
color: #fff;
}
.step-content p {
margin: 0;
font-size: 0.9rem;
color: #888;
}
.hint {
margin-top: 2.5rem;
font-size: 0.9rem;
color: #666;
}
</style>