### OpenAlgo v2.0 Quick Start Setup and Run Source: https://github.com/marketcalls/openalgo/blob/main/docs/test/MANUAL_TESTING_GUIDE.md This snippet provides the essential commands to clone the OpenAlgo repository, set up the environment, install dependencies, build the frontend, and run the application. It also includes the URL to access the running application. ```bash # 1. Setup git clone https://github.com/marketcalls/openalgo.git cd openalgo cp .sample.env .env # Edit .env with your broker credentials # 2. Install & Build pip install uv uv sync cd frontend && npm install && npm run build && cd .. # 3. Run uv run app.py # 4. Access open http://127.0.0.1:5000 ``` -------------------------------- ### Quick Start Installation with UV Source: https://github.com/marketcalls/openalgo/blob/main/README.md Clone the repository, install the uv package manager, configure environment variables, and run the application using uv. ```bash # Clone the repository git clone https://github.com/marketcalls/openalgo.git cd openalgo # Install UV package manager pip install uv # Configure environment cp .sample.env .env # Edit .env with your broker API credentials as per documentation # Run the application using UV uv run app.py ``` -------------------------------- ### Quick Start for Windows Source: https://github.com/marketcalls/openalgo/blob/main/install/Docker-install-readme.md Use this command to download and run the Docker setup script on Windows PowerShell or Command Prompt. ```powershell curl.exe -O https://raw.githubusercontent.com/marketcalls/openalgo/main/install/docker-run.bat docker-run.bat ``` -------------------------------- ### Setup Frontend Dependencies Source: https://github.com/marketcalls/openalgo/blob/main/docs/design/35-development-testing/README.md Navigate to the frontend directory and install project dependencies using npm. ```bash cd frontend npm install ``` -------------------------------- ### Quick Start for macOS/Linux Source: https://github.com/marketcalls/openalgo/blob/main/install/Docker-install-readme.md Use these commands to download, make executable, and run the Docker setup script on macOS or Linux terminals. ```bash curl -O https://raw.githubusercontent.com/marketcalls/openalgo/main/install/docker-run.sh chmod +x docker-run.sh ./docker-run.sh ``` -------------------------------- ### Setup Python Virtual Environment and Install Dependencies Source: https://github.com/marketcalls/openalgo/blob/main/docs/design/12-ubuntu-server/README.md Installs the 'uv' package manager, creates a virtual environment, and installs project dependencies including Gunicorn and eventlet for production. ```bash # Install uv package manager pip install uv # Create virtual environment and install dependencies uv venv .venv source .venv/bin/activate uv sync # Install production dependencies uv pip install gunicorn eventlet==0.35.2 ``` -------------------------------- ### Development Environment Configuration Source: https://github.com/marketcalls/openalgo/blob/main/docs/design/28-environment-config/README.md Example environment variables for a local development setup. ```bash FLASK_DEBUG = 'True' FLASK_ENV = 'development' LOG_LEVEL = 'DEBUG' HOST_SERVER = 'http://127.0.0.1:5000' FLASK_HOST_IP = '127.0.0.1' CSP_UPGRADE_INSECURE_REQUESTS = 'FALSE' ``` -------------------------------- ### React Frontend Development Setup Source: https://github.com/marketcalls/openalgo/blob/main/CLAUDE.md Provides commands for setting up and running the React frontend, including dependency installation, development server, production build, testing, and linting. ```bash cd frontend # Install dependencies npm install # Development server (hot reload) npm run dev # Production build npm run build # Run tests npm test # Run end-to-end tests npm run e2e # Linting and formatting npm run lint npm run format ``` -------------------------------- ### Install and Run Pre-commit Hooks Source: https://github.com/marketcalls/openalgo/blob/main/docs/prd/ci-cd-local-development.md One-time setup for pre-commit hooks and running all checks before committing. Also includes commands for running backend and frontend tests. ```bash # One-time setup: Install pre-commit hooks pip install pre-commit pre-commit install # Run all checks before committing pre-commit run --all-files # Run backend tests uv run pytest test/ -v # Run frontend tests cd frontend && npm test ``` -------------------------------- ### One-Line Docker Installation Script Source: https://github.com/marketcalls/openalgo/blob/main/install/Docker-install-readme.md Automates the installation of OpenAlgo with Docker, including Nginx, Certbot, and SSL setup. Download, make executable, and run. ```bash wget https://raw.githubusercontent.com/marketcalls/openalgo/refs/heads/main/install/install-docker.sh && chmod +x install-docker.sh && ./install-docker.sh ``` -------------------------------- ### Creating New Installation with Docker Source: https://github.com/marketcalls/openalgo/blob/main/docs/docker/DOCKER_SCRIPTS_ANALYSIS.md This command initiates a new installation or starts the OpenAlgo service using Docker Compose. It's part of the testing checklist to ensure the environment is set up correctly after script updates. ```bash ./docker-run.sh start ``` -------------------------------- ### OpenAlgo Start Script Overview Source: https://github.com/marketcalls/openalgo/blob/main/docs/design/11-docker/README.md This bash script serves as the main entrypoint for the OpenAlgo application. It automates environment detection, directory setup, database migrations, starts a WebSocket proxy, and launches the Gunicorn server with optimized settings. It also implements graceful shutdown handling. ```bash #!/bin/bash # start.sh (simplified overview - actual script is 246 lines) echo "[OpenAlgo] Starting up..." # ============================================ # RAILWAY/CLOUD ENVIRONMENT DETECTION # ============================================ # If HOST_SERVER is set and no .env exists, auto-generate .env # with 40+ configuration variables including: # - Broker configuration # - Database URLs # - CORS, CSP, CSRF settings # - Rate limiting # - WebSocket/ZeroMQ configuration # ============================================ # DIRECTORY SETUP # ============================================ for dir in db log log/strategies strategies strategies/scripts keys; do mkdir -p "$dir" 2>/dev/null || true done # ============================================ # DATABASE MIGRATIONS # ============================================ if [ -f "/app/upgrade/migrate_all.py" ]; then /app/.venv/bin/python /app/upgrade/migrate_all.py fi # ============================================ # WEBSOCKET PROXY SERVER # ============================================ /app/.venv/bin/python -m websocket_proxy.server & WEBSOCKET_PID=$! # ============================================ # SIGNAL HANDLING # ============================================ cleanup() { echo "[OpenAlgo] Shutting down..." kill $WEBSOCKET_PID 2>/dev/null exit 0 } trap cleanup SIGTERM SIGINT # ============================================ # GUNICORN STARTUP # ============================================ APP_PORT="${PORT:-5000}" # Railway uses PORT env var mkdir -p /tmp/gunicorn_workers exec /app/.venv/bin/gunicorn \ --worker-class eventlet \ --workers 1 \ --bind 0.0.0.0:${APP_PORT} \ --timeout 300 \ --graceful-timeout 30 \ --worker-tmp-dir /tmp/gunicorn_workers \ --log-level warning \ app:app ``` -------------------------------- ### Install Pre-commit Tool and Hooks Source: https://github.com/marketcalls/openalgo/blob/main/docs/prd/ci-cd-local-development.md Installs the pre-commit tool and sets up the repository's hooks. Includes a command to verify the installation. ```bash # Install pre-commit tool pip install pre-commit # Install hooks for this repository pre-commit install # Verify installation pre-commit --version ``` -------------------------------- ### Check Initial Setup Requirement Source: https://github.com/marketcalls/openalgo/blob/main/docs/design/03-login-broker-flow/README.md Checks if the system requires initial setup by determining if any users already exist. Redirects to setup if no users are found. ```python # blueprints/auth.py @auth_bp.route('/check-setup', methods=['GET']) def check_setup_required(): """Check if initial setup is required (no users exist).""" needs_setup = find_user_by_username() is None return jsonify({ 'status': 'success', 'needs_setup': needs_setup }) ``` -------------------------------- ### Python SDK Example for LTP Subscription Source: https://github.com/marketcalls/openalgo/blob/main/docs/api/websocket-streaming/ltp.md This Python code demonstrates how to initialize the client, connect to the WebSocket, subscribe to LTP updates for multiple instruments, and handle incoming data. Ensure you have the 'openalgo' library installed. ```python from openalgo import api import time # Initialize client with WebSocket client = api( api_key="your_api_key", host="http://127.0.0.1:5000", ws_url="ws://127.0.0.1:8765" ) # Instruments to subscribe instruments = [ {"exchange": "NSE", "symbol": "RELIANCE"}, {"exchange": "NSE", "symbol": "INFY"} ] # Callback for LTP updates def on_ltp(data): print(f"LTP Update: {data['symbol']} = {data['ltp']}") # Connect and subscribe client.connect() client.subscribe_ltp(instruments, on_data_received=on_ltp) # Keep running try: time.sleep(60) # Run for 60 seconds finally: client.unsubscribe_ltp(instruments) client.disconnect() ``` -------------------------------- ### Creating New Installation with Docker (Windows) Source: https://github.com/marketcalls/openalgo/blob/main/docs/docker/DOCKER_SCRIPTS_ANALYSIS.md This command initiates a new installation or starts the OpenAlgo service using Docker Compose on a Windows environment. It's part of the testing checklist to ensure the environment is set up correctly after script updates. ```bat docker-run.bat start ``` -------------------------------- ### Setup SSL with Let's Encrypt Source: https://github.com/marketcalls/openalgo/blob/main/docs/design/12-ubuntu-server/README.md Uses Certbot to obtain and install SSL certificates for the specified domain, enabling HTTPS for the OpenAlgo application. ```bash sudo certbot --nginx -d your-domain.com ``` -------------------------------- ### Install Dependencies, Run Dev Server, Tests, and Build Source: https://github.com/marketcalls/openalgo/blob/main/frontend/docs/frontend/README.md Standard npm commands for managing the OpenAlgo frontend project. Use 'npm install' to set up dependencies, 'npm run dev' to start the development server, 'npm run test' to execute tests, and 'npm run build' for production deployment. ```bash npm install npm run dev npm run test npm run build ``` -------------------------------- ### View Installation Log File Source: https://github.com/marketcalls/openalgo/blob/main/docs/installation-guidelines/getting-started/ubuntu-server-installation.md Lists the contents of the installation logs directory and displays the content of a specific installation log file. ```bash ls -l ~/openalgo-install/logs/ cat ~/openalgo-install/logs/install_YYYYMMDD_HHMMSS.log ``` -------------------------------- ### Install mibian Library Source: https://github.com/marketcalls/openalgo/blob/main/test/README_OPTION_GREEKS_TESTS.md Install the mibian library, which is required for Option Greeks calculations. Use pip or uv for installation. ```bash pip install mibian ``` ```bash uv pip install mibian ``` -------------------------------- ### Get Order Logs Response Example Source: https://github.com/marketcalls/openalgo/blob/main/docs/design/22-log-section/README.md Example JSON response for the GET /logs/api/orders endpoint, showing log data and pagination details. ```json { "status": "success", "data": [ { "id": 1, "api_type": "placeorder", "request_data": "{\"symbol\": \"SBIN\", ...}", "response_data": "{\"status\": \"success\", ...}", "created_at": "2024-01-15 09:30:15" } ], "pagination": { "page": 1, "per_page": 50, "total": 1250, "pages": 25 } } ``` -------------------------------- ### Download and Prepare Installation Script Source: https://github.com/marketcalls/openalgo/blob/main/docs/installation-guidelines/getting-started/ubuntu-server-installation.md Creates a directory, navigates into it, downloads the installation script, and makes it executable. ```bash mkdir -p ~/openalgo-install cd ~/openalgo-install wget https://raw.githubusercontent.com/marketcalls/openalgo/main/install/install.sh chmod +x install.sh ``` -------------------------------- ### Verify Chromium Installation Source: https://github.com/marketcalls/openalgo/blob/main/docs/telegram-chart-rendering.md Check if the Chromium browser binary is installed and accessible within the container or on the host system. If missing, refer to the installation guide. ```bash # Docker docker exec openalgo-web /usr/bin/chromium --version # Bare metal chromium --version || chromium-browser --version || /snap/bin/chromium --version ``` -------------------------------- ### Get Quote Output Example Source: https://github.com/marketcalls/openalgo/blob/main/docs/prd/flow-node-reference.md Example of the JSON output when fetching current quote data for a symbol. ```json { "ltp": 625.50, "open": 620.00, "high": 628.00, "low": 618.50, "close": 622.00, "volume": 1500000 } ``` -------------------------------- ### Install OpenAlgo Source: https://github.com/marketcalls/openalgo/blob/main/docs/userguide/30-faqs/README.md Clone the repository, set up the environment by copying the sample .env file, and run the application using uv. ```bash git clone https://github.com/marketcalls/openalgo.git cd openalgo cp .sample.env .env uv run app.py ``` -------------------------------- ### Analyze OpenAlgo Installation Logs Source: https://github.com/marketcalls/openalgo/blob/main/install/README.md Examine installation logs to troubleshoot setup issues for multiple OpenAlgo deployments. This helps identify errors during the installation process. ```bash # List all installation logs ls -l install/logs/ # View latest installation log cat install/logs/$(ls -t install/logs/ | head -1) # Example: View specific deployment logs cat install/logs/install_20240101_120000.log # Fyers installation cat install/logs/install_20240101_143000.log # Zerodha installation ``` -------------------------------- ### Ngrok Output Example Source: https://github.com/marketcalls/openalgo/blob/main/docs/design/29-ngrok-config/README.md This is an example of the output displayed when OpenAlgo starts and ngrok is active, showing the local and ngrok URLs. ```text ╭─── OpenAlgo v2.0.0 ───────────────────────────────────────────╮ │ │ │ Endpoints │ │ Web App http://127.0.0.1:5000 │ │ WebSocket ws://127.0.0.1:8765 │ │ Ngrok https://abc123.ngrok.io │ │ │ │ Status Ready │ │ │ ╰───────────────────────────────────────────────────────────────╯ ``` -------------------------------- ### Run Production Installation Script Source: https://github.com/marketcalls/openalgo/blob/main/docs/userguide/04-installation/README.md Execute the installation script with sudo privileges. It will prompt for domain, broker, and credentials. ```bash sudo ./install.sh ``` -------------------------------- ### Get Depth Output Example Source: https://github.com/marketcalls/openalgo/blob/main/docs/prd/flow-node-reference.md Example of the JSON output when fetching market depth data, showing buy and sell orders. ```json { "buy": [ {"price": 625.45, "quantity": 1000, "orders": 5} ], "sell": [ {"price": 625.50, "quantity": 800, "orders": 3} ] } ``` -------------------------------- ### Recommended Setup Requirements Source: https://github.com/marketcalls/openalgo/blob/main/docs/userguide/03-system-requirements/README.md This outlines the recommended hardware and software specifications for a more robust setup. ```text Recommended Setup: ┌─────────────────────────────┐ │ • 4 GB RAM │ │ • 2 vCPU │ │ • 5 GB SSD │ │ • Python 3.12 │ │ • Ubuntu 22.04 LTS │ │ • Low-latency connection │ └─────────────────────────────┘ ``` -------------------------------- ### Initialize TOTP Setup Source: https://github.com/marketcalls/openalgo/blob/main/docs/design/50-totp-configuration/README.md Initiates the TOTP setup process by generating a secret key and a provisioning URI for QR code generation. This endpoint is typically called first to start the 2FA setup. ```APIDOC ## POST /api/auth/totp/setup ### Description Initializes the TOTP setup process, generating a secret and provisioning URI. ### Method POST ### Endpoint /api/auth/totp/setup ### Headers - **Authorization** (string) - Required - Bearer USER_TOKEN ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. - **data** (object) - Contains the generated TOTP details. - **secret** (string) - The generated TOTP secret key. - **qr_code** (string) - The QR code image data in base64 format. - **provisioning_uri** (string) - The URI used to configure authenticator apps. ### Response Example ```json { "status": "success", "data": { "secret": "JBSWY3DPEHPK3PXP", "qr_code": "data:image/png;base64,iVBORw0KGgo...", "provisioning_uri": "otpauth://totp/OpenAlgo:user@example.com?secret=JBSWY3DPEHPK3PXP&issuer=OpenAlgo" } } ``` ``` -------------------------------- ### Install and Enable Fail2ban Source: https://github.com/marketcalls/openalgo/blob/main/docs/audit/recommendations.md Install Fail2ban to protect your SSH service by blocking repeated failed login attempts. Ensure it is enabled and started. ```bash sudo apt install fail2ban sudo systemctl enable fail2ban sudo systemctl start fail2ban ``` -------------------------------- ### Quick Install OpenAlgo (All Platforms) Source: https://github.com/marketcalls/openalgo/blob/main/docs/userguide/04-installation/README.md Use this command-line sequence for a fast installation on any supported operating system. It clones the repository, installs the UV package manager, sets up the environment file, and runs the application. ```bash # 1. Clone the repository git clone https://github.com/marketcalls/openalgo.git cd openalgo # 2. Install UV package manager pip install uv # 3. Create configuration cp .sample.env .env # 4. Run OpenAlgo uv run app.py ``` -------------------------------- ### Quick Start Docker Development Source: https://github.com/marketcalls/openalgo/blob/main/docs/userguide/04-installation/README.md Clone the repository, create and configure the `.env` file for Docker, then build and start the OpenAlgo services using Docker Compose. ```bash # Clone repository git clone https://github.com/marketcalls/openalgo.git cd openalgo # Create environment file cp .sample.env .env # Edit .env with the Docker settings above # Build and start docker-compose up --build ``` -------------------------------- ### Minimum Setup Requirements Source: https://github.com/marketcalls/openalgo/blob/main/docs/userguide/03-system-requirements/README.md This outlines the minimum hardware and software specifications for a basic setup. ```text Minimum Setup: ┌─────────────────────────────┐ │ • 2 GB RAM │ │ • 1 vCPU │ │ • 1 GB Storage │ │ • Python 3.11+ │ │ • Stable Internet │ └─────────────────────────────┘ ``` -------------------------------- ### Download and Execute Installation Script Source: https://github.com/marketcalls/openalgo/blob/main/install/Docker-Multi-SSL-README.md Run this command to download the advanced installation script and make it executable. ```bash wget https://raw.githubusercontent.com/marketcalls/openalgo/main/install/install-docker-multi-custom-ssl.sh chmod +x install-docker-multi-custom-ssl.sh ./install-docker-multi-custom-ssl.sh ``` -------------------------------- ### Timeline Example: Weekend Source: https://github.com/marketcalls/openalgo/blob/main/docs/prd/python-strategies-scheduling.md Shows the execution flow on a non-trading day, highlighting how strategy starts are skipped. ```text ┌─────────────────────────────────────────────────────────────────────────────┐ │ Saturday, January 20, 2024 (Weekend) │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ │ 00:01 daily_trading_day_check() runs │ │ → Is Saturday → NOT a trading day │ │ → All scheduled strategies remain stopped │ │ │ │ 09:20 strategy_start_ema_crossover job fires │ │ → scheduled_start_strategy('ema_crossover') │ │ → is_trading_day() returns False │ │ → Start skipped │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ ``` -------------------------------- ### React App Setup Source: https://github.com/marketcalls/openalgo/blob/main/DISCOVERY_MAP.md Serves the setup page of the React application. ```APIDOC ## GET /setup ### Description Serves the setup page of the React application. ### Method GET ### Endpoint `/setup` ``` -------------------------------- ### Clone and Setup Repository Source: https://github.com/marketcalls/openalgo/blob/main/CONTRIBUTING.md Clone your forked repository, add the upstream remote, and verify your remotes. This is the initial step for setting up your local development environment. ```bash # Fork the repository on GitHub (click Fork button) # Clone your fork git clone https://github.com/YOUR_USERNAME/openalgo.git cd openalgo # Add upstream remote git remote add upstream https://github.com/marketcalls/openalgo.git # Verify remotes git remote -v ``` -------------------------------- ### Example .env Configuration Source: https://github.com/marketcalls/openalgo/blob/main/docs/userguide/04-installation/README.md This is an example of the .env file used for configuration. Remember to change sensitive values. ```ini # Application Settings FLASK_HOST=127.0.0.1 FLASK_PORT=5000 # Security (CHANGE THESE!) APP_KEY=your-secret-key-here API_KEY_PEPPER=your-pepper-here # Broker Selection BROKER=zerodha # Broker Credentials BROKER_API_KEY=your-api-key BROKER_API_SECRET=your-api-secret ``` -------------------------------- ### Install UV and Configure (Ubuntu/Linux) Source: https://github.com/marketcalls/openalgo/blob/main/docs/userguide/04-installation/README.md Install the UV package manager and create the environment configuration file for OpenAlgo on Ubuntu/Linux. ```bash # Install UV pip install uv # Create configuration cp .sample.env .env ``` -------------------------------- ### Troubleshooting Module Import Errors Source: https://github.com/marketcalls/openalgo/blob/main/test/README_OPTION_TESTS.md Example of a ModuleNotFoundError and its solution. Install missing Python packages using pip or uv pip. ```bash ModuleNotFoundError: No module named 'requests' **Solution**: Install required packages: ```bash pip install requests # or uv pip install requests ``` ``` -------------------------------- ### Python Virtual Environment Setup Source: https://github.com/marketcalls/openalgo/blob/main/docs/test/QUICK_TEST_CHECKLIST.md Commands to set up a Python virtual environment and install dependencies. Replace 'python3.11' with your desired Python version. ```bash python3.11 -m venv venv && source venv/bin/activate && pip install -r requirements.txt && python app.py ``` -------------------------------- ### Install and Run OpenAlgo Application Source: https://github.com/marketcalls/openalgo/blob/main/docs/design/README.md Installs the uv package manager, configures the environment by copying a sample .env file, and then runs the application using uv. ```bash pip install uv cp .sample.env .env uv run app.py ``` -------------------------------- ### Start OpenAlgo Project Source: https://github.com/marketcalls/openalgo/blob/main/docs/test/QUICK_TEST_CHECKLIST.md Commands to set up and run the OpenAlgo project locally. Ensure you are in the project root, pull the latest changes, sync dependencies, build the frontend, and then run the application. ```bash cd openalgo git pull uv sync cd frontend && npm run build && cd .. uv run app.py ``` -------------------------------- ### Example Prompt for Getting Quote Source: https://github.com/marketcalls/openalgo/blob/main/docs/userguide/remote-mcp.md Use this prompt to retrieve the Last Traded Price (LTP) for a specific stock symbol on a given exchange. ```text Using OpenAlgo, give me the LTP of RELIANCE on NSE. ``` -------------------------------- ### Daily Trading Summary Example Source: https://github.com/marketcalls/openalgo/blob/main/docs/userguide/23-telegram-bot/README.md Displays a formatted daily trading summary. This is a text-based output and does not require specific programming language setup. ```text 📊 DAILY TRADING SUMMARY ━━━━━━━━━━━━━━━━━━━━━━━━ Date: 2025-01-21 (Tuesday) 📈 P&L ─────────────────────── Realized: ₹8,500 Unrealized: ₹2,300 Total: ₹10,800 (+2.16%) 📋 TRADES ─────────────────────── Total: 15 Winning: 10 (66.7%) Losing: 5 (33.3%) Avg Win: ₹1,200 Avg Loss: ₹550 📊 POSITIONS (EOD) ─────────────────────── SBIN: +100 @ 625 (P&L: +₹500) HDFC: -50 @ 1650 (P&L: +₹800) 🎯 TOP PERFORMERS ─────────────────────── 1. NIFTY30JAN25FUT: +₹3,500 2. SBIN: +₹2,000 3. HDFC: +₹1,500 Happy Trading! 🚀 ``` -------------------------------- ### OAuth Flow Example Source: https://github.com/marketcalls/openalgo/blob/main/docs/prd/remote-mcp.md Illustrates the typical user-facing OAuth flow for granting MCP client access, starting from redirection to the authorization server. ```text 1. claude.ai redirects to https://mcp.example/oauth/authorize?... 2. /oauth/authorize is gated by @check_session_validity: - If no valid session → standard OpenAlgo login page (username + password + TOTP) - On successful login → redirected back to the consent screen 3. Consent screen shows: "claude.ai wants: read:market, read:account [, write:orders]" [Authorize] [Deny] 4. Authorize → server emits authorization code → redirect back to claude.ai ``` -------------------------------- ### Local Development Setup (uv) Source: https://github.com/marketcalls/openalgo/blob/main/docs/releases/version-2.0.1.0-released.md Commands for local developers to pull the latest changes, synchronize dependencies, build the frontend, and run the application using uv. ```bash git pull origin main uv sync cd frontend && npm install && npm run build uv run app.py ``` -------------------------------- ### Timeline Example: Trading Day Source: https://github.com/marketcalls/openalgo/blob/main/docs/prd/python-strategies-scheduling.md Illustrates the sequence of events on a typical trading day, from daily checks to strategy start and stop times. ```text ┌─────────────────────────────────────────────────────────────────────────────┐ │ Monday, January 15, 2024 (Trading Day) │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ │ 00:01 daily_trading_day_check() runs │ │ → Is Monday, not a holiday → Trading day confirmed │ │ │ │ 09:20 strategy_start_ema_crossover job fires │ │ → scheduled_start_strategy('ema_crossover') │ │ → Strategy subprocess started (PID: 12345) │ │ → Log streaming begins │ │ │ │ 09:21 market_hours_enforcer() runs (every minute) │ │ 09:22 market_hours_enforcer() runs │ │ ... │ │ │ │ 15:15 strategy_stop_ema_crossover job fires │ │ → scheduled_stop_strategy('ema_crossover') │ │ → SIGTERM sent to process group │ │ → Process terminated gracefully │ │ │ │ 15:16 market_hours_enforcer() runs │ │ → Confirms all strategies stopped │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ ``` -------------------------------- ### Example: Quote Command Source: https://github.com/marketcalls/openalgo/blob/main/docs/whatsapp.md Use the /quote command to get the last traded price of a symbol. You can optionally specify the exchange; it defaults to NSE if omitted. ```plaintext /quote RELIANCE /quote NIFTY NSE_INDEX ``` -------------------------------- ### Download OpenAlgo Installation Script Source: https://github.com/marketcalls/openalgo/blob/main/install/README.md Connect to your Linux server and download the installation script using wget or curl. Make the script executable. ```bash # Connect to your Linux server via SSH ssh user@your_server_ip # Create a directory for installation mkdir -p ~/openalgo-install cd ~/openalgo-install # Download the installation script wget https://raw.githubusercontent.com/marketcalls/openalgo/main/install/install.sh # Or using curl curl -O https://raw.githubusercontent.com/marketcalls/openalgo/main/install/install.sh # Make the script executable chmod +x install.sh ``` -------------------------------- ### Starting the OpenAlgo Application Source: https://github.com/marketcalls/openalgo/blob/main/docs/test/BROKER_INTEGRATION_TESTING_GUIDE.md Navigate to the OpenAlgo directory and start the application using uv unicorn. Access the UI, Swagger documentation, API logs, and WebSocket testing interface via the provided URLs. ```bash cd openalgo uv run app.py # UI: http://127.0.0.1:5000 # Swagger: http://127.0.0.1:5000/api/docs # API logs: http://127.0.0.1:5000/analyzer # WS test: http://127.0.0.1:5000/websocket/test ``` -------------------------------- ### Broker Adapter Implementation Example (Zerodha) Source: https://github.com/marketcalls/openalgo/blob/main/docs/design/06-websockets/README.md Python example of a `ZerodhaAdapter` class inheriting from `BaseBrokerWebSocketAdapter`, demonstrating connection, subscription, and tick handling. ```python class ZerodhaAdapter(BaseBrokerWebSocketAdapter): def connect(self, auth_token: str, feed_token: str = None): api_key, access_token = auth_token.split(':') self.kite_ws = KiteTicker(api_key, access_token) self.kite_ws.on_ticks = self._on_ticks self.kite_ws.connect() def subscribe(self, symbols: list, mode: str = "LTP"): tokens = [self._get_token(sym) for sym in symbols] kite_mode = self._map_mode(mode) self.kite_ws.subscribe(tokens) self.kite_ws.set_mode(kite_mode, tokens) def _on_ticks(self, ws, ticks): for tick in ticks: normalized = self._normalize_tick(tick) self._publish_to_zmq(normalized) ``` -------------------------------- ### Historical Data Request Payload Source: https://github.com/marketcalls/openalgo/blob/main/docs/test/MANUAL_TESTING_GUIDE.md Example JSON payload to request historical data for a symbol. Specify the interval, start date, and end date for the desired period. ```json { "apikey": "YOUR_API_KEY", "symbol": "RELIANCE", "exchange": "NSE", "interval": "5m", "start_date": "2025-01-01", "end_date": "2025-01-13" } ``` -------------------------------- ### Download and Prepare Multi-Domain Installation Script Source: https://github.com/marketcalls/openalgo/blob/main/docs/installation-guidelines/getting-started/ubuntu-server-installation.md Downloads the specialized script for multi-domain deployments and makes it executable. ```bash wget https://raw.githubusercontent.com/marketcalls/openalgo/main/install/install-multi.sh chmod +x install-multi.sh ``` -------------------------------- ### Filter Logs by Date Range Source: https://github.com/marketcalls/openalgo/blob/main/docs/design/22-log-section/README.md Example of a React component state for managing a date range filter. Use this to define the start and end dates for log filtering. ```javascript // React component example const [dateRange, setDateRange] = useState({ start: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), end: new Date() }); ``` -------------------------------- ### Install OpenAlgo with Official Script Source: https://github.com/marketcalls/openalgo/blob/main/docs/userguide/04-installation/README.md Use the official install script to set up OpenAlgo on your system. ```bash mkdir -p ~/openalgo-install cd ~/openalgo-install wget https://raw.githubusercontent.com/marketcalls/openalgo/main/install/install.sh chmod +x install.sh sudo ./install.sh ``` -------------------------------- ### Ngrok Command Example Source: https://github.com/marketcalls/openalgo/blob/main/docs/design/29-ngrok-config/README.md This command starts an ngrok tunnel for HTTP traffic on port 5000. It provides an encrypted tunnel, HTTPS termination, and request inspection capabilities. ```bash ngrok http 5000 ``` -------------------------------- ### Start Application for Database Initialization Source: https://github.com/marketcalls/openalgo/blob/main/docs/design/30-upgrade-procedure/README.md Starts the application using 'uv run app.py' to automatically initialize any new database tables. This is a safe operation that does not overwrite existing data. ```bash # Start the app to initialize any new database tables # Tables are created if they don't exist (safe - won't overwrite existing data) uv run app.py ``` -------------------------------- ### Group Chat ID Configuration Source: https://github.com/marketcalls/openalgo/blob/main/docs/userguide/23-telegram-bot/README.md This example shows the format for a group chat ID, which is required for configuring group notifications in OpenAlgo. Group IDs typically start with a hyphen. ```text Group Chat ID: -1001234567890 ``` -------------------------------- ### Initialize WebSocket Adapter using Factory Source: https://github.com/marketcalls/openalgo/blob/main/docs/design/52-broker-factory/README.md Demonstrates how to use the `create_broker_adapter` factory function to instantiate a broker adapter and initialize it with user credentials. ```python # Initialize WebSocket system from websocket_proxy.broker_factory import create_broker_adapter from database.auth_db import get_user_profile def initialize_websocket(user_id): # Get user's active broker user_profile = get_user_profile(user_id) active_broker = user_profile.get('active_broker') # Create adapter using factory adapter = create_broker_adapter(active_broker) # Initialize with user credentials adapter.initialize( broker_name=active_broker, user_id=user_id ) # Connect to broker WebSocket adapter.connect() return adapter ``` -------------------------------- ### Broker Capabilities API Response (Crypto) Source: https://github.com/marketcalls/openalgo/blob/main/docs/audit/broker-exchange-separation-audit.md Example JSON response for the GET /api/broker/capabilities endpoint when a crypto broker is configured. It specifies crypto-related exchanges and indicates leverage configuration is available. ```json { "status": "success", "data": { "broker_name": "deltaexchange", "broker_type": "crypto", "supported_exchanges": ["CRYPTO"], "leverage_config": true } } ``` -------------------------------- ### Broker Capabilities API Response (Stock) Source: https://github.com/marketcalls/openalgo/blob/main/docs/audit/broker-exchange-separation-audit.md Example JSON response for the GET /api/broker/capabilities endpoint when a stock broker is configured. It includes broker name, type, supported exchanges, and leverage configuration. ```json { "status": "success", "data": { "broker_name": "zerodha", "broker_type": "IN_stock", "supported_exchanges": ["NSE", "BSE", "NFO", "BFO", "CDS", "MCX", "NSE_INDEX", "BSE_INDEX", "MCX_INDEX"], "leverage_config": false } } ```