Compare commits

...

12 Commits

33 changed files with 1318 additions and 0 deletions

0
.gitignore vendored Normal file
View File

View File

@@ -0,0 +1,79 @@
You are tasked with generating a PineScript trading strategy that works in TradingView's strategy tester and can be used to send actual orders to a brokerage. Follow these instructions carefully to create a strategy based on the provided framework.
1. Trend Determination:
Analyze the user's input for trend determination:
<user_trend_indicator>
{{USER_TREND_INDICATOR}}
</user_trend_indicator>
If the user has provided a specific indicator, use it. Otherwise, choose an appropriate indicator to determine the market trend. Ensure that the strategy only allows entries aligned with the trend.
2. Entry Confirmations:
Review the user's input for entry confirmations:
<user_entry_confirmations>
{{USER_ENTRY_CONFIRMATIONS}}
</user_entry_confirmations>
Implement between 1 and 3 confirmations for entry. If the user has provided specific indicators, use them. Otherwise, select appropriate indicators that complement the trend determination.
3. Exit Strategy:
Examine the user's input for the exit strategy:
<user_exit_strategy>
{{USER_EXIT_STRATEGY}}
</user_exit_strategy>
Implement a stop loss and profit target based on the user's input. If the user hasn't specified a method, choose an appropriate approach (e.g., indicator-based, static R:R ratio).
4. Parameter Configuration:
Set up the strategy parameters based on the user's input:
<user_parameters>
{{USER_PARAMETERS}}
</user_parameters>
Include configurations for:
- Key indicator parameters
- Instrument to trade (default to chart)
- Timeframe (default to chart)
- Trading window (e.g., 9:30 AM - 4:00 PM EST)
- Number of contracts to trade
- Any other relevant settings
5. PineScript Code Generation:
Generate the PineScript code for the strategy, incorporating all the elements above. Use clear variable names and add comments to explain each section of the code.
6. Output Format:
Provide your response in the following format:
<strategy_summary>
Briefly describe the key components of the strategy, including the trend determination method, entry confirmations, and exit strategy.
</strategy_summary>
<pinescript_code>
// Strategy Name: [Give your strategy a descriptive name]
// Author: AI Assistant
// Date: [Current date]
// Strategy Parameters
[Include all configurable parameters here]
// Trend Determination
[Include trend determination code]
// Entry Confirmations
[Include entry confirmation code]
// Exit Strategy
[Include exit strategy code]
// Strategy Logic
[Include main strategy logic, combining trend, entry, and exit components]
// Plotting (optional)
[Include any plotting code for visual representation on the chart]
</pinescript_code>
<usage_instructions>
Provide brief instructions on how to use the strategy in TradingView, including how to adjust parameters and any important considerations for live trading.
</usage_instructions>
Ensure that the generated PineScript code is complete, well-commented, and ready to be used in TradingView's strategy tester. The code should also be suitable for sending actual orders to a brokerage when properly configured.

11
ai-gen-strat/README.md Normal file
View File

@@ -0,0 +1,11 @@
There should be a folder per strategy with following elements:
```
│ ├── strategy-001/ # Each strategy in its own directory
│ │ ├── prompt.md # The detailed prompt used
│ │ ├── strategy.pine # Generated PineScript code
│ │ ├── results.json # Backtest results file (JSON?)
│ │ └── README.md # Strategy description and summary
│ └── strategy-002...
```

View File

@@ -0,0 +1,5 @@
Generate PineScript trading strategy that works in TradingView strategy tester and also can be used to send actual orders to brokerage. Strategies should be generated based on below framework:
- strategy should have a way to determine current market trend and only allow entries aligned with the trend - user can decide on providing indicator for determining trend or allow LLM to decide best one
- strategy should have between 1 and 3 confirmations for entry - those could be set of indicators provided by user or decided by LLM
- strategy should have capability to set stop loss and profit target - again this could be user provided indicator based or R:R static SL/PT ratio, user can also choose to let LLM to decide on best strategy for setting those
- strategy should allow configurability of key parameters for indicators used as well as deciding instrument to trade (default from chart that is open), timeframe (default to open chart), time window when trade could be placed (eg. from 9:30am - 4:00pm EST), number of contracts to be traded plus any other important settings you might consider useful

173
app_idea/app_gen_prompt.txt Normal file
View File

@@ -0,0 +1,173 @@
You are a technical Project Planning Assistant and Senior Dev with more than 20Y of experience building successfull SaaS applications, an AI designed to help users plan and document their app ideas. Your goal is to guide the user through a structured process to reverse engineer all the necessary documents for building their app. You will ask targeted questions (appended at the end of this prompt), generate documents iteratively, and adapt to the users needs. You will at all times make decisions for specific technologies based on the users answers.
Everything needs to be tailored to the users app idea. You create each document at the end of each session (e.g. answers for backend finished --> create backend.md and so on). You will find that there are few examples for each section, making it appear that the user wants to build a fitness app but that's not correct (unless he says so). But this prompt is the template for any app really. These documents will then perfectly outline every aspect of the application the users wants to build.
Whenever the user's answers are unclear or you need more info, ask follow up questions until you perfectly understand what the application is and does and what you need to add to the documents for each of the 13 phases from app overview to third-party-libraries.
Should the user not know the answer to one of the questions, please answer other (simpler) questions to reverse engineer what feature, functionality or idea he's trying to explain or is having in his mind. Then repeat his answer in your own words and explain if this is how he wants it to work for his app. Whenever the user can't answer a technical aspect (e.g. which state management solution to use) you jump in as an experienced Project Planning Assistant and Senior Dev and suggest a library or tool or solution he should use for his specific use case aka app.
In addition to the existing scope of work, you will generate a document titled "third-party-libraries.md" to list and describe the third-party libraries needed for the development process. This document will be created based on the user's answers and will be included in the final output folder structure.
Scope of Work:
Ask the user a series of questions to gather all necessary information about their app idea.
Use the answers to generate the following documents:
Product Requirements Document (PRD): Defines the apps purpose, features, and target audience.
Frontend Documentation: Describes the frontend architecture, UI components, and state management.
Backend Documentation: Describes the backend architecture, API design, and database schema.
Third-Party Libraries Documentation
Ensure all documents are written in Markdown format and stored in a structured folder.
Process:
Introduction: Explain the process and ask for the app idea.
Information Gathering: Ask targeted questions to understand the apps scope, features, and requirements so you can create proper documentation in .md format for the backend, frontend, database schema, state management, api communication / documentation, user flow and add third party library suggestions.
Document Generation: Create documents based on user input.
Review & Iteration: Review the outputs with the user and make adjustments.
Final Handoff: Compile all documents and plans into a structured format.
Instructions:
Always ask one question at a time to avoid overwhelming the user.
After gathering enough information for each section, generate the corresponding document and ask for feedback.
Include the "third-party-libraries.md" document in the final handoff, ensuring it complements the other documents without redundancy.
Use Markdown formatting for all documents.
Be patient and adapt to the users pace and level of expertise.
---
Questions to Ask (Appended to Initial Prompt)
1. App Idea & Scope
App Idea: Can you describe your app idea in detail? What problem does it solve, and who is it for?
Target Audience: Who are the primary users of your app? Describe their demographics, goals, and pain points.
Key Features: What are the main features of your app? List them in order of priority.
Platform: Will this app be for mobile (iOS/Android), web, or both?
Timeline: What is your desired timeline for the project (e.g., MVP in 3 months)?
2. Frontend
UI Framework: Do you have a preference for the frontend framework (e.g., React Native for mobile, React.js for web)?
UI Library: Would you like to use a UI library (e.g., NativeBase, Material-UI) for pre-built components?
Navigation: How should users navigate between screens (e.g., tabs, side menu)?
Styling: Do you have a preference for styling (e.g., Tailwind CSS, Styled Components)?
Forms: Will your app require forms (e.g., login, sign-up, data entry)? If yes, describe them.
3. Backend
Backend Framework: Do you have a preference for the backend framework (e.g., Node.js with Express.js)?
Database: What type of database do you want to use (e.g., PostgreSQL for relational data, Firebase Firestore for NoSQL)?
Authentication: How should users authenticate (e.g., email/password, social login)?
API Design: Should the backend use RESTful APIs or GraphQL?
Third-Party Integrations: Are there any third-party APIs you want to integrate (e.g., Fitbit, Stripe)?
4. State Management
Local State: Will you need local state management for component-specific data (e.g., form inputs)?
Global State: Do you want to use a global state management solution (e.g., Redux, Zustand)?
Server State: How should server-side data be managed (e.g., React Query, SWR)?
Persistence: Should any state be persisted across sessions (e.g., user preferences)?
5. Database
Schema Design: What kind of data will your app handle? Describe the main entities and relationships.
Indexing: Are there any fields that will be frequently queried and need indexing?
Migrations: Do you need a migration tool to manage schema changes (e.g., Knex.js, TypeORM)?
Backups: Should the database have automated backups?
6. API Communication
Endpoints: What endpoints will your app need (e.g., GET /workouts, POST /workouts)?
Error Handling: How should errors be handled (e.g., specific error messages, status codes)?
Rate Limiting: Should the API have rate limiting to prevent abuse?
WebSockets: Do you need real-time communication (e.g., chat, live updates)?
7. DevOps
Hosting: Where should the app be hosted (e.g., Vercel for frontend, Render/Heroku for backend)?
CI/CD: Should the app use continuous integration and deployment (e.g., GitHub Actions)?
Monitoring: Do you need monitoring tools (e.g., Sentry for error tracking)?
Scaling: Should the app be designed for horizontal scaling (e.g., load balancers)?
8. Testing
Unit Testing: Should the app have unit tests for individual components and functions?
Integration Testing: Should the app have integration tests for interactions between components and APIs?
End-to-End Testing: Should the app have end-to-end tests for entire user flows?
Manual Testing: Will you perform exploratory testing to catch edge cases?
9. Documentation
Code Comments: Should the code include inline comments to explain complex logic?
API Documentation: Should the API be documented using tools like Swagger/OpenAPI?
README: Should the project have a comprehensive README with setup instructions?
Architecture Diagrams: Should the apps structure and data flow be visualized with diagrams?
10. Security
Authentication: Should the app use secure authentication methods (e.g., JWT, OAuth)?
Authorization: Should the app have role-based access control (e.g., admin vs. regular user)?
Data Encryption: Should sensitive data (e.g., passwords, payment info) be encrypted?
Input Validation: Should user inputs be sanitized to prevent SQL injection and XSS attacks?
11. Performance Optimization
Frontend Performance: Should the frontend be optimized (e.g., lazy loading, code splitting)?
Backend Performance: Should the backend be optimized (e.g., database query optimization, caching)?
Network Performance: Should API payloads be minimized for faster loading?
12. User Flow
User Onboarding: How should users sign up and log in? Describe the steps (e.g., email/password, social login, multi-factor authentication).
Core User Journey: What is the primary user journey? Describe the steps from start to finish (e.g., sign up → set preferences → use core feature → view results).
Page Interactions: What interactions should users have on each page (e.g., buttons, forms, dropdowns, modals)?
Error Handling: How should errors be handled during user flows (e.g., invalid input, failed API calls, network issues)?
Edge Cases: Are there any edge cases to consider (e.g., offline mode, incomplete data, expired sessions)?
Alternative Flows: Are there alternative user flows (e.g., guest mode, skip onboarding)?
User Permissions: Are there different user roles or permissions (e.g., admin vs. regular user)?
Notifications: Should users receive notifications (e.g., email, push)? If yes, describe the triggers and content.
Core User Journey: What is the primary user journey? Describe the steps from start to finish (e.g., sign up → set goals → log workouts → view progress).
Page Interactions: What interactions should users have on each page (e.g., buttons, forms, navigation)?
Error Handling: How should errors be handled during user flows (e.g., invalid login, failed API calls)?
Edge Cases: Are there any edge cases to consider (e.g., offline mode, incomplete data)?
13. Third-Party Libraries
Library Identification:
Which third-party libraries do you plan to use for specific functionalities (e.g., payment processing, analytics, etc.)?
If unsure, describe the functionalities you need, and I will suggest appropriate libraries.
Requirements and Compatibility:
Are there any specific requirements for the libraries (e.g., open-source, commercial, specific licenses)?
How will these libraries integrate with the existing tech stack?
Security and Compliance:
Are there any security considerations or compliance requirements for the chosen libraries?
---
Document Descriptions
1. Product Requirements Document (PRD)
Purpose: Defines the apps purpose, features, and target audience.
Contents:
App overview (name, description, tagline).
Target audience and user personas.
Key features and prioritization.
Success metrics (e.g., user acquisition, engagement).
Assumptions and risks.
2. Frontend Documentation
Purpose: Describes the frontend architecture, UI components, and state management.
Contents:
UI framework and library.
Navigation structure.
Styling approach.
State management solution (local and global).
Key components and their functionality.
3. Backend Documentation
Purpose: Describes the backend architecture, API design, and database schema.
Contents:
Backend framework and language.
Database schema and relationships.
API endpoints and specifications.
Authentication and authorization mechanisms.
Third-party integrations.
4. User Flow Documentation
Purpose: Defines the user flows as a Mermaid diagram, detailing the steps from onboarding to core feature usage, including interactions, error handling, and edge cases.
Contents:
Onboarding Flow:
Steps for signing up and logging in.
Screens and interactions (e.g., email/password input, social login buttons, multi-factor authentication).
Core User Journey:
Step-by-step process for the primary user journey (e.g., sign up → set preferences → use core feature → view results).
Screens and interactions at each step (e.g., buttons, forms, dropdowns, modals).
Error Handling:
How errors are displayed and resolved (e.g., invalid input, failed API calls, network issues).
Edge Cases:
Handling of edge cases (e.g., offline mode, incomplete data, expired sessions).
Alternative Flows:
Guest mode, skip onboarding, or other alternative paths.
User Permissions:
Different user roles and their permissions (e.g., admin vs. regular user).
Notifications:
Triggers and content for notifications (e.g., email, push).
---
Final Output
At the end of the interaction, the LLM will generate a structured folder with all the documents and plans, ready to be handed off to AI coding agents. Heres an example folder structure:
project-name/
├── docs/
│ ├── prd.md
│ ├── frontend.md
│ ├── backend.md
│ ├── api.md
│ ├── database-schema.md
│ ├── user-flow.md
│ ├── devops.md
│ ├── state-management.md
│ ├── performance-optimization.md
│ ├── testing-plan.md
│ ├── code-documentation.md
│ ├── third-party-libraries.md
├── README.md

View File

@@ -0,0 +1,166 @@
# Backend Documentation
## Backend Framework and Language
**Framework**: Node.js with Express.js
**Language**: JavaScript/TypeScript
**Architecture**: RESTful API with layered architecture
Node.js with Express.js is chosen for:
- Excellent performance for real-time applications
- Rich ecosystem of packages for financial data processing
- Good compatibility with React frontend
- Efficient handling of asynchronous operations (important for LLM API calls)
- Seamless integration with Supabase
## API Design
### API Structure
The API follows RESTful principles with the following main resources:
1. **Auth**
- `/api/auth/login` - Social login with Google
- `/api/auth/logout` - User logout
- `/api/auth/refresh` - Token refresh
2. **Users**
- `/api/users/profile` - User profile management
- `/api/users/api-keys` - Secure API key management
- `/api/users/credits` - Credit management
3. **Indicators**
- `/api/indicators` - CRUD operations for indicators
- `/api/indicators/categories` - Get indicators by category
- `/api/indicators/trending` - Get trending indicators
4. **Strategies**
- `/api/strategies` - CRUD operations for strategies
- `/api/strategies/generate` - AI strategy generation
- `/api/strategies/export` - Generate PineScript code
- `/api/strategies/versions` - Strategy version management
5. **Community**
- `/api/community/strategies` - Shared strategies
- `/api/community/users` - User profiles
### API Versioning
The API will be versioned using URL path versioning:
- `/api/v1/...` - Initial version
### Authentication and Authorization
1. **Authentication**
- JWT (JSON Web Tokens) for session management
- Google OAuth for social login
- Refresh token rotation for security
2. **Authorization**
- Role-based access control (Free user vs. Paid user)
- Resource-based permissions
## LLM Integration
### Supported Providers
- OpenAI
- Anthropic
- OpenRouter.ai
### Integration Architecture
1. **Provider Adapter Pattern**
- Abstract interface for LLM providers
- Concrete implementations for each provider
- Fallback mechanism if primary provider fails
2. **Prompt Engineering**
- Structured prompts for strategy generation
- Context management for complex strategies
- Response validation and error handling
3. **Security Considerations**
- Encrypted storage of API keys
- No persistence of full strategy responses
- Rate limiting to prevent abuse
## Error Handling
1. **Standardized Error Responses**
```json
{
"status": "error",
"code": "ERROR_CODE",
"message": "User-friendly error message",
"details": { /* Additional error details */ }
}
```
2. **Error Categories**
- Authentication errors (401)
- Authorization errors (403)
- Resource not found (404)
- Validation errors (422)
- Server errors (500)
- LLM provider errors (502)
3. **Graceful Degradation**
- Fallback options when services are unavailable
- Detailed user instructions for recovery
## Third-Party Integrations
1. **Payment Processing**
- Stripe integration for subscription management
- PayPal as alternative payment method
- Coupon code functionality
2. **Email Service**
- Transactional emails for account verification
- Subscription notifications
- Strategy export delivery
## Caching Strategy
1. **Redis Cache**
- Cache common indicator configurations
- Store frequently accessed strategy templates
- Temporary storage for generated strategies
2. **Cache Invalidation**
- Time-based expiration for market data
- Event-based invalidation for user-specific data
## Security Measures
1. **Data Protection**
- Encryption of sensitive data at rest
- Secure transmission with TLS
- API key encryption with AES-256
2. **API Security**
- Rate limiting to prevent abuse
- CORS configuration for frontend access
- Input validation and sanitization
- Protection against common attacks (XSS, CSRF, injection)
3. **Monitoring and Logging**
- Structured logging for operations
- Error tracking and alerting
- Audit trail for sensitive operations
## Performance Optimization
1. **Query Optimization**
- Efficient database queries
- Pagination for large result sets
- Eager loading of related data
2. **Asynchronous Processing**
- Background jobs for resource-intensive tasks
- Queuing system for LLM requests
3. **Scaling Considerations**
- Horizontal scaling readiness
- Stateless API design
- Connection pooling for database access

263
app_idea/database-schema.md Normal file
View File

@@ -0,0 +1,263 @@
# Database Schema
## Overview
The application uses **Supabase** as the database provider, which is built on PostgreSQL. This provides:
- Relational database capabilities
- Built-in authentication
- Row-level security
- Real-time capabilities
- Storage options for larger objects
## Tables and Relationships
### Users
Stores user account information and preferences.
```sql
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
email TEXT UNIQUE NOT NULL,
full_name TEXT,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
credits INTEGER DEFAULT 5,
is_premium BOOLEAN DEFAULT FALSE,
preferences JSONB DEFAULT '{}'::JSONB,
last_login TIMESTAMP WITH TIME ZONE
);
```
### ApiKeys
Stores encrypted API keys for LLM services.
```sql
CREATE TABLE api_keys (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
provider TEXT NOT NULL,
key_encrypted TEXT NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
last_used TIMESTAMP WITH TIME ZONE,
UNIQUE(user_id, provider)
);
```
### Indicators
Stores the library of available technical indicators.
```sql
CREATE TABLE indicators (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
name TEXT NOT NULL,
description TEXT,
category TEXT NOT NULL,
type TEXT NOT NULL, -- trend, entry, exit, stop_loss
parameters JSONB NOT NULL DEFAULT '{}'::JSONB,
defaults JSONB NOT NULL DEFAULT '{}'::JSONB,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
created_by UUID REFERENCES users(id),
is_custom BOOLEAN DEFAULT FALSE,
is_public BOOLEAN DEFAULT TRUE,
accuracy_rating DECIMAL(3,2)
);
```
### CustomIndicators
Stores user-created custom indicators (premium feature).
```sql
CREATE TABLE custom_indicators (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
description TEXT,
category TEXT NOT NULL,
type TEXT NOT NULL, -- trend, entry, exit, stop_loss
parameters JSONB NOT NULL DEFAULT '{}'::JSONB,
pine_script TEXT NOT NULL,
is_public BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
```
### Strategies
Stores created trading strategies.
```sql
CREATE TABLE strategies (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
description TEXT,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
is_ai_generated BOOLEAN DEFAULT FALSE,
is_public BOOLEAN DEFAULT FALSE,
market_type TEXT, -- futures, stocks, crypto, forex
timeframe TEXT, -- 1m, 5m, 15m, 1h, 4h, 1d
config JSONB NOT NULL
);
```
### StrategyVersions
Stores versions of strategies for version control.
```sql
CREATE TABLE strategy_versions (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
strategy_id UUID REFERENCES strategies(id) ON DELETE CASCADE,
version_number INTEGER NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
config JSONB NOT NULL,
notes TEXT,
UNIQUE(strategy_id, version_number)
);
```
### StrategyComponents
Links strategies to their component indicators with configuration.
```sql
CREATE TABLE strategy_components (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
strategy_id UUID REFERENCES strategies(id) ON DELETE CASCADE,
indicator_id UUID, -- Can reference either indicators or custom_indicators
is_custom BOOLEAN DEFAULT FALSE,
component_type TEXT NOT NULL, -- trend, entry, exit, stop_loss
parameters JSONB NOT NULL DEFAULT '{}'::JSONB,
position INTEGER NOT NULL, -- Order within the component type
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
```
### Subscriptions
Stores user subscription information.
```sql
CREATE TABLE subscriptions (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
status TEXT NOT NULL,
provider TEXT NOT NULL, -- stripe, paypal
provider_subscription_id TEXT,
plan_type TEXT NOT NULL,
current_period_start TIMESTAMP WITH TIME ZONE,
current_period_end TIMESTAMP WITH TIME ZONE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
```
### Coupons
Stores discount coupon codes.
```sql
CREATE TABLE coupons (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
code TEXT UNIQUE NOT NULL,
discount_percent INTEGER NOT NULL,
description TEXT,
is_active BOOLEAN DEFAULT TRUE,
max_uses INTEGER,
current_uses INTEGER DEFAULT 0,
expiration_date TIMESTAMP WITH TIME ZONE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
```
### UserCoupons
Tracks coupon usage by users.
```sql
CREATE TABLE user_coupons (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
coupon_id UUID REFERENCES coupons(id) ON DELETE CASCADE,
used_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
UNIQUE(user_id, coupon_id)
);
```
## Indexes
```sql
-- For faster user lookups by email
CREATE INDEX idx_users_email ON users(email);
-- For filtering indicators by type and category
CREATE INDEX idx_indicators_type_category ON indicators(type, category);
-- For retrieving user strategies
CREATE INDEX idx_strategies_user_id ON strategies(user_id);
-- For retrieving strategy versions
CREATE INDEX idx_strategy_versions_strategy_id ON strategy_versions(strategy_id);
-- For retrieving strategy components
CREATE INDEX idx_strategy_components_strategy_id ON strategy_components(strategy_id);
-- For coupon code lookups
CREATE INDEX idx_coupons_code ON coupons(code);
```
## Row Level Security (RLS)
Supabase provides row-level security to ensure users can only access their own data:
```sql
-- Users table
ALTER TABLE users ENABLE ROW LEVEL SECURITY;
CREATE POLICY user_self_access ON users
FOR ALL USING (auth.uid() = id);
-- API Keys table
ALTER TABLE api_keys ENABLE ROW LEVEL SECURITY;
CREATE POLICY api_keys_self_access ON api_keys
FOR ALL USING (auth.uid() = user_id);
-- Strategies table
ALTER TABLE strategies ENABLE ROW LEVEL SECURITY;
CREATE POLICY strategies_self_access ON strategies
FOR ALL USING (auth.uid() = user_id OR is_public = TRUE);
-- Custom indicators table
ALTER TABLE custom_indicators ENABLE ROW LEVEL SECURITY;
CREATE POLICY custom_indicators_self_access ON custom_indicators
FOR ALL USING (auth.uid() = user_id OR is_public = TRUE);
```
## Data Encryption
Sensitive data like API keys will be encrypted using Supabase's pgcrypto extension:
```sql
-- Setup pgcrypto extension if not already enabled
CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- Function to encrypt API keys
CREATE OR REPLACE FUNCTION encrypt_api_key(key_text TEXT, secret TEXT)
RETURNS TEXT AS $$
BEGIN
RETURN encode(encrypt(key_text::bytea, secret::bytea, 'aes-cbc/pad:pkcs')::bytea, 'base64');
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- Function to decrypt API keys
CREATE OR REPLACE FUNCTION decrypt_api_key(encrypted_key TEXT, secret TEXT)
RETURNS TEXT AS $$
BEGIN
RETURN convert_from(decrypt(decode(encrypted_key, 'base64')::bytea, secret::bytea, 'aes-cbc/pad:pkcs')::bytea, 'UTF8');
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
```
## Migrations
Migrations will be managed using Supabase migrations, which provide:
- Version control for database schema
- Rollback capability
- Environment-specific configurations

View File

@@ -0,0 +1,148 @@
# Frontend Documentation
## UI Framework and Library
**Framework**: React
**Styling**: Tailwind CSS
**Additional UI Libraries**: Headless UI (for accessible components)
## Design Philosophy
The application follows a minimalistic, modern design inspired by Apple's design language with:
- Clean, uncluttered interfaces
- Ample white space
- Subtle animations and transitions
- Focus on content and functionality
- Support for both light and dark mode
## Navigation Structure
The application uses a sidebar navigation layout with the following primary sections:
1. **Dashboard** - Overview of user activity and saved strategies
2. **Strategy Builder** - Main interface for creating strategies
3. **My Strategies** - Library of saved and generated strategies
4. **Community** - Social features and shared strategies
5. **Settings** - Account management and preferences
Mobile view will use a collapsible hamburger menu to ensure responsiveness.
## State Management
**Solution**: Zustand
Zustand is selected for state management due to its:
- Simplified API compared to Redux
- Strong performance for complex state
- Minimal boilerplate code
- Good compatibility with React's concurrent features
- Ability to handle complex nested state required for strategy configurations
## Component Structure
### Core Components
1. **StrategyBuilder**
- Main component for strategy creation
- Contains sub-sections for each framework part
- Houses the visual indicator selection interface
2. **IndicatorSelector**
- Allows selection from pre-built indicators
- Provides customization controls for indicator parameters
- Displays visual representation of indicator behavior
3. **StrategyViewer**
- Displays the complete strategy with all selected components
- Provides export options
- Shows educational content about strategy components
4. **CodeExporter**
- Generates PineScript code
- Toggles between minimal and commented code
- Provides copy functionality
5. **AIStrategyGenerator**
- Interface for API key management
- Controls for AI-based strategy generation
- Displays generated strategies with explanations
6. **StrategyVersionControl**
- Manages different versions of strategies
- Provides comparison tools
- Allows reverting to previous versions
### Shared Components
1. **Header**
- App logo and navigation
- User profile and account menu
- Theme toggle (light/dark mode)
2. **Sidebar**
- Main navigation menu
- Collapsible on mobile devices
3. **Modal**
- Reusable modal component for alerts, confirmations, etc.
4. **Toast**
- Notification system for success/error messages
5. **Button**
- Consistent button styles across the application
- Various states (primary, secondary, disabled)
6. **Card**
- Container for strategy items and content blocks
## Forms and Inputs
1. **API Key Management Form**
- Secure input for LLM API keys
- Validation for proper key format
- Test connection functionality
2. **Strategy Parameters Form**
- Number inputs with min/max validation
- Toggle switches for boolean options
- Dropdown selects for pre-defined options
3. **Filter and Search Forms**
- Used in strategy library and community sections
- Quick filtering by strategy type, performance, etc.
## Responsive Design
The application will follow a mobile-first approach with specific breakpoints for:
- Mobile (< 640px)
- Tablet (640px - 1024px)
- Desktop (> 1024px)
Tailwind's responsive classes will be utilized for consistent responsive behavior.
## Theme Management
The application will support both light and dark modes:
- System preference detection by default
- User toggle option
- Persistent preference storage
- Smooth transition between themes
## Performance Considerations
1. **Code Splitting**
- Route-based code splitting
- Dynamic imports for heavy components
2. **Lazy Loading**
- Defer loading of non-critical components
- Implement for community features and advanced settings
3. **Memoization**
- Use React.memo for complex component renders
- Implement useMemo for expensive calculations
4. **Asset Optimization**
- Optimize images and icons
- Use SVGs where possible for crisp rendering at all sizes

View File

@@ -0,0 +1,111 @@
# Product Requirements Document (PRD)
## App Overview
**Name**: TradingScriptPro
**Description**: A web-based SaaS application that allows non-programmer retail traders to generate profitable trading strategies in PineScript for the TradingView platform without coding knowledge.
**Tagline**: "Professional Trading Strategies Without The Code"
## Target Audience
**Primary Users**: Retail traders without programming skills who want to create custom trading strategies.
**User Persona**:
- **Name**: Alex
- **Age**: 35-45
- **Occupation**: Part-time trader, full-time professional
- **Technical Skills**: Understands trading concepts but has minimal programming knowledge
- **Goals**:
- Create profitable trading strategies for futures markets
- Test different technical indicators without having to code
- Share successful strategies with the trading community
- **Pain Points**:
- Cannot code in PineScript
- Finds pre-made strategies too generic
- Wants to customize strategies based on personal trading style
- Struggles to implement complex indicator combinations
## Key Features
1. **Strategy Framework Builder**
- Component-based strategy creation using a four-part framework:
- Trend finder indicators
- Entry finder indicators
- Exit finder indicators
- Stop loss management
- Visual interface for selecting and configuring indicators
- Parameter customization for each indicator
2. **AI-Powered Strategy Generation**
- Integration with multiple LLM providers (OpenAI, Anthropic, OpenRouter.ai)
- User-provided API keys
- Educational content explaining generated strategies
3. **Strategy Management**
- Save and organize created strategies
- Version control for strategy iterations
- Export to PineScript with optional detailed comments
4. **Social Features**
- Share generated strategies with community
- Export PineScript code
5. **User Account Management**
- Social login via Gmail
- Freemium model with 5 free strategy credits
- Paid subscription for unlimited strategies and advanced features
## Feature Prioritization
| Priority | Feature | Rationale |
|----------|---------|-----------|
| 1 | Strategy Framework Builder | Core functionality of the application |
| 2 | AI-Powered Strategy Generation | Primary value proposition |
| 3 | Strategy Management | Essential for user workflow |
| 4 | User Account Management | Required for monetization |
| 5 | Social Features | Enhances user engagement |
| 6 | Advanced Backtesting (Future) | Valuable but complex to implement initially |
## Success Metrics
1. **User Acquisition**
- Number of registered users
- Conversion rate from free to paid accounts
- User retention rate
2. **Engagement**
- Number of strategies created per user
- Time spent in the application
- Frequency of visits
3. **Performance**
- Strategy generation success rate
- API response times
- User satisfaction rating
## Assumptions
1. Users have basic knowledge of trading concepts and technical indicators
2. Users have access to TradingView accounts for actual trading
3. The application will initially focus on futures markets but can expand to other instruments
4. Users are willing to provide their own LLM API keys
5. Generated strategies will be useful for real trading scenarios
## Risks
1. **Technical Risks**
- Integration complexity with multiple LLM providers
- Ensuring generated PineScript code is valid and error-free
- Performance issues when handling complex strategy generation
2. **Business Risks**
- User resistance to providing personal API keys
- Competition from existing strategy builders
- Accuracy and profitability of generated strategies
- Cost of LLM API usage affecting user adoption
3. **Mitigation Strategies**
- Robust testing of PineScript output
- Clear educational content about strategy performance expectations
- Transparent communication about API key security measures
- Focus on unique value proposition (no-code, AI-powered, educational)

0
app_idea/readme.md Normal file
View File

View File

@@ -0,0 +1,48 @@
# State Management Documentation
## State Management Solution
The application uses **Zustand** as the primary state management solution for the following reasons:
- Simplified API with minimal boilerplate
- Strong performance characteristics for complex state
- Good compatibility with React's concurrent features
- Excellent TypeScript support
- Middleware support for additional functionality
## State Structure
The state is divided into several specialized stores for different concerns:
### 1. User Store
Manages authentication state and user profile information.
```javascript
// userStore.js
import create from 'zustand';
import { persist } from 'zustand/middleware';
const useUserStore = create(
persist(
(set, get) => ({
user: null,
isAuthenticated: false,
credits: 0,
isPremium: false,
// Actions
setUser: (userData) => set({
user: userData,
isAuthenticated: true,
credits: userData.credits,
isPremium: userData.isPremium
}),
logout: () => set({
user: null,
isAuthenticated: false,
credits: 0,
isPremium: false
}),

303
app_idea/user-flow.md Normal file
View File

@@ -0,0 +1,303 @@
# User Flow Documentation
## Onboarding Flow
```mermaid
stateDiagram-v2
[*] --> LandingPage: User visits site
LandingPage --> Registration: Click "Sign Up"
Registration --> GoogleAuth: Click "Sign in with Google"
GoogleAuth --> WelcomePage: Successfully authenticated
GoogleAuth --> Registration: Authentication failed
WelcomePage --> SetupOptions: Choose setup path
SetupOptions --> GuidedTour: Choose "Show me around"
SetupOptions --> APIKeySetup: Choose "Set up API keys"
SetupOptions --> SkipSetup: Choose "Skip for now"
GuidedTour --> APIKeySetup: Tour complete
APIKeySetup --> Dashboard: API keys set
SkipSetup --> Dashboard: Skip setup
Dashboard --> [*]
```
### Steps Breakdown:
1. **Landing Page**
- Introduction to TradingScriptPro
- Value proposition
- Call-to-action for sign-up
- Login option for existing users
2. **Registration**
- Google social login option
- Terms of service acceptance
- Privacy policy acknowledgment
3. **Google Authentication**
- Secure OAuth flow
- Email permission request
4. **Welcome Page**
- Welcome message for new users
- Brief explanation of the 5 free credits
- Setup options presentation
5. **API Key Setup (Optional)**
- Educational content about LLM API keys
- Secure input fields for API keys
- Validation and test connection
6. **Guided Tour (Optional)**
- Interactive walkthrough of key features
- Example strategy creation
- Quick tips for best results
## Core User Journey: Strategy Creation
```mermaid
stateDiagram-v2
[*] --> Dashboard: User logged in
Dashboard --> StrategyBuilder: Click "Create New Strategy"
Dashboard --> AIGenerator: Click "AI Generate Strategy"
StrategyBuilder --> TrendSetup: Step 1
TrendSetup --> EntrySetup: Continue
EntrySetup --> ExitSetup: Continue
ExitSetup --> StopLossSetup: Continue
StopLossSetup --> StrategyReview: All components configured
AIGenerator --> AIPromptInput: Describe strategy goals
AIPromptInput --> AIProcessing: Submit request
AIProcessing --> AIResults: Strategy generated
AIProcessing --> AIError: Generation failed
AIError --> AIPromptInput: Retry with modifications
AIResults --> StrategyReview: Review generated strategy
StrategyReview --> StrategyTesting: Preview strategy
StrategyReview --> StrategyModification: Edit components
StrategyModification --> StrategyReview: Changes complete
StrategyTesting --> StrategySaving: Save strategy
StrategySaving --> ExportOptions: Strategy saved
ExportOptions --> PineScriptMinimal: Export minimal code
ExportOptions --> PineScriptDetailed: Export detailed code
ExportOptions --> ShareCommunity: Share with community
PineScriptMinimal --> Dashboard: Return to dashboard
PineScriptDetailed --> Dashboard: Return to dashboard
ShareCommunity --> Dashboard: Return to dashboard
```
### Steps Breakdown:
1. **Strategy Builder Entry**
- Two paths: Manual builder or AI generator
- Clear explanation of each approach
- Credit usage information for AI generation
2. **Manual Strategy Building**
- **Trend Setup**:
- Select from trend indicators
- Configure parameters
- Visual feedback on selection
- **Entry Setup**:
- Select from entry indicators
- Configure parameters
- Rules for entry conditions
- **Exit Setup**:
- Select from exit indicators
- Configure parameters
- Rules for exit conditions
- **Stop Loss Setup**:
- Configure stop loss approach
- Set parameters (fixed, trailing, indicator-based)
- Risk management options
3. **AI Strategy Generation**
- **Prompt Input**:
- Market selection
- Trading style preferences
- Goals and risk tolerance
- **Processing**:
- Loading indicator
- Status updates
- Credit usage notification
- **Results**:
- Complete strategy presentation
- Educational explanation of components
- Options to modify or accept
4. **Strategy Review**
- Complete strategy overview
- Component interaction explanation
- Performance expectations
- Modification options
5. **Export Options**
- PineScript code generation:
- Minimal code option
- Detailed commented code option
- Copy to clipboard functionality
- Community sharing option
- Version saving
## Account Management Flow
```mermaid
stateDiagram-v2
[*] --> Dashboard
Dashboard --> AccountSettings: Click user avatar
AccountSettings --> SubscriptionManagement: "Subscription" tab
AccountSettings --> APIKeyManagement: "API Keys" tab
AccountSettings --> ProfileSettings: "Profile" tab
SubscriptionManagement --> ViewCurrentPlan: View subscription details
SubscriptionManagement --> UpgradePlan: Upgrade to premium
SubscriptionManagement --> EnterCoupon: Apply coupon code
UpgradePlan --> PaymentSelection: Choose payment method
PaymentSelection --> StripeCheckout: Stripe selected
PaymentSelection --> PayPalCheckout: PayPal selected
StripeCheckout --> SubscriptionConfirmation: Payment successful
PayPalCheckout --> SubscriptionConfirmation: Payment successful
SubscriptionConfirmation --> Dashboard: Return to dashboard
APIKeyManagement --> AddNewKey: Add new provider key
APIKeyManagement --> RemoveKey: Remove existing key
APIKeyManagement --> UpdateKey: Update existing key
AddNewKey --> APIKeyValidation: Test connection
UpdateKey --> APIKeyValidation: Test connection
APIKeyValidation --> APIKeySuccess: Validation passed
APIKeyValidation --> APIKeyError: Validation failed
APIKeySuccess --> APIKeyManagement: Return to key management
APIKeyError --> AddNewKey: Try again
RemoveKey --> APIKeyManagement: Key removed
ProfileSettings --> UpdateProfile: Edit profile information
UpdateProfile --> ProfileSettings: Save changes
```
### Steps Breakdown:
1. **Account Settings Entry**
- User avatar menu in header
- Settings categories
- Account status overview
2. **Subscription Management**
- Current plan display
- Usage statistics (credits remaining)
- Upgrade options with benefits
- Coupon code redemption
3. **Payment Process**
- Payment method selection
- Secure checkout integration
- Order summary
- Confirmation and receipt
4. **API Key Management**
- Current keys display (partially masked)
- Add/update/remove functionality
- Connection testing
- Security information
5. **Profile Settings**
- Basic profile information
- Email preferences
- Account deletion option
## Error Handling Flows
```mermaid
stateDiagram-v2
[*] --> UserAction: User performs action
UserAction --> Success: Action completes successfully
UserAction --> Error: Action fails
Error --> ValidationError: Input validation fails
Error --> APIError: API call fails
Error --> CreditsExhausted: User out of credits
Error --> AuthError: Authentication issue
ValidationError --> InlineErrorDisplay: Show error next to input
ValidationError --> UserAction: User corrects input
APIError --> ConnectionErrorModal: Show API connection error
APIError --> APITroubleshooting: Show troubleshooting steps
CreditsExhausted --> UpgradePrompt: Show upgrade offer
CreditsExhausted --> CouponPrompt: Offer coupon option
AuthError --> ReauthPrompt: Prompt for reauthentication
InlineErrorDisplay --> UserAction: User corrects error
ConnectionErrorModal --> APIKeyManagement: Go to API key settings
APITroubleshooting --> UserAction: User retries after troubleshooting
UpgradePrompt --> SubscriptionManagement: User opts to upgrade
CouponPrompt --> EnterCoupon: User enters coupon
ReauthPrompt --> GoogleAuth: User reauthenticates
```
### Error Scenarios and Recovery:
1. **Validation Errors**
- Field-specific error messages
- Immediate feedback on input
- Clear recovery instructions
2. **API Connection Errors**
- Clear explanation of the issue
- Troubleshooting steps:
- Check API key validity
- Verify internet connection
- Check LLM provider service status
- Retry options with backoff
3. **Credits Exhausted**
- Friendly notification
- Options to:
- Upgrade to premium
- Enter coupon code
- Review existing strategies
4. **Authentication Errors**
- Session expiration handling
- Secure re-authentication
- Session persistence options
## Alternative Flows
1. **Guest Mode (Limited Features)**
- Strategy browsing only
- Community section access
- Call-to-action for registration
2. **Free vs. Premium User Paths**
- Clear indicators of premium features
- Upgrade prompts at strategic points
- Value demonstration before paywall

11
desc-strat/README.md Normal file
View File

@@ -0,0 +1,11 @@
There should be a folder per strategy with following elements:
```
│ ├── strategy-001/ # Each strategy in its own directory
│ │ ├── prompt.md # The detailed prompt used
│ │ ├── strategy.pine # Generated PineScript code
│ │ ├── results.json # Backtest results file (JSON?)
│ │ └── README.md # Strategy description and summary
│ └── strategy-002...
```

View File

View File

0
docs/backtesting.md Normal file
View File

View File

0
docs/methodology.md Normal file
View File

0
tools/backtest.py Normal file
View File

0
tools/generate-code.py Normal file
View File

View File