# Table of Contents - [What is OpenAlgo? | Documentation](#what-is-openalgo-documentation) - [Why to Build with OpenAlgo? | Documentation](#why-to-build-with-openalgo-documentation) - [OpenAlgo Architecture | Documentation](#openalgo-architecture-documentation) - [Community Support | Documentation](#community-support-documentation) - [OpenAlgo GPT | Documentation](#openalgo-gpt-documentation) - [New Features | Documentation](#new-features-documentation) - [Traffic/Latency Monitor | Documentation](#traffic-latency-monitor-documentation) - [Python Strategy Hosting | Documentation](#python-strategy-hosting-documentation) - [Mini FOSS Universe | Documentation](#mini-foss-universe-documentation) - [Historify | Documentation](#historify-documentation) - [Action Center | Documentation](#action-center-documentation) - [PNL Tracker | Documentation](#pnl-tracker-documentation) - [Flow - Visual Strategy Builder | Documentation](#flow-visual-strategy-builder-documentation) - [Responsibilities | Documentation](#responsibilities-documentation) - [Compliance | Documentation](#compliance-documentation) - [Monetization | Documentation](#monetization-documentation) - [Chartink Integration | Documentation](#chartink-integration-documentation) - [Fast Scalper | Documentation](#fast-scalper-documentation) - [API Analyzer | Documentation](#api-analyzer-documentation) - [Brokers | Documentation](#brokers-documentation) - [Exchanges | Documentation](#exchanges-documentation) - [Firstock | Documentation](#firstock-documentation) - [5paisa (XTS) | Documentation](#5paisa-xts-documentation) - [AliceBlue | Documentation](#aliceblue-documentation) - [AngelOne | Documentation](#angelone-documentation) - [5Paisa | Documentation](#5paisa-documentation) - [FlatTrade | Documentation](#flattrade-documentation) - [Delta Exchange | Documentation](#delta-exchange-documentation) - [Fyers | Documentation](#fyers-documentation) - [Definedge | Documentation](#definedge-documentation) - [Compositedge | Documentation](#compositedge-documentation) - [IndiaBulls Securities | Documentation](#indiabulls-securities-documentation) - [IIFL (XTS) | Documentation](#iifl-xts-documentation) - [Shoonya | Documentation](#shoonya-documentation) - [Dhan(Sandbox) | Documentation](#dhan-sandbox-documentation) - [Dhan | Documentation](#dhan-documentation) - [Getting Started | Documentation](#getting-started-documentation) - [Static IP | Documentation](#static-ip-documentation) - [Pocketful | Documentation](#pocketful-documentation) - [Tradejini | Documentation](#tradejini-documentation) - [Accessing OpenAlgo | Documentation](#accessing-openalgo-documentation) - [Start OpenAlgo | Documentation](#start-openalgo-documentation) - [Upstox | Documentation](#upstox-documentation) - [RMoney (XTS) | Documentation](#rmoney-xts-documentation) - [Pre-Requesties | Documentation](#pre-requesties-documentation) - [Nubra | Documentation](#nubra-documentation) - [Groww | Documentation](#groww-documentation) - [Kotak Securities | Documentation](#kotak-securities-documentation) - [Motilal Oswal | Documentation](#motilal-oswal-documentation) - [Paytm | Documentation](#paytm-documentation) - [Samco | Documentation](#samco-documentation) - [Start OpenAlgo | Documentation](#start-openalgo-documentation) - [Setup | Documentation](#setup-documentation) - [IndMoney (INDstocks) | Documentation](#indmoney-indstocks-documentation) - [HouseOfFoss | Documentation](#houseoffoss-documentation) - [TOTP Configuration | Documentation](#totp-configuration-documentation) - [V1 | Documentation](#v1-documentation) - [Mstock | Documentation](#mstock-documentation) - [SSL Verification Failed | Documentation](#ssl-verification-failed-documentation) - [Mac OS Installation | Documentation](#mac-os-installation-documentation) - [Windows Installation | Documentation](#windows-installation-documentation) - [Setup | Documentation](#setup-documentation) - [JainamXTS | Documentation](#jainamxts-documentation) - [Install Dependencies | Documentation](#install-dependencies-documentation) - [Install certifi | Documentation](#install-certifi-documentation) - [Install Dependencies | Documentation](#install-dependencies-documentation) - [Zerodha | Documentation](#zerodha-documentation) - [Ngrok Config | Documentation](#ngrok-config-documentation) - [Windows Server Installation | Documentation](#windows-server-installation-documentation) - [Testing OpenAlgo in Cloud | Documentation](#testing-openalgo-in-cloud-documentation) - [Wisdom Capital | Documentation](#wisdom-capital-documentation) - [Pre-Requesites | Documentation](#pre-requesites-documentation) - [Accessing OpenAlgo | Documentation](#accessing-openalgo-documentation) - [Zebu | Documentation](#zebu-documentation) - [Ngrok Config | Documentation](#ngrok-config-documentation) - [Accounts API | Documentation](#accounts-api-documentation) - [Cloudflared with Custom Domain | Documentation](#cloudflared-with-custom-domain-documentation) - [Environmental Variables | Documentation](#environmental-variables-documentation) - [Contributors | Documentation](#contributors-documentation) - [Ubuntu Server Installation | Documentation](#ubuntu-server-installation-documentation) - [Tradingview | Documentation](#tradingview-documentation) - [Skills | Documentation](#skills-documentation) - [API Collections | Documentation](#api-collections-documentation) - [Devtunnels | Documentation](#devtunnels-documentation) - [Order Constants | Documentation](#order-constants-documentation) - [Amazon Elastic Beanstalk | Documentation](#amazon-elastic-beanstalk-documentation) - [Utilities API | Documentation](#utilities-api-documentation) - [HTTP Status Codes | Documentation](#http-status-codes-documentation) - [Metatrader 5 | Documentation](#metatrader-5-documentation) - [Data API | Documentation](#data-api-documentation) - [Ping | Documentation](#ping-documentation) - [Analyzer Toggle | Documentation](#analyzer-toggle-documentation) - [Symbol Format | Documentation](#symbol-format-documentation) - [Orders API | Documentation](#orders-api-documentation) - [Amibroker | Documentation](#amibroker-documentation) - [Download & Install Library | Documentation](#download-install-library-documentation) - [Playground | Documentation](#playground-documentation) - [Ban IP | Documentation](#ban-ip-documentation) - [Architecture | Documentation](#architecture-documentation) - [Practices | Documentation](#practices-documentation) - [43 - Telegram Bot Configuration | Documentation](#43-telegram-bot-configuration-documentation) - [44 - Toast Notifications System | Documentation](#44-toast-notifications-system-documentation) - [51 - Broker and System Config | Documentation](#51-broker-and-system-config-documentation) - [50 - TOTP Configuration | Documentation](#50-totp-configuration-documentation) - [52 - Broker Factory Implementation | Documentation](#52-broker-factory-implementation-documentation) - [48 - Password Reset | Documentation](#48-password-reset-documentation) - [47 - SMTP Configuration | Documentation](#47-smtp-configuration-documentation) - [44 - PnL Tracker | Documentation](#44-pnl-tracker-documentation) - [46 - Search | Documentation](#46-search-documentation) - [42 - Action Center | Documentation](#42-action-center-documentation) - [49 - Themes | Documentation](#49-themes-documentation) - [release | Documentation](#release-documentation) - [Version 2.0.0.5 Released | Documentation](#version-2-0-0-5-released-documentation) - [Version 2.0.0.3 Released | Documentation](#version-2-0-0-3-released-documentation) - [Version 2.0.0.4 Released | Documentation](#version-2-0-0-4-released-documentation) - [Version 1.0.0.39 Released | Documentation](#version-1-0-0-39-released-documentation) - [Version 1.0.0.38 Released | Documentation](#version-1-0-0-38-released-documentation) --- # What is OpenAlgo? | Documentation OpenAlgo is a free, open source, self hosted algorithmic trading platform that bridges your trading ideas with real execution. Built with Python Flask and a modern React frontend, it provides a unified API layer across 30+ Indian brokers, enabling seamless automation from Amibroker, TradingView, GoCharting, N8N, Python, Java, Go, .NET, Node.js, ChartInk, MetaTrader, Excel, and Google Sheets. Traders can also receive strategy alerts directly on Telegram, ensuring real time visibility and control. ### [hashtag](https://docs.openalgo.in/#overview) Overview **OpenAlgo** is an **open-source, self-hosted algorithmic trading platform** that makes it easy to build, test, and run trading strategies across multiple Indian brokers using a **single, consistent interface**. Beyond execution, OpenAlgo empowers traders to completely own their trading infrastructure. Traders can effortlessly build algorithmic strategies, indicators, and custom trading dashboards using AI agentic coding tools, connect with their favorite trading platforms, and deploy strategies without being tied to any single broker or vendor. By standardizing broker APIs into one consistent trading layer, OpenAlgo allows strategies to work the same way across brokers, making automation faster, scalable, and fully under the trader’s control. * * * ### [hashtag](https://docs.openalgo.in/#what-problem-does-openalgo-solve) What Problem Does OpenAlgo Solve? OpenAlgo is built around one core idea: effortlessly create trading strategies using AI tools and run and monitor them like never before. Instead of learning multiple broker APIs and documentation, AI agentic coding tools such as Codex, Claude Code, Antigravity, and OpenCode understand OpenAlgo directly. Traders can build strategies faster, create their own algo features, design custom trading alerts, connect to any trading platform of their choice, store historical data, and run analytics or backtesting within a fully self hosted environment. There are no code tool offerings available, and you completely own your data and infrastructure. Most brokers expose their own APIs with different authentication methods, order parameters, market data structures, and operational limitations. This creates unnecessary complexity for traders and developers. OpenAlgo removes this friction by providing one common API layer across supported brokers, delivering consistent behavior across live trading and testing environments. Strategies work the same way regardless of the broker, allowing you to switch brokers without rewriting logic while maintaining full control over execution, data, and automation. * * * ### [hashtag](https://docs.openalgo.in/#who-should-use-openalgo) Who Should Use OpenAlgo? #### [hashtag](https://docs.openalgo.in/#traders) Traders OpenAlgo is suitable for traders who want to: * Automate rule-based or discretionary strategies * Execute TradingView, ChartInk, or Amibroker alerts * Test strategies safely using sandbox testing * Monitor orders, positions, and profit/loss in real time * Maintain full control over execution and data No coding expertise is required to get started, though advanced users can extend it further. * * * #### [hashtag](https://docs.openalgo.in/#developers) Developers OpenAlgo is designed for developers who need: * A stable and well-documented REST and WebSocket API * Uniform request and response formats across brokers * SDKs in multiple programming languages * A self-hosted, extensible trading backend * Support for advanced use cases such as AI-driven execution * * * ### [hashtag](https://docs.openalgo.in/#key-capabilities) Key Capabilities #### [hashtag](https://docs.openalgo.in/#unified-trading-api) Unified Trading API OpenAlgo exposes a standardized API that allows you to: * Place, modify, and cancel orders * Fetch positions, holdings, and funds * Access orderbook and tradebook * Retrieve real-time and historical market data All supported brokers follow the same API structure. * * * #### [hashtag](https://docs.openalgo.in/#multiple-ways-to-run-strategies) Multiple Ways to Run Strategies OpenAlgo supports different strategy workflows: * **Hosted Python strategies** running directly inside OpenAlgo * **Visual Flow strategies** built using a no-code, drag-and-drop interface * **External signals** from TradingView, Amibroker, ChartInk, Excel, or Google Sheets * **AI agents** connected through the MCP server This flexibility allows users to choose the approach that best fits their experience level. * * * #### [hashtag](https://docs.openalgo.in/#sandbox-testing-environment) Sandbox Testing Environment OpenAlgo includes a fully isolated **sandbox testing environment** for validating strategies before live deployment. Sandbox testing provides: * Live market data * Configurable **sandbox capital** * Realistic margin and order behavior * Automatic handling of exchange square-off rules * Complete isolation from live trading data * * * #### [hashtag](https://docs.openalgo.in/#order-control-and-safety) Order Control and Safety OpenAlgo offers optional order approval workflows: * Automatic execution for fully automated strategies * Manual approval for supervised or discretionary trading * Full audit trail of all actions This helps reduce execution risk and improves transparency. * * * #### [hashtag](https://docs.openalgo.in/#security-and-privacy) Security and Privacy Security and data ownership are core principles of OpenAlgo: * Broker credentials are encrypted * Passwords are securely hashed * Two-factor authentication is supported * API access is rate-limited * No user data is collected or shared All data remains on infrastructure controlled by the user. * * * ### [hashtag](https://docs.openalgo.in/#deployment-and-usage) Deployment and Usage OpenAlgo is designed to be self-hosted: * Run on a local machine * Deploy on a VPS or cloud server * Suitable for personal, professional, and team use Once installed, it can serve as a central execution engine for all trading strategies. ### [hashtag](https://docs.openalgo.in/#what-openalgo-is-not) What OpenAlgo is NOT Let's be clear about what OpenAlgo doesn't do: Misconception Reality Get-rich-quick scheme It's a tool - profitability depends on your strategy Strategy provider You need your own trading ideas Financial advisor You're responsible for trading decisions Black box 100% open source - verify every line of code Cloud service Self-hosted - you control everything ### [hashtag](https://docs.openalgo.in/#system-requirements) System Requirements Component Minimum Recommended **OS** Windows 10, macOS 10.15, Ubuntu 20.04 Latest versions **Python** 3.12+ 3.12+ **RAM** 2 GB 2 GB+ **Storage** 2 GB 10 GB+ (for historical data) **Network** Stable internet Low latency connection ### [hashtag](https://docs.openalgo.in/#summary) Summary Aspect OpenAlgo **Cost** Free (Open Source, AGPL License) **Brokers** 25+ Indian brokers **Exchanges** NSE, NFO, BSE, BFO, MCX, CDS, BCD **Signal Sources** TradingView, Amibroker, ChartInk, Python, AI **Strategy Building** Flow (Visual), Python Hosting, External Webhooks **Sandbox Trading** Analyzer Mode with ₹1 Crore sandbox capital **Historical Data** Historify with DuckDB storage **Real-Time Data** WebSocket streaming for quotes and orders **Notifications** Telegram bot, WebSocket updates **Data Privacy** 100% - self-hosted on your infrastructure **Skill Required** Basic trading knowledge * * * [NextWhy to Build with OpenAlgo?chevron-right](https://docs.openalgo.in/why-to-build-with-openalgo) Last updated 1 month ago * [Overview](https://docs.openalgo.in/#overview) * [What Problem Does OpenAlgo Solve?](https://docs.openalgo.in/#what-problem-does-openalgo-solve) * [Who Should Use OpenAlgo?](https://docs.openalgo.in/#who-should-use-openalgo) * [Key Capabilities](https://docs.openalgo.in/#key-capabilities) * [Deployment and Usage](https://docs.openalgo.in/#deployment-and-usage) * [What OpenAlgo is NOT](https://docs.openalgo.in/#what-openalgo-is-not) * [System Requirements](https://docs.openalgo.in/#system-requirements) * [Summary](https://docs.openalgo.in/#summary) sun-brightdesktopmoon sun-brightdesktopmoon --- # Why to Build with OpenAlgo? | Documentation _"Why should I use OpenAlgo when I can just build my strategy directly on top of the broker's SDK or API?"_ It's a common question. Many start with broker SDKs because it feels quick—just wire your signals and send orders. But soon, the pain points show up: * How do you monitor trades in real-time? * Where do you store and replay logs? * How do you test webhooks or strategies before going live? * How do you manage symbols, expiries, and contracts across brokers? * What happens when you want to switch from Broker A to Broker B? That's when you realize the SDK is not enough. **OpenAlgo takes care of the heavy lifting.** It's not just an API wrapper—it's a **full-stack, open-source trading automation framework** designed to host strategies, manage brokers, and scale securely. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FpUyC8MAnG7JBCr2RrXvo%252Fimage.png%3Falt%3Dmedia%26token%3Dede4be9f-54d7-4050-b611-7aa362dc3dea&width=768&dpr=3&quality=100&sign=270fbeb4&sv=2) * * * ### [hashtag](https://docs.openalgo.in/why-to-build-with-openalgo#what-makes-openalgo-different) What Makes OpenAlgo Different? #### [hashtag](https://docs.openalgo.in/why-to-build-with-openalgo#strategy-management-and-hosting) Strategy Management & Hosting Host your **Python strategies directly inside OpenAlgo**, alongside strategies from TradingView, Amibroker, ChartInk, MetaTrader, Excel, or custom webhooks. Start, pause, schedule, monitor, and analyze—all from a central control plane. Capability Description **Python Strategy Hosting** Upload and run Python scripts with scheduling **Flow Visual Builder** Create strategies without code using drag-and-drop **Multi-Platform Support** TradingView, Amibroker, ChartInk, Excel, and more **Centralized Control** Manage all strategies from one dashboard #### [hashtag](https://docs.openalgo.in/why-to-build-with-openalgo#sandbox-testing-and-api-analyzer) Sandbox Testing & API Analyzer The **Analyzer Mode** works like a local sandbox—test your signals, APIs, and strategies with ₹1 Crore sandbox capital without hitting real broker servers. Validate everything before going live. Feature Benefit **Sandbox Capital** ₹1 Crore to test freely **Real Market Prices** Realistic simulation with live data **Margin Calculations** Actual margin requirements enforced **Position Tracking** Full position and holdings management **Zero Risk** Complete isolation from live trading #### [hashtag](https://docs.openalgo.in/why-to-build-with-openalgo#historical-data-and-backtesting) Historical Data & Backtesting **Historify** lets you download and store historical market data locally using DuckDB. Use this data for backtesting, analysis, or feeding into your strategy development workflow. Capability Description **Bulk Downloads** Download years of OHLCV data **DuckDB Storage** Efficient columnar storage **Multiple Timeframes** 1-minute to daily data **Export Options** CSV, JSON, or direct query #### [hashtag](https://docs.openalgo.in/why-to-build-with-openalgo#multi-broker-multi-platform) Multi-Broker, Multi-Platform OpenAlgo supports **24+ Indian brokers** via a **unified API and WebSocket layer**. Write your strategy once, and run it across Zerodha, Angel One, Dhan, Upstox, Fyers, Flattrade, Firstock, and more—without rewriting code. #### [hashtag](https://docs.openalgo.in/why-to-build-with-openalgo#unified-symbol-and-contract-management) Unified Symbol & Contract Management With OpenAlgo's **Common Symbol Format**, you don't have to worry about broker-specific quirks. Contracts, expiries, and lot sizes are maintained automatically. Broker Their Format OpenAlgo Format Zerodha `SBIN` `SBIN` Angel `SBIN-EQ` `SBIN` Dhan `SBIN` `SBIN` **One symbol format. All brokers.** * * * ### [hashtag](https://docs.openalgo.in/why-to-build-with-openalgo#speed-stability-and-control) Speed, Stability, and Control #### [hashtag](https://docs.openalgo.in/why-to-build-with-openalgo#performance-optimizations) Performance Optimizations Feature Impact **HTTPX Connection Pooling** 50ms–120ms latency vs 150ms–250ms in plain scripts **WebSocket Broadcast Layer** One broker stream powers multiple strategies **Symbol Caching** Instant symbol lookups without repeated API calls **Rate Limit Management** Automatic throttling to stay within broker limits #### [hashtag](https://docs.openalgo.in/why-to-build-with-openalgo#real-time-monitoring) Real-Time Monitoring Tool Purpose **Latency Monitor** Track order round-trip times **Traffic Logs** Complete API request/response history **P&L Tracker** Real-time profit/loss visualization **WebSocket Dashboard** Monitor live data connections #### [hashtag](https://docs.openalgo.in/why-to-build-with-openalgo#notification-and-alerts) Notification & Alerts Channel Capabilities **Telegram Bot** Trade notifications, commands, alerts **WebSocket Updates** Real-time order and position changes **Dashboard Alerts** Visual notifications in UI * * * ### [hashtag](https://docs.openalgo.in/why-to-build-with-openalgo#security-by-default) Security by Default OpenAlgo is production-tested with enterprise-grade security: Security Feature Description **CORS & CSP Headers** Cross-origin and content security policies **CSRF Protection** Token-based request validation **Rate Limiting** Per-endpoint request throttling **Two-Factor Auth** TOTP-based login security **Session Management** Secure session handling with timeouts **Audit Trails** Complete logging for compliance **API Key Encryption** Secure storage with pepper-based hashing **Subprocess Isolation** Sandboxed execution for hosted strategies Deploy locally, in **Docker**, or on cloud servers—secure out of the box. * * * ### [hashtag](https://docs.openalgo.in/why-to-build-with-openalgo#sdks-add-ins-and-ecosystem) SDKs, Add-ins, and Ecosystem #### [hashtag](https://docs.openalgo.in/why-to-build-with-openalgo#official-sdks) Official SDKs Language Package **Python** `openalgo` on PyPI **Node.js** REST API integration **Go** REST API integration #### [hashtag](https://docs.openalgo.in/why-to-build-with-openalgo#platform-integrations) Platform Integrations Platform Integration Type **TradingView** Webhooks **Amibroker** HTTP calls from AFL **ChartInk** Scanner webhooks **Excel** VBA with REST API **Google Sheets** Apps Script **MetaTrader 5** EA integration #### [hashtag](https://docs.openalgo.in/why-to-build-with-openalgo#deployment-options) Deployment Options Option Best For **Local** Personal desktop trading **Docker** Clean, reproducible deployments **Cloud Server** 24/7 automated trading **VPS** Low-latency remote access * * * ### [hashtag](https://docs.openalgo.in/why-to-build-with-openalgo#why-not-just-use-broker-apis-directly) Why Not Just Use Broker APIs Directly? With direct broker APIs, you'd have to build: Component What You'd Build OpenAlgo Provides **Strategy Hosting** Process management, scheduling Built-in with Python hosting **Testing Environment** Sandbox, mock broker Analyzer Mode with ₹1 Cr capital **Symbol Management** Expiry handling, contract mapping Unified symbol format **Connection Pooling** HTTP/WebSocket optimization HTTPX with connection reuse **Trade Dashboard** React UI, real-time updates Full React frontend included **Log Storage** Database, query interface SQLite with traffic logs **Latency Tracking** Timing, metrics, alerts Latency monitor built-in **Multi-Broker Support** N broker integrations 24+ brokers pre-integrated **Security Layer** Auth, rate limiting, CSRF Enterprise security included **Notifications** Telegram, alerts Telegram bot integrated OpenAlgo ships with all this—**pre-wired, tested, and open source**. * * * ### [hashtag](https://docs.openalgo.in/why-to-build-with-openalgo#open-source-freedom) Open Source Freedom Licensed under **AGPL**, OpenAlgo gives you: Freedom Description **Full Source Code** Inspect, modify, extend **Self-Hosting** Run on your infrastructure **No Per-Order Fees** Zero transaction costs **No Vendor Lock-in** Switch or fork anytime **Commercial Use** Build products on top (with compliance) **Community Support** Discord, GitHub, documentation * * * ### [hashtag](https://docs.openalgo.in/why-to-build-with-openalgo#the-bottom-line) The Bottom Line Aspect Broker APIs OpenAlgo **Setup Time** Weeks of development Hours to deploy **Broker Switching** Rewrite everything Change one config **Testing** Build your own sandbox Analyzer Mode ready **Monitoring** Build dashboards Full UI included **Security** Implement yourself Production-ready **Maintenance** You maintain everything Community maintained **Cost** Your development time Free and open source **Broker APIs give you** _**access**_**.** **OpenAlgo gives you** _**infrastructure**_**.** It doesn't replace your strategy logic—it **amplifies** it with the ecosystem you need to operate, monitor, test, and scale confidently. And when you're ready to switch brokers or expand to multi-broker setups, you'll already be on **OpenAlgo's unified, broker-agnostic foundation**. * * * **Previous**: 01 - What is OpenAlgo **Next**: 03 - Key Concepts [PreviousWhat is OpenAlgo?chevron-left](https://docs.openalgo.in/) [NextOpenAlgo Architecturechevron-right](https://docs.openalgo.in/openalgo-architecture) Last updated 3 months ago * [What Makes OpenAlgo Different?](https://docs.openalgo.in/why-to-build-with-openalgo#what-makes-openalgo-different) * [Speed, Stability, and Control](https://docs.openalgo.in/why-to-build-with-openalgo#speed-stability-and-control) * [Security by Default](https://docs.openalgo.in/why-to-build-with-openalgo#security-by-default) * [SDKs, Add-ins, and Ecosystem](https://docs.openalgo.in/why-to-build-with-openalgo#sdks-add-ins-and-ecosystem) * [Why Not Just Use Broker APIs Directly?](https://docs.openalgo.in/why-to-build-with-openalgo#why-not-just-use-broker-apis-directly) * [Open Source Freedom](https://docs.openalgo.in/why-to-build-with-openalgo#open-source-freedom) * [The Bottom Line](https://docs.openalgo.in/why-to-build-with-openalgo#the-bottom-line) sun-brightdesktopmoon Copy ┌─────────────────────────────────────────────────────────────────┐ │ Your Strategy Code │ │ (Write Once) │ └─────────────────────────────┬───────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ OpenAlgo Unified API │ │ (Common Interface for All Brokers) │ └───┬─────────┬─────────┬─────────┬─────────┬─────────┬──────────┘ │ │ │ │ │ │ ▼ ▼ ▼ ▼ ▼ ▼ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ │Zerodha│ │ Angel │ │ Dhan │ │ Fyers │ │Upstox │ │ More │ └───────┘ └───────┘ └───────┘ └───────┘ └───────┘ └───────┘ sun-brightdesktopmoon --- # OpenAlgo Architecture | Documentation [hashtag](https://docs.openalgo.in/openalgo-architecture#windows-mac-hosting-architecture) Windows/Mac Hosting Architecture -------------------------------------------------------------------------------------------------------------------------------- ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F9nhK1BjttOrokjikSz3W%252Fimage.png%3Falt%3Dmedia%26token%3D98943011-d9e9-4082-8772-4aa67e60735a&width=768&dpr=3&quality=100&sign=ad8d40f9&sv=2) [hashtag](https://docs.openalgo.in/openalgo-architecture#linux-server-hosting-architecture) Linux Server Hosting Architecture ---------------------------------------------------------------------------------------------------------------------------------- ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FbmjVjCZ5fC8LtAsQCzj3%252Fimage.png%3Falt%3Dmedia%26token%3D60d1661e-18ae-4aef-8bea-2de0e92aefcd&width=768&dpr=3&quality=100&sign=e1d63243&sv=2) [PreviousWhy to Build with OpenAlgo?chevron-left](https://docs.openalgo.in/why-to-build-with-openalgo) [NextMini FOSS Universechevron-right](https://docs.openalgo.in/mini-foss-universe) Last updated 3 months ago * [Windows/Mac Hosting Architecture](https://docs.openalgo.in/openalgo-architecture#windows-mac-hosting-architecture) * [Linux Server Hosting Architecture](https://docs.openalgo.in/openalgo-architecture#linux-server-hosting-architecture) sun-brightdesktopmoon sun-brightdesktopmoon --- # Community Support | Documentation Welcome to the OpenAlgo Community on Discord! This is your hub for connecting with fellow developers and algo traders, sharing insights, getting support, and collaborating on projects. ### [hashtag](https://docs.openalgo.in/community-support#how-to-join) How to Join To become a part of our growing community, please use the invitation link below: [Join the OpenAlgo Discord Communityarrow-up-right](https://discord.gg/UPh7QPsNhP) and you can raise your issues and feature request in [openalgo github section arrow-up-right](https://github.com/marketcalls/openalgo/issues) ### [hashtag](https://docs.openalgo.in/community-support#community-guidelines) Community Guidelines * **Respect:** Treat every member with respect. No harassment or discrimination is tolerated. * **Collaboration:** Feel free to ask for help and offer support. Share your knowledge and learn from others. * **No Spam:** Keep discussions on-topic. Avoid spamming channels with promotions or irrelevant content. * **Intellectual Property:** Respect copyright laws and do not share illegal downloads or copyrighted content. * **Privacy:** Do not share personal information of yourself or others. ### [hashtag](https://docs.openalgo.in/community-support#channels-and-their-purposes) Channels and Their Purposes * **#general:** General discussions related to algo trading and development. * **#developers:** Technical discussions about OpenAlgo's API, SDKs, and development. * **#algotraders:** Strategies, tips, and discussion for algo traders. * **#announcements:** Stay updated with the latest news and events. * **#trading-platforms:** Discuss various platforms and tools for trading. ### [hashtag](https://docs.openalgo.in/community-support#openalgo-virtual-meet) [OpenAlgo Virtual Meetarrow-up-right](https://learn.marketcalls.in/courses/-OpenAlgo-Developer-Meet---Mar-22-2024-65fd4c74a2a47848adb27c40) * **Event Time:** 02nd April 2024 (7.30 p.m IST) * **Agenda Highlights:** Discover features of OpenAlgo v1.0, integration techniques, plugin systems, and the roadmap for v2.0. ### [hashtag](https://docs.openalgo.in/community-support#support-and-faq) Support and FAQ #### [hashtag](https://docs.openalgo.in/community-support#how-can-i-get-help-with-an-issue) How can I get help with an issue? Post your question in the relevant channel. For technical issues, use #developers, and for trading-related inquiries, use #algotraders. #### [hashtag](https://docs.openalgo.in/community-support#are-there-any-regular-events-or-meetups) Are there any regular events or meetups? Yes, we host the OpenAlgo Virtual Meet annually. You can find the details in the #announcements channel. #### [hashtag](https://docs.openalgo.in/community-support#how-do-i-report-inappropriate-behavior) How do I report inappropriate behavior? Contact a moderator via direct message or use the `@moderator` tag in the #general channel. ### [hashtag](https://docs.openalgo.in/community-support#resources) Resources * \[OpenAlgo API Documentation\] * \[Tutorials and Guides\] * \[Trading Strategies and Tips\] * \[Code Repositories\] ### [hashtag](https://docs.openalgo.in/community-support#contact-us) Contact Us For direct support or inquiries, please contact the community moderators or reach out through the following email: [\[email protected\]](https://docs.openalgo.in/cdn-cgi/l/email-protection) . [PreviousMini FOSS Universechevron-left](https://docs.openalgo.in/mini-foss-universe) [NextOpenAlgo GPTchevron-right](https://docs.openalgo.in/openalgo-gpt) Last updated 3 months ago * [How to Join](https://docs.openalgo.in/community-support#how-to-join) * [Community Guidelines](https://docs.openalgo.in/community-support#community-guidelines) * [Channels and Their Purposes](https://docs.openalgo.in/community-support#channels-and-their-purposes) * [OpenAlgo Virtual Meet](https://docs.openalgo.in/community-support#openalgo-virtual-meet) * [Support and FAQ](https://docs.openalgo.in/community-support#support-and-faq) * [Resources](https://docs.openalgo.in/community-support#resources) * [Contact Us](https://docs.openalgo.in/community-support#contact-us) sun-brightdesktopmoon sun-brightdesktopmoon --- # OpenAlgo GPT | Documentation OpenAlgo GPT is an AI assistant built to help traders, investors, algo trading learners, and developers understand OpenAlgo and build trading strategies faster. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FlAOffJHkI6meB6gB2Adt%252Fopenalgo%2520customGPT.png%3Falt%3Dmedia%26token%3Da2dc520e-af9f-4df9-bf08-e9e575daaf81&width=768&dpr=3&quality=100&sign=7faf66bb&sv=2) It is designed for both non-coders and coders. If you are a trader with a strategy idea, you can explain it in simple words. If you are a developer, you can use it to generate cleaner OpenAlgo code, improve existing scripts, debug issues, and speed up strategy development. You can access OpenAlgo GPT here: [https://chatgpt.com/g/g-WK6vMYtbS-openalgo/arrow-up-right](https://chatgpt.com/g/g-WK6vMYtbS-openalgo/) OpenAlgo GPT helps bridge the gap between trading ideas and working code. Many traders know what they want to build but may not know how to convert that idea into Python. Many developers know Python but may need help understanding OpenAlgo APIs, symbol formats, order constants, technical indicators, WebSocket data, and strategy hosting. OpenAlgo GPT brings both worlds together. With OpenAlgo GPT, you can describe a strategy in plain English and ask it to generate Python code using OpenAlgo. For example, you can say: > Create a Python strategy for EMA crossover on NIFTY using 5 minute candles. Add stop loss, target, and duplicate-order prevention. Or: > Build an RSI strategy for SBIN. Buy when RSI crosses above 30 and exit when RSI crosses below 70. Make it suitable for OpenAlgo Strategy Hosting. OpenAlgo GPT can help convert such ideas into structured Python code with historical data fetching, indicator calculation, signal generation, risk controls, order placement logic, and safer execution practices. OpenAlgo GPT can help you build indicator-based strategies, intraday strategies, positional strategies, backtesting scripts, paper trading bots, live trading templates, WebSocket streaming scripts, Plotly charts, candlestick charts, indicator dashboards, scheduled strategies, and OpenAlgo-hosted Python strategy files. For non-coders, OpenAlgo GPT can explain trading code in simple language. You can paste a strategy and ask it to explain what each part does. You can also ask it to change the symbol, timeframe, stop loss, target, quantity, or indicator conditions. This makes it easier for traders to understand and modify strategies without needing deep programming knowledge. For coders, OpenAlgo GPT can help with OpenAlgo SDK usage, cleaner Python structure, DataFrame validation, technical indicator integration, backtesting logic, WebSocket callbacks, APScheduler jobs, SQLAlchemy workflows when needed, strategy hosting environment variables, and debugging OpenAlgo-related errors. OpenAlgo GPT understands the OpenAlgo Python SDK and can help with historical data, quotes, market depth, order placement, smart orders, basket orders, split orders, order modification, order cancellation, positions, holdings, funds, and broker-related API usage. It can help generate historical data code using OpenAlgo’s standard format with symbol, exchange, interval, start date, and end date. For daily candles, it follows OpenAlgo’s convention of using interval as D. It can also help validate the historical data before using it by checking whether the data is empty, whether OHLCV columns are available, whether candles are sorted properly, and whether missing values need to be handled. OpenAlgo GPT can also help users work with OpenAlgo’s technical indicator library. It can assist with trend indicators such as SMA, EMA, WMA, HMA, Supertrend, Ichimoku, and Alligator. It can help with momentum indicators such as RSI, MACD, Stochastic, CCI, Williams Percent R, Fisher Transform, and Connors RSI. It can help with volatility indicators such as ATR, Bollinger Bands, Keltner Channel, Donchian Channel, Chandelier Exit, and Historical Volatility. It can help with volume indicators such as OBV, VWAP, MFI, ADL, CMF, and RVOL. It can also help with statistical, hybrid, and utility indicators such as Linear Regression, Correlation, Beta, ADX, Aroon, Pivot Points, Parabolic SAR, crossover, crossunder, highest, lowest, change, and rate of change. Backtesting is another important area where OpenAlgo GPT can help. Users can ask it to create a backtest for a strategy using OpenAlgo historical data. A backtest can include entry rules, exit rules, indicator calculation, position tracking, trade list generation, profit and loss calculation, win rate, net profit or loss, drawdown, and summary statistics. Backtesting helps users study how a strategy behaved in the past, but it does not guarantee future results. OpenAlgo GPT can also help convert a backtest into a paper trading or live trading script. It can add practical safety controls such as stop loss, target, position sizing, max trades per day, duplicate-order prevention, candle-close confirmation, open position checks, order response validation, and graceful shutdown. Before using real capital, users should always test strategies in paper mode or in a controlled environment. For real-time market data, OpenAlgo GPT can help users build WebSocket scripts. It can assist with LTP streaming, quote streaming, market depth streaming, authentication, symbol subscription, unsubscription, callback handling, verbose mode control, and graceful disconnect. This is useful for users who want to build real-time dashboards, live trading systems, or event-driven strategies. OpenAlgo GPT can also help with data visualization. It can generate Plotly candlestick charts, OHLC charts, indicator overlays, buy and sell markers, volume charts, backtest equity curves, and strategy performance charts. For Plotly candlestick charts, it follows OpenAlgo’s working charting style and uses category-based x-axis formatting to avoid gaps caused by weekends and non-trading periods. Another useful capability is symbol format support. OpenAlgo GPT can help users understand the correct OpenAlgo symbol format for equities, indices, futures, options, currencies, and commodities. It can explain how equity symbols are written, how futures symbols are constructed, and how options symbols include the base symbol, expiry date, strike price, and option type. OpenAlgo GPT can also help users understand order constants. It can explain exchanges such as NSE, NFO, BSE, BFO, MCX, CDS, and NSE\_INDEX. It can explain product types such as CNC, MIS, and NRML. It can explain price types such as MARKET, LIMIT, SL, and SL-M. It can also explain actions such as BUY and SELL. One of the most useful workflows is preparing strategies for OpenAlgo Python Strategy Hosting. OpenAlgo allows users to host Python strategies inside OpenAlgo itself. Users can upload Python strategy files, start and stop strategies, schedule strategy execution, select exchange-specific calendars, pass custom parameters, monitor output, and run each strategy in an isolated process. OpenAlgo GPT can help create Python scripts that are suitable for this hosted environment. It can structure the code so that it reads environment variables such as the API key, host, WebSocket URL, symbol, exchange, and custom parameters. It can also help align the strategy’s exchange with the exchange calendar selected in OpenAlgo Strategy Hosting. For scheduled strategies, OpenAlgo GPT can help create APScheduler-based workflows using IST timezone. This can be useful for running signal checks every few minutes, starting strategies at market open, stopping near market close, or adding intraday square-off logic. OpenAlgo GPT does not write to databases unless users ask for it. When database support is required, it can help create SQLAlchemy-based workflows for storing trades, signals, backtest results, or execution records. The best way to use OpenAlgo GPT is to provide clear details about what you want to build. Include the symbol, exchange, timeframe, start date, end date, indicator rules, entry condition, exit condition, quantity or capital, product type, stop loss, target, and whether you want a backtest, paper trading script, live trading script, or OpenAlgo-hosted strategy. For example, a good prompt would be: > Create a paper trading strategy for RELIANCE on NSE using 5 minute candles. Buy when EMA 20 crosses above EMA 50. Exit when EMA 20 crosses below EMA 50. Use MIS product, quantity 1, stop loss 1 percent, target 2 percent. Make it suitable for OpenAlgo Strategy Hosting. You can also ask simpler questions such as: > Explain this strategy code in simple language. > > Create a Plotly candlestick chart with EMA 20 and EMA 50. > > Create a WebSocket quote streaming script for NIFTY and INFY. > > Explain the correct OpenAlgo symbol format for BANKNIFTY options. > > Generate a Supertrend strategy using OpenAlgo indicators. > > Convert this strategy into a paper trading bot. OpenAlgo GPT is a coding and documentation assistant for the OpenAlgo ecosystem. It helps users learn faster, code faster, and build trading workflows more confidently. It is not a profit-generating tool and should not be treated as financial advice. All generated strategies should be reviewed, tested, and validated before being used with real capital. The goal of OpenAlgo GPT is to make algo trading development more accessible. Traders can focus on their strategy ideas. Developers can focus on improving systems. Learners can understand how automated trading works. Together with OpenAlgo’s broker integration, Python SDK, technical indicators, WebSocket data, and strategy hosting, OpenAlgo GPT can help users move from idea to execution more efficiently. Explore OpenAlgo GPT here: [https://chatgpt.com/g/g-WK6vMYtbS-openalgo/arrow-up-right](https://chatgpt.com/g/g-WK6vMYtbS-openalgo/) Join the OpenAlgo community: [https://openalgo.in/discordarrow-up-right](https://openalgo.in/discord) Read the OpenAlgo documentation: [https://docs.openalgo.inarrow-up-right](https://docs.openalgo.in/) [PreviousCommunity Supportchevron-left](https://docs.openalgo.in/community-support) [NextNew Featureschevron-right](https://docs.openalgo.in/new-features) Last updated 14 minutes ago sun-brightdesktopmoon sun-brightdesktopmoon --- # New Features | Documentation Open Algo is constantly evolving to meet the needs of modern traders by introducing innovative features that enhance functionality, security, and user experience. Each new addition focuses on improving performance, streamlining workflows, and enabling more efficient trading strategies. From cutting-edge tools to seamless integrations, these updates are tailored to empower both traders and developers. The platform's new features include advanced trading tools, enhanced API capabilities, and robust security measures. These updates ensure Open Algo remains adaptable to industry trends, supporting multiple brokers, diverse trading styles, and custom workflows. Whether you're a scalper, a positional trader, or a developer building on top of Open Algo, the latest features provide the flexibility and reliability you need. [PreviousOpenAlgo GPTchevron-left](https://docs.openalgo.in/openalgo-gpt) [NextFast Scalperchevron-right](https://docs.openalgo.in/new-features/fast-scalper) Last updated 3 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Traffic/Latency Monitor | Documentation OpenAlgo introduces powerful tools for performance monitoring: 1\. Latency Monitor (/latency): • Real-Time Tracking: Monitors Round-Trip Time (RTT) for order execution. • Broker Comparison: Evaluate broker performance and latency breakdown. • Benefits: • Optimize execution strategies. • Detect and troubleshoot delays. • Compare brokers for better reliability. 2\. Traffic Monitor (/traffic): • API Analytics: Track API usage, errors, and response times. • Endpoint Insights: Identify heavily-used endpoints and optimize requests. • Benefits: • Monitor system health. • Resolve performance bottlenecks. • Plan scaling based on actual usage. These tools provide essential visibility to optimize system performance, ensuring reliable and efficient trading operations. [PreviousPNL Trackerchevron-left](https://docs.openalgo.in/new-features/pnl-tracker) [NextChartink Integrationchevron-right](https://docs.openalgo.in/new-features/chartink-integration) Last updated 2 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Python Strategy Hosting | Documentation * * * [hashtag](https://docs.openalgo.in/new-features/python-strategy-hosting#hosting-python-strategies-in-openalgo) Hosting Python Strategies in OpenAlgo --------------------------------------------------------------------------------------------------------------------------------------------------------- OpenAlgo allows you to host and run multiple Python trading strategies as isolated subprocesses. Each strategy operates with its own memory and log files, ensuring that one script does not interfere with another. ### [hashtag](https://docs.openalgo.in/new-features/python-strategy-hosting#id-1.-accessing-the-python-strategy-manager) 1\. Accessing the Python Strategy Manager To begin, log into your OpenAlgo dashboard: * Click on your **Profile** icon in the top right corner. * Select **Python Strategies** from the dropdown menu. * This dashboard provides an overview of your total, running, and scheduled strategies. ### [hashtag](https://docs.openalgo.in/new-features/python-strategy-hosting#id-2.-adding-a-new-strategy) 2\. Adding a New Strategy Click the **Add Strategy** button to open the configuration interface. #### [hashtag](https://docs.openalgo.in/new-features/python-strategy-hosting#uploading-the-script) Uploading the Script * **Strategy Name:** Enter a unique descriptive name for your strategy. * **Python Script:** Upload your `.py` file. OpenAlgo supports standard Python libraries and the OpenAlgo SDK. #### [hashtag](https://docs.openalgo.in/new-features/python-strategy-hosting#configuration-and-scheduling) Configuration & Scheduling * **Exchange:** Select the target exchange (e.g., NSE Equity, MCX Commodity, Crypto). OpenAlgo is holiday-aware and will only run the strategy during valid market hours for the selected exchange. * **Schedule:** Define the **Start Time** and **Stop Time**. You can also select specific days of the week (Monday–Sunday) to enable or disable the strategy. ### [hashtag](https://docs.openalgo.in/new-features/python-strategy-hosting#id-3.-monitoring-and-management) 3\. Monitoring & Management Once a strategy is added, it will appear on your Python Strategies page. * **Start/Stop:** Use the manual controls to trigger or halt the script execution. * **View Logs:** Click "View Logs" to see real-time output. This section tracks data fetching, signal generation, and order execution. You can copy or download these logs for debugging. * **Edit Code:** The built-in code editor allows for quick modifications directly within the browser, though it is recommended to test major changes locally first. ### [hashtag](https://docs.openalgo.in/new-features/python-strategy-hosting#id-4.-execution-modes) 4\. Execution Modes OpenAlgo features a toggle to prevent accidental trades during development: * **Analyzer Mode:** Use this for testing purposes. It allows the script to run and generate logs without sending real orders to the broker. * **Live Mode:** Once your strategy is verified, switch to Live Mode to enable actual order placement. ### [hashtag](https://docs.openalgo.in/new-features/python-strategy-hosting#id-5.-technical-environment-variables) 5\. Technical Environment Variables When your script runs within OpenAlgo, several environment variables are automatically injected. You should use these instead of hardcoding sensitive data: Variable Description `OPENALGO_API_KEY` Your decrypted API key for the platform. `STRATEGY_ID` A unique identifier for the specific strategy instance. `OPENALGO_HOST` The internal host URL for API requests. `OPENALGO_WS_URL` The WebSocket URL for real-time data streaming. ### [hashtag](https://docs.openalgo.in/new-features/python-strategy-hosting#id-6.-verifying-orders) 6\. Verifying Orders After a trade is triggered by your Python strategy, you can verify it in two places: 1. **Strategy Logs:** Shows the logic and parameters that triggered the trade. 2. **Order Book:** Shows the status (Complete, Rejected, etc.) and details (Price, Quantity, Product Type) of the order sent to the broker. * * * #### [hashtag](https://docs.openalgo.in/new-features/python-strategy-hosting#best-practices) Best Practices * Always test new strategies in **Analyzer Mode** for at least one full trading session. * Use the **Python Strategy Guide** link within the app for updated code snippets and recommended patterns. * Ensure your OpenAlgo instance has a stable internet connection if running on a local machine to prevent WebSocket disconnections. [PreviousFast Scalperchevron-left](https://docs.openalgo.in/new-features/fast-scalper) [NextFlow - Visual Strategy Builderchevron-right](https://docs.openalgo.in/new-features/flow-visual-strategy-builder) Last updated 8 days ago * [Hosting Python Strategies in OpenAlgo](https://docs.openalgo.in/new-features/python-strategy-hosting#hosting-python-strategies-in-openalgo) * [1\. Accessing the Python Strategy Manager](https://docs.openalgo.in/new-features/python-strategy-hosting#id-1.-accessing-the-python-strategy-manager) * [2\. Adding a New Strategy](https://docs.openalgo.in/new-features/python-strategy-hosting#id-2.-adding-a-new-strategy) * [3\. Monitoring & Management](https://docs.openalgo.in/new-features/python-strategy-hosting#id-3.-monitoring-and-management) * [4\. Execution Modes](https://docs.openalgo.in/new-features/python-strategy-hosting#id-4.-execution-modes) * [5\. Technical Environment Variables](https://docs.openalgo.in/new-features/python-strategy-hosting#id-5.-technical-environment-variables) * [6\. Verifying Orders](https://docs.openalgo.in/new-features/python-strategy-hosting#id-6.-verifying-orders) sun-brightdesktopmoon sun-brightdesktopmoon --- # Mini FOSS Universe | Documentation The **OpenAlgo Mini FOSS Universe** is a curated collection of open-source projects, SDKs, libraries, and integrations that extend the OpenAlgo ecosystem across languages, platforms, and workflows. Whether you’re building trading strategies, data pipelines, dashboards, or AI-driven systems, OpenAlgo provides open-source tools that integrate seamlessly into every modern trading workflow. This ecosystem is designed to be: * **Modular** — use only what you need * **Extensible** — customize and build on top of existing components * **Language-agnostic** — work in the stack you’re most comfortable with * **Production-ready** — stable APIs with long-term support All projects in the Mini FOSS Universe are community-driven and built with real-world trading and automation use cases in mind. * * * ### [hashtag](https://docs.openalgo.in/mini-foss-universe#core-project) Core Project Component Repository 🧠 **OpenAlgo Core** [https://github.com/marketcalls/openalgoarrow-up-right](https://github.com/marketcalls/openalgo) **OpenAlgo Core** is the central heartbeat of the ecosystem — powering the API service, authentication, routing, and platform logic. All SDKs, libraries, and integrations interact with the API endpoints exposed by OpenAlgo Core. * * * ### [hashtag](https://docs.openalgo.in/mini-foss-universe#libraries-and-sdks) Libraries and SDKs OpenAlgo provides official SDKs and libraries to help developers interact with the OpenAlgo API without making raw HTTP calls. These packages handle authentication, request formatting, and response parsing, allowing you to focus on strategy and logic. #### [hashtag](https://docs.openalgo.in/mini-foss-universe#api-version) API Version The current stable version of the OpenAlgo API is **v1**. * All SDKs and integrations listed below are built against **API v1** * v1 is stable, backward-compatible, and recommended for production use * Future versions will be introduced without breaking existing v1 integrations * * * ### [hashtag](https://docs.openalgo.in/mini-foss-universe#sdks) SDKs SDKs are officially supported client packages intended for application development and system-level integrations. Language / Platform Repository Python [https://github.com/marketcalls/openalgo-python-libraryarrow-up-right](https://github.com/marketcalls/openalgo-python-library) Node.js [https://github.com/marketcalls/openalgo-nodearrow-up-right](https://github.com/marketcalls/openalgo-node) Java [https://github.com/marketcalls/openalgo-javaarrow-up-right](https://github.com/marketcalls/openalgo-java) RUST [https://github.com/marketcalls/openalgo-rustarrow-up-right](https://github.com/marketcalls/openalgo-rust) .NET / C# [https://github.com/marketcalls/openalgo.NETarrow-up-right](https://github.com/marketcalls/openalgo.NET) Go [https://github.com/marketcalls/openalgo-goarrow-up-right](https://github.com/marketcalls/openalgo-go) * * * ### [hashtag](https://docs.openalgo.in/mini-foss-universe#libraries-and-platform-integrations) Libraries and Platform Integrations These libraries and tools extend OpenAlgo support to popular trading platforms, analysis tools, and user interfaces. Platform / Tool Repository 📊 **Excel Add-in** [https://github.com/marketcalls/OpenAlgo-Excelarrow-up-right](https://github.com/marketcalls/OpenAlgo-Excel) 📉 **Amibroker Plugin** [https://github.com/marketcalls/OpenAlgoPluginarrow-up-right](https://github.com/marketcalls/OpenAlgoPlugin) 🔁 **Backtrader Integration** [https://github.com/p2c2e/openalgo-backtraderarrow-up-right](https://github.com/p2c2e/openalgo-backtrader) ⚡ **PineTS** [https://github.com/marketcalls/openalgo-pinetsarrow-up-right](https://github.com/marketcalls/openalgo-pinets) 🪞 **AlgoMirror** [https://github.com/marketcalls/algomirrorarrow-up-right](https://github.com/marketcalls/algomirror) ⚡ OpenAlgo chart [https://github.com/crypt0inf0/openalgo-chartarrow-up-right](https://github.com/crypt0inf0/openalgo-chart) 🌐 OpenAlgo Helm Chart [https://github.com/p2c2e/openalgo\_helmarrow-up-right](https://github.com/p2c2e/openalgo_helm) 🤖 **MCP / AI Agents** [https://github.com/marketcalls/openalgo-mcparrow-up-right](https://github.com/marketcalls/openalgo-mcp) 📱 **OpenAlgo Mobile** [https://github.com/marketcalls/openalgo-mobilearrow-up-right](https://github.com/marketcalls/openalgo-mobile) 🌐 **Web Portal** [https://github.com/marketcalls/openalgo-webpagearrow-up-right](https://github.com/marketcalls/openalgo-webpage) 🧩 **Chrome Plugin** [https://github.com/marketcalls/openalgo-chromearrow-up-right](https://github.com/marketcalls/openalgo-chrome) 🚄 **Fast Scalper (Rust + Tauri)** [https://github.com/marketcalls/fastscalper-tauriarrow-up-right](https://github.com/marketcalls/fastscalper-tauri) * * * ### [hashtag](https://docs.openalgo.in/mini-foss-universe#documentation-and-examples) Documentation and Examples Each SDK and integration has dedicated documentation that includes installation steps, configuration guidance, and working examples: * Python — [https://docs.openalgo.in/trading-platform/pythonarrow-up-right](https://docs.openalgo.in/trading-platform/python) * Node.js — [https://docs.openalgo.in/trading-platform/nodejsarrow-up-right](https://docs.openalgo.in/trading-platform/nodejs) * Java — [https://docs.openalgo.in/trading-platform/javaarrow-up-right](https://docs.openalgo.in/trading-platform/java) * .NET — [https://docs.openalgo.in/trading-platform/.netarrow-up-right](https://docs.openalgo.in/trading-platform/.net) * Go — [https://docs.openalgo.in/trading-platform/goarrow-up-right](https://docs.openalgo.in/trading-platform/go) * RUST — https://docs.openalgo.in/trading-platform/rust * Excel — [https://docs.openalgo.in/trading-platform/excelarrow-up-right](https://docs.openalgo.in/trading-platform/excel) * Amibroker Plugin — [https://docs.openalgo.in/trading-platform/amibroker/amibroker-pluginarrow-up-right](https://docs.openalgo.in/trading-platform/amibroker/amibroker-plugin) * MCP / AI Agents — [https://docs.openalgo.in/mcparrow-up-right](https://docs.openalgo.in/mcp) * * * ### [hashtag](https://docs.openalgo.in/mini-foss-universe#philosophy) Philosophy The Mini FOSS Universe reflects OpenAlgo’s core philosophy: **open standards, transparent design, and tools that adapt to how traders actually work**. You can use these projects independently, combine them into larger systems, or fork and extend them to suit your own trading infrastructure. [PreviousOpenAlgo Architecturechevron-left](https://docs.openalgo.in/openalgo-architecture) [NextCommunity Supportchevron-right](https://docs.openalgo.in/community-support) Last updated 3 months ago * [Core Project](https://docs.openalgo.in/mini-foss-universe#core-project) * [Libraries and SDKs](https://docs.openalgo.in/mini-foss-universe#libraries-and-sdks) * [SDKs](https://docs.openalgo.in/mini-foss-universe#sdks) * [Libraries and Platform Integrations](https://docs.openalgo.in/mini-foss-universe#libraries-and-platform-integrations) * [Documentation and Examples](https://docs.openalgo.in/mini-foss-universe#documentation-and-examples) * [Philosophy](https://docs.openalgo.in/mini-foss-universe#philosophy) sun-brightdesktopmoon sun-brightdesktopmoon --- # Historify | Documentation * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-1.-overview) 1\. Overview **Historify** is a built-in feature in OpenAlgo (Version 2) that transforms the platform into a **full-stack historical market data management system**. It allows you to: * Download historical data directly from supported brokers * Store the data locally inside OpenAlgo * Validate and visualize stored data * Export and import datasets * Schedule automatic downloads * Use the stored data as a source for backtesting engines In short, Historify lets you **own, manage, and reuse your historical market data** efficiently. * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-2.-why-historify-exists) 2\. Why Historify Exists Most traders and quants face these common challenges: * Repeatedly downloading the same historical data * Slow backtesting due to API latency * No centralized place to store and organize market data * Dependency on third-party vendors Historify solves these problems by acting as: > A **local historical data warehouse** + **API layer** + **backtesting data source** * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-3.-system-architecture-simplified) 3\. System Architecture (Simplified) OpenAlgo internally uses two databases: #### [hashtag](https://docs.openalgo.in/new-features/historify#id-3.1-sqlite-database) 3.1 SQLite Database Stores: * Master contracts * Orders * Logs * Configuration and metadata #### [hashtag](https://docs.openalgo.in/new-features/historify#id-3.2-duckdb-database-high-performance-analytics-db) 3.2 DuckDB Database (High-Performance Analytics DB) Stores: * Daily historical market data * 1-minute historical market data DuckDB is optimized for analytical workloads and is extremely fast, making it ideal for: * Large dataset queries * Backtesting * Timeframe aggregation All historical data stored in DuckDB is exposed through the **Historify API**. * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-4.-accessing-historify) 4\. Accessing Historify Path inside OpenAlgo: **Profile → Historify** You will see a complete historical data management interface with options for: * Watchlists * Downloads * Jobs * Charts * Scheduler * Export * Import * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-5.-supported-base-data-types) 5\. Supported Base Data Types Currently supported base intervals: * **Daily** * **1 Minute** All higher timeframes (5m, 15m, 1h, etc.) are generated by aggregating the 1-minute data. * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-6.-using-watchlists) 6\. Using Watchlists Watchlists act as symbol containers for bulk operations. #### [hashtag](https://docs.openalgo.in/new-features/historify#example-flow) Example Flow: 1. Create a watchlist 2. Add symbols (e.g., SBIN, INFY, TCS) 3. Use this watchlist for downloads, scheduling, or exports Once added, symbols automatically appear in the selected watchlist. * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-7.-downloading-historical-data) 7\. Downloading Historical Data #### [hashtag](https://docs.openalgo.in/new-features/historify#steps) Steps 1. Select a watchlist 2. Choose: * Data type: Daily or 1-Minute * Lookback period (e.g., 1 year, 3 months) 3. Start download #### [hashtag](https://docs.openalgo.in/new-features/historify#what-happens-internally) What Happens Internally * OpenAlgo fetches data from broker APIs * Data is stored inside DuckDB * A background job is created * Progress and status are shown in the Jobs section After completion, data is permanently available locally. * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-8.-validating-data-using-charts) 8\. Validating Data Using Charts Historify includes an integrated charting view (TradingView Lightweight Charts). You can: * Select a symbol * Choose timeframe * Visually confirm price data This step helps verify: * Missing candles * Abnormal spikes * Data alignment Note: Charts display **stored historical data**, not real-time prices. * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-9.-timeframe-generation) 9\. Timeframe Generation If 1-minute data exists, Historify can create: * 3-minute * 5-minute * 7-minute * 15-minute * Custom intervals These are dynamically aggregated from 1-minute data—no separate downloads needed. * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-10.-scheduler-automatic-downloads) 10\. Scheduler (Automatic Downloads) The Scheduler allows fully automated data collection. #### [hashtag](https://docs.openalgo.in/new-features/historify#common-use-case) Common Use Case Download new data automatically after market close every day. #### [hashtag](https://docs.openalgo.in/new-features/historify#scheduler-options) Scheduler Options * Type: Daily or Interval-based * Time: Example 18:00 * Lookback Days: Usually set to 1 (incremental update) #### [hashtag](https://docs.openalgo.in/new-features/historify#important-notes) Important Notes * OpenAlgo must remain logged in * Schedules should be created before 3:00 AM (token validity window) * Multiple schedules can be created Result: Data refresh happens without human intervention. * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-11.-exporting-data) 11\. Exporting Data Stored historical data can be exported into multiple formats. #### [hashtag](https://docs.openalgo.in/new-features/historify#supported-exports) Supported Exports * Daily / 1-minute / aggregated timeframes * CSV * ZIP * Parquet #### [hashtag](https://docs.openalgo.in/new-features/historify#use-cases) Use Cases * Import into Amibroker * Import into NinjaTrader * External research * Machine learning pipelines * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-12.-importing-external-data) 12\. Importing External Data You can import your own datasets into Historify. #### [hashtag](https://docs.openalgo.in/new-features/historify#current-capabilities) Current Capabilities * One symbol at a time * Daily or 1-minute base interval #### [hashtag](https://docs.openalgo.in/new-features/historify#example-use-case) Example Use Case Import 10–15 years of index futures data from another provider, then: * Store inside DuckDB * Use like native Historify data * Backtest instantly * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-13.-historify-as-an-api-data-source) 13\. Historify as an API Data Source Historify exposes all stored data through the same historical data API used by OpenAlgo. #### [hashtag](https://docs.openalgo.in/new-features/historify#two-possible-sources) Two Possible Sources * **API** → Fetch directly from broker * **DB** → Fetch from DuckDB (Historify) Switching source to **DB** enables ultra-fast retrieval. #### [hashtag](https://docs.openalgo.in/new-features/historify#benefits) Benefits * Millisecond-level response times * No broker rate limits * Perfect for large backtests * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-14.-backtesting-workflow-using-historify) 14\. Backtesting Workflow Using Historify High-level flow: 1. Download historical data into Historify 2. Verify via charts 3. Set data source to DB 4. Connect your backtesting engine 5. Run simulations Because both: * Data retrieval (DuckDB) * Backtesting engine are optimized, overall performance becomes significantly faster. * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-15.-performance-advantages) 15\. Performance Advantages * DuckDB optimized for analytics * Columnar storage * Fast aggregations * Low memory overhead Typical large historical queries return in **tens of milliseconds**. * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-16.-typical-use-cases) 16\. Typical Use Cases * Strategy research * Quant backtesting * Market structure analysis * Data warehousing * Indicator optimization * Academic research * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-17.-key-benefits-summary) 17\. Key Benefits Summary * Local ownership of historical data * No repeated downloads * Broker-independent after storage * Fast backtesting * Centralized data management * Import, export, schedule, visualize * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-18.-limitations-current) 18\. Limitations (Current) * Base intervals limited to Daily and 1-Minute * One-symbol-at-a-time import * Broker integrations still expanding * External data vendors planned for future * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-19.-future-direction) 19\. Future Direction Planned improvements include: * Additional broker integrations * External data vendor support * Bulk import * More export formats * Advanced validation tools * * * ### [hashtag](https://docs.openalgo.in/new-features/historify#id-20.-final-thoughts) 20\. Final Thoughts Historify turns OpenAlgo into more than a trading bridge—it becomes a **personal market data platform**. You can: * Build your own historical database * Maintain it automatically * Validate it visually * Use it across strategies and backtesting engines This foundation enables faster research, better strategies, and complete control over your market data. [PreviousFlow - Visual Strategy Builderchevron-left](https://docs.openalgo.in/new-features/flow-visual-strategy-builder) [NextAPI Analyzerchevron-right](https://docs.openalgo.in/new-features/api-analyzer) Last updated 2 months ago * [1\. Overview](https://docs.openalgo.in/new-features/historify#id-1.-overview) * [2\. Why Historify Exists](https://docs.openalgo.in/new-features/historify#id-2.-why-historify-exists) * [3\. System Architecture (Simplified)](https://docs.openalgo.in/new-features/historify#id-3.-system-architecture-simplified) * [4\. Accessing Historify](https://docs.openalgo.in/new-features/historify#id-4.-accessing-historify) * [5\. Supported Base Data Types](https://docs.openalgo.in/new-features/historify#id-5.-supported-base-data-types) * [6\. Using Watchlists](https://docs.openalgo.in/new-features/historify#id-6.-using-watchlists) * [7\. Downloading Historical Data](https://docs.openalgo.in/new-features/historify#id-7.-downloading-historical-data) * [8\. Validating Data Using Charts](https://docs.openalgo.in/new-features/historify#id-8.-validating-data-using-charts) * [9\. Timeframe Generation](https://docs.openalgo.in/new-features/historify#id-9.-timeframe-generation) * [10\. Scheduler (Automatic Downloads)](https://docs.openalgo.in/new-features/historify#id-10.-scheduler-automatic-downloads) * [11\. Exporting Data](https://docs.openalgo.in/new-features/historify#id-11.-exporting-data) * [12\. Importing External Data](https://docs.openalgo.in/new-features/historify#id-12.-importing-external-data) * [13\. Historify as an API Data Source](https://docs.openalgo.in/new-features/historify#id-13.-historify-as-an-api-data-source) * [14\. Backtesting Workflow Using Historify](https://docs.openalgo.in/new-features/historify#id-14.-backtesting-workflow-using-historify) * [15\. Performance Advantages](https://docs.openalgo.in/new-features/historify#id-15.-performance-advantages) * [16\. Typical Use Cases](https://docs.openalgo.in/new-features/historify#id-16.-typical-use-cases) * [17\. Key Benefits Summary](https://docs.openalgo.in/new-features/historify#id-17.-key-benefits-summary) * [18\. Limitations (Current)](https://docs.openalgo.in/new-features/historify#id-18.-limitations-current) * [19\. Future Direction](https://docs.openalgo.in/new-features/historify#id-19.-future-direction) * [20\. Final Thoughts](https://docs.openalgo.in/new-features/historify#id-20.-final-thoughts) sun-brightdesktopmoon sun-brightdesktopmoon --- # Action Center | Documentation ### [hashtag](https://docs.openalgo.in/new-features/action-center#what-is-action-center) What is Action Center? **Action Center** is like a "shopping cart approval system" for your trading orders. Instead of orders executing immediately, they wait in a queue for you to manually review and approve them before they go to your broker. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F4mM0TTs4BBPwTTj9mFaJ%252Fimage.png%3Falt%3Dmedia%26token%3Decc05812-d383-4a19-a1b2-bbde9ceb75dc&width=768&dpr=3&quality=100&sign=fbbcde0e&sv=2) Think of it as a **safety checkpoint** between your trading strategy and your real money. ### [hashtag](https://docs.openalgo.in/new-features/action-center#why-would-you-use-it) Why Would You Use It? #### [hashtag](https://docs.openalgo.in/new-features/action-center#real-world-examples) Real-World Examples **Example 1: Testing a New Strategy** * You wrote a Python trading bot that generates buy/sell signals * You're not 100% confident it works correctly yet * Instead of letting it trade automatically, you enable Action Center * Now every order waits for your approval - you can catch mistakes before they cost you money **Example 2: High-Risk Trades** * Your strategy generates a signal to buy 1000 shares of a volatile stock * You want to review the order before it executes * Action Center lets you verify quantity, price, and timing before confirming **Example 3: Learning and Monitoring** * You want to understand what signals your strategy is generating * Action Center shows you every order before execution * Great for learning how your algorithm behaves in real market conditions ### [hashtag](https://docs.openalgo.in/new-features/action-center#how-it-works) How It Works #### [hashtag](https://docs.openalgo.in/new-features/action-center#two-modes) Two Modes **1\. Auto Mode (Default) - Fully Automated** Orders execute immediately without any manual intervention. **2\. Semi-Auto Mode - Manual Approval Required** Orders wait in Action Center for you to review and approve. ### [hashtag](https://docs.openalgo.in/new-features/action-center#step-by-step-setup) Step-by-Step Setup #### [hashtag](https://docs.openalgo.in/new-features/action-center#step-1-enable-semi-auto-mode) Step 1: Enable Semi-Auto Mode 1. Go to **Profile** → **API Key** page 2. Find **"Order Execution Mode"** section 3. Turn ON the toggle switch (it will turn orange) 4. Status changes from "Auto Mode" to "Semi-Auto Mode" #### [hashtag](https://docs.openalgo.in/new-features/action-center#step-2-send-orders-from-your-strategy) Step 2: Send Orders from Your Strategy Your Python code stays exactly the same: But now the response will be different: #### [hashtag](https://docs.openalgo.in/new-features/action-center#step-3-review-orders-in-action-center) Step 3: Review Orders in Action Center 1. Click **"Action Center"** in the main menu 2. You'll see a badge showing how many orders are pending 3. Click on "Pending" tab to see orders waiting for approval #### [hashtag](https://docs.openalgo.in/new-features/action-center#step-4-approve-or-reject) Step 4: Approve or Reject For each order, you can: * **Approve**: Click green "Approve" button → Order sends to broker * **Reject**: Click red "Reject" button → Order cancelled, never sent to broker ### [hashtag](https://docs.openalgo.in/new-features/action-center#what-you-can-see-in-action-center) What You Can See in Action Center For each pending order: * **Symbol** (e.g., "SBIN") * **Action** (BUY or SELL) * **Quantity** (e.g., 10 shares) * **Price** (e.g., ₹625.50) * **Order Type** (MARKET, LIMIT, etc.) * **When it was created** (e.g., "2 minutes ago") * **Current status** (Pending, Approved, Rejected) ### [hashtag](https://docs.openalgo.in/new-features/action-center#tabs-in-action-center) Tabs in Action Center 1. **Pending** - Orders waiting for your action 2. **Approved** - Orders you approved and sent to broker 3. **Rejected** - Orders you declined 4. **All Orders** - Complete history ### [hashtag](https://docs.openalgo.in/new-features/action-center#special-features) Special Features #### [hashtag](https://docs.openalgo.in/new-features/action-center#auto-refresh) Auto-Refresh The "Pending" tab refreshes every 30 seconds automatically, so you always see the latest orders. #### [hashtag](https://docs.openalgo.in/new-features/action-center#statistics-dashboard) Statistics Dashboard At the top, you see: * Pending Approval: 5 orders * Buy Orders: 3 * Sell Orders: 2 * Approved: 15 * Rejected: 2 #### [hashtag](https://docs.openalgo.in/new-features/action-center#audit-trail) Audit Trail Every action is logged: * Who approved/rejected * When it was approved/rejected * Rejection reason (if you provide one) ### [hashtag](https://docs.openalgo.in/new-features/action-center#common-questions) Common Questions #### [hashtag](https://docs.openalgo.in/new-features/action-center#q-do-i-need-to-change-my-trading-code) Q: Do I need to change my trading code? **A:** No! Your API calls stay exactly the same. Just toggle the mode in settings. #### [hashtag](https://docs.openalgo.in/new-features/action-center#q-what-happens-if-i-dont-approve-reject-orders) Q: What happens if I don't approve/reject orders? **A:** They stay in the Pending queue indefinitely. Your strategy will keep generating signals, but they won't execute until you approve. #### [hashtag](https://docs.openalgo.in/new-features/action-center#q-can-i-switch-back-to-auto-mode-anytime) Q: Can I switch back to Auto Mode anytime? **A:** Yes! Just toggle the switch OFF in API Key settings. New orders will execute immediately again. #### [hashtag](https://docs.openalgo.in/new-features/action-center#q-does-this-work-with-all-order-types) Q: Does this work with all order types? **A:** Yes! Works with: * Regular orders (`placeorder`) * Smart orders (`placesmartorder`) * Basket orders (`basketorder`) * Split orders (`splitorder`) * Options orders (`optionsorder`) #### [hashtag](https://docs.openalgo.in/new-features/action-center#q-can-i-see-which-orders-my-strategy-generated-vs-which-i-approved) Q: Can I see which orders my strategy generated vs which I approved? **A:** Yes! Each order shows: * Created time (when strategy sent it) * Approved time (when you clicked Approve) * Broker order ID (after execution) ### [hashtag](https://docs.openalgo.in/new-features/action-center#quick-comparison) Quick Comparison Feature Auto Mode Semi-Auto Mode **Order Execution** Immediate After approval **Your Involvement** None Review each order **Safety** High risk (no checks) Low risk (manual review) **Speed** Very fast Slower (manual) **Best For** Proven strategies Testing, learning ### [hashtag](https://docs.openalgo.in/new-features/action-center#when-to-use-which-mode) When to Use Which Mode #### [hashtag](https://docs.openalgo.in/new-features/action-center#use-auto-mode-when) Use Auto Mode When: * Your strategy is proven and tested * You need high-frequency trading * You trust the strategy 100% * Speed is critical #### [hashtag](https://docs.openalgo.in/new-features/action-center#use-semi-auto-mode-when) Use Semi-Auto Mode When: * Testing a new strategy * Learning algorithmic trading * High-risk trades need verification * You want full control over every order ### [hashtag](https://docs.openalgo.in/new-features/action-center#example-workflow) Example Workflow **Scenario**: You're testing a new momentum strategy 1. **Morning 9:00 AM** * Enable Semi-Auto mode in settings * Start your Python trading bot 2. **9:30 AM** - Market opens * Your bot generates BUY signal for RELIANCE * Order appears in Action Center "Pending" tab 3. **9:31 AM** - You review * Symbol: RELIANCE ✅ (Correct) * Quantity: 10 ✅ (Looks good) * Price: ₹2,500 ✅ (Reasonable) * Click "Approve" 4. **9:31 AM** - Order executes * Sent to broker * Shows "Approved" status * Broker order ID: 240612000123456 5. **10:00 AM** - Another signal * Your bot wants to SELL 100 shares of INFY * Wait... 100 shares seems too much! * Click "Reject" with reason: "Quantity too large" 6. **End of Day** * Review statistics: 10 approved, 2 rejected * Adjust your strategy code to fix the quantity issue ### [hashtag](https://docs.openalgo.in/new-features/action-center#tips-for-success) Tips for Success 1. **Start with Semi-Auto** when testing new strategies 2. **Switch to Auto** only when you're confident 3. **Monitor the Pending tab** regularly (it auto-refreshes) 4. **Use rejection reasons** to track why you rejected orders 5. **Review history** in "All Orders" tab to learn from patterns ### [hashtag](https://docs.openalgo.in/new-features/action-center#undefined) * * * **Remember**: Action Center gives you control. Use it wisely to protect your capital while testing new strategies! [PreviousChartink Integrationchevron-left](https://docs.openalgo.in/new-features/chartink-integration) [NextResponsibilitieschevron-right](https://docs.openalgo.in/responsibilities) Last updated 5 months ago * [What is Action Center?](https://docs.openalgo.in/new-features/action-center#what-is-action-center) * [Why Would You Use It?](https://docs.openalgo.in/new-features/action-center#why-would-you-use-it) * [How It Works](https://docs.openalgo.in/new-features/action-center#how-it-works) * [Step-by-Step Setup](https://docs.openalgo.in/new-features/action-center#step-by-step-setup) * [What You Can See in Action Center](https://docs.openalgo.in/new-features/action-center#what-you-can-see-in-action-center) * [Tabs in Action Center](https://docs.openalgo.in/new-features/action-center#tabs-in-action-center) * [Special Features](https://docs.openalgo.in/new-features/action-center#special-features) * [Common Questions](https://docs.openalgo.in/new-features/action-center#common-questions) * [Quick Comparison](https://docs.openalgo.in/new-features/action-center#quick-comparison) * [When to Use Which Mode](https://docs.openalgo.in/new-features/action-center#when-to-use-which-mode) * [Example Workflow](https://docs.openalgo.in/new-features/action-center#example-workflow) * [Tips for Success](https://docs.openalgo.in/new-features/action-center#tips-for-success) * [](https://docs.openalgo.in/new-features/action-center#undefined) sun-brightdesktopmoon Copy Trading Signal → OpenAlgo → Broker → Order Executed (instant) Copy Trading Signal → OpenAlgo → Action Center (WAIT) → You Approve → Broker → Order Executed (paused here) ↓ You Reject → Order Cancelled Copy api.placeorder({ "apikey": "YOUR_API_KEY", "symbol": "SBIN", "action": "BUY", "quantity": "10" }) Copy { "status": "success", "message": "Order queued for approval in Action Center", "mode": "semi_auto" } sun-brightdesktopmoon --- # PNL Tracker | Documentation ### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#overview) Overview The PnL Tracker is a real-time profit and loss monitoring feature in OpenAlgo that provides visual insights into intraday trading performance. It displays MTM (Mark-to-Market) PnL curves and drawdown analysis using interactive charts powered by TradingView Lightweight Charts. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FIURnWq0uDKtmsY6zSiOQ%252FPNL.jpeg%3Falt%3Dmedia%26token%3Dc901efc3-f2da-4581-a60a-66e809a254f3&width=768&dpr=3&quality=100&sign=7cae426f&sv=2) [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#pnl-tracker-documentation) PnL Tracker Documentation --------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#overview-1) Overview The PnL Tracker is a real-time profit and loss monitoring feature in OpenAlgo that provides visual insights into intraday trading performance. It displays MTM (Mark-to-Market) PnL curves and drawdown analysis using interactive charts powered by TradingView Lightweight Charts. ### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#features) Features #### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#key-metrics) Key Metrics * **Current MTM**: Real-time mark-to-market profit/loss * **Max MTM**: Peak profit achieved during the trading day with timestamp * **Min MTM**: Maximum loss during the trading day with timestamp * **Max Drawdown**: Largest peak-to-trough decline in portfolio value #### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#visualization) Visualization * Interactive intraday PnL curve from 9:00 AM IST to current time * Drawdown visualization showing portfolio decline from peaks * IST timezone support with accurate time display * Theme-aware charts (Light/Dark/Garden themes) ### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#technical-architecture) Technical Architecture #### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#components) Components **1\. Blueprint Route (**`**/blueprints/pnltracker.py**`**)** * **Endpoint**: `/pnltracker` - Main page * **API Endpoint**: `/pnltracker/api/pnl` - Data API (POST) * **Session Management**: Uses `check_session_validity` decorator * **Authentication**: API key based authentication via `get_api_key_for_tradingview()` **2\. Frontend (**`**/templates/pnltracker.html**`**)** * TradingView Lightweight Charts v5.0.8 for visualization * DaisyUI components for UI * Manual refresh control (no auto-refresh) * Responsive design with mobile support #### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#data-flow) Data Flow ### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#pnl-calculation-logic) PnL Calculation Logic #### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#for-executed-trades) For Executed Trades #### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#for-open-positions-no-trades) For Open Positions (No Trades) #### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#portfolio-mtm) Portfolio MTM * Individual symbol PnLs are combined into portfolio PnL * Time-synchronized data using pandas DataFrame joins * Forward-fill missing data points for continuity ### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#timestamp-handling) Timestamp Handling The system robustly handles different timestamp formats from various brokers: 1. **Unix timestamp (seconds)**: Most common format 2. **Unix timestamp (milliseconds)**: Alternative format 3. **String datetime**: ISO format strings 4. **Timezone handling**: Automatic conversion to IST ### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#error-handling) Error Handling #### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#graceful-degradation) Graceful Degradation * **Missing historical data**: Shows flat PnL line at current value * **Invalid timestamps**: Falls back to default time range * **String numeric values**: Automatically converts to float * **Empty tradebook**: Uses position data if available * **No data**: Returns zero PnL metrics #### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#logging) Logging * Comprehensive logging at INFO, WARNING, and ERROR levels * Detailed error messages for debugging * Performance metrics logging ### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#time-filtering) Time Filtering * **Start Time**: 9:00 AM IST (market open) * **End Time**: Current time * **Frequency**: 1-minute intervals * **Timezone**: Asia/Kolkata (IST) ### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#performance-optimization) Performance Optimization #### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#manual-refresh-only) Manual Refresh Only * No automatic refresh to reduce server load * User-initiated refresh via button click * Prevents unnecessary API calls #### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#data-batching) Data Batching * Single API call fetches all required data * Parallel processing of multiple symbols * Efficient pandas operations for calculations #### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#caching-strategy) Caching Strategy * Session-based authentication caching * Reuses auth tokens within session * Minimizes database queries ### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#broker-compatibility) Broker Compatibility #### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#supported-features-by-broker) Supported Features by Broker * All brokers supporting tradebook API * All brokers supporting 1-minute historical data * Position tracking across all integrated brokers #### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#special-cases) Special Cases * **MCX/Commodities**: Special quantity calculation when trade\_value equals average\_price (1 lot) * **Different timestamp formats**: Automatic detection and conversion * **Missing data fields**: Graceful fallback to defaults ### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#usage) Usage #### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#accessing-pnl-tracker) Accessing PnL Tracker 1. Login to OpenAlgo 2. Click profile menu in navbar 3. Select "PnL Tracker" (below "Logs") 4. View real-time PnL metrics and charts 5. Click "Refresh" button to update data #### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#understanding-the-display) Understanding the Display * **Green values**: Profit positions * **Red values**: Loss positions * **Purple line**: MTM PnL curve * **Pink area**: Drawdown from peak ### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#troubleshooting) Troubleshooting #### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#common-issues) Common Issues 1. **"No data in TradeBook"** * Normal when no trades executed * Position PnL will still be displayed if positions exist 2. **Timestamps showing wrong time** * Automatic IST conversion handles this * Check broker's timestamp format if persistent 3. **Zero values displayed** * Verify API key is configured * Check if market is open (after 9 AM IST) * Ensure positions or trades exist 4. **Chart not loading** * Verify lightweight-charts.js is loaded * Check browser console for errors * Try different theme or refresh page #### [hashtag](https://docs.openalgo.in/new-features/pnl-tracker#undefined) [PreviousAPI Analyzerchevron-left](https://docs.openalgo.in/new-features/api-analyzer) [NextTraffic/Latency Monitorchevron-right](https://docs.openalgo.in/new-features/traffic-latency-monitor) Last updated 8 months ago * [Overview](https://docs.openalgo.in/new-features/pnl-tracker#overview) * [PnL Tracker Documentation](https://docs.openalgo.in/new-features/pnl-tracker#pnl-tracker-documentation) * [Overview](https://docs.openalgo.in/new-features/pnl-tracker#overview-1) * [Features](https://docs.openalgo.in/new-features/pnl-tracker#features) * [Technical Architecture](https://docs.openalgo.in/new-features/pnl-tracker#technical-architecture) * [PnL Calculation Logic](https://docs.openalgo.in/new-features/pnl-tracker#pnl-calculation-logic) * [Timestamp Handling](https://docs.openalgo.in/new-features/pnl-tracker#timestamp-handling) * [Error Handling](https://docs.openalgo.in/new-features/pnl-tracker#error-handling) * [Time Filtering](https://docs.openalgo.in/new-features/pnl-tracker#time-filtering) * [Performance Optimization](https://docs.openalgo.in/new-features/pnl-tracker#performance-optimization) * [Broker Compatibility](https://docs.openalgo.in/new-features/pnl-tracker#broker-compatibility) * [Usage](https://docs.openalgo.in/new-features/pnl-tracker#usage) * [Troubleshooting](https://docs.openalgo.in/new-features/pnl-tracker#troubleshooting) sun-brightdesktopmoon Copy 1. User clicks PnL Tracker in navbar ↓ 2. Frontend loads and requests PnL data ↓ 3. Backend fetches: - Tradebook (executed trades) - Current positions - Historical 1-minute data ↓ 4. Calculate MTM PnL: - For trades: (current_price - executed_price) × quantity - For positions: (current_price - average_price) × quantity ↓ 5. Generate time series data from 9 AM IST ↓ 6. Return formatted data to frontend ↓ 7. Display interactive charts Copy # For each trade in tradebook: if action == 'BUY': pnl = (current_price - executed_price) × quantity else: # SELL pnl = (executed_price - current_price) × quantity Copy # When tradebook is empty but positions exist: if quantity > 0: # Long position pnl = (current_price - average_price) × quantity else: # Short position pnl = (average_price - current_price) × abs(quantity) sun-brightdesktopmoon --- # Flow - Visual Strategy Builder | Documentation ### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#introduction) Introduction The Flow Visual Strategy Builder is OpenAlgo's node-based visual programming interface. It allows you to create trading strategies without writing code by connecting nodes in a flowchart-like canvas. ### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#what-is-the-flow-builder) What is the Flow Builder? Copy ┌─────────────────────────────────────────────────────────────────────────────┐ │ Flow Visual Strategy Builder │ │ │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ │ Trigger │────▶│ Condition│────▶│ Action │────▶│ Output │ │ │ │ Node │ │ Node │ │ Node │ │ Node │ │ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │ │ │ Example: Webhook → Check Price → Place Order → Send Notification │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ ### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#benefits) Benefits Feature Description No Coding Required Build strategies visually Drag and Drop Intuitive interface Real-time Testing Test flows instantly Reusable Components Save and reuse node groups Version Control Track changes to flows ### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#accessing-the-flow-builder) Accessing the Flow Builder 1. Login to OpenAlgo 2. Navigate to **Flow** in the sidebar 3. Click **New Flow** or select existing ### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#interface-overview) Interface Overview ### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#node-types) Node Types #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#trigger-nodes) Trigger Nodes Trigger nodes start flow execution. Node Description Use Case Webhook Receives external HTTP requests TradingView, ChartInk alerts Timer Executes at intervals Periodic checks Schedule Executes at specific times Market open/close actions Manual Manual trigger button Testing #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#condition-nodes) Condition Nodes Condition nodes control flow logic. Node Description Use Case If/Else Branch based on condition Price above/below threshold Compare Compare two values Value comparisons Logic Gate AND, OR, NOT operations Multiple conditions Switch Multiple branches Route by symbol/action #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#action-nodes) Action Nodes Action nodes execute trading operations. Node Description Use Case Place Order Send order to broker Standard orders Smart Order Position-aware order Reversal strategies Basket Order Multiple orders Multi-symbol strategies Close Position Close specific position Exit trades Close All Close all positions End-of-day square off #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#utility-nodes) Utility Nodes Utility nodes for supporting operations. Node Description Use Case Log Write to log Debugging Telegram Send Telegram message Notifications Delay Wait for specified time Throttling Variable Store/retrieve values State management HTTP Request Call external APIs Data fetching ### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#building-your-first-flow) Building Your First Flow #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#example-tradingview-alert-to-order) Example: TradingView Alert to Order **Step 1: Add Webhook Trigger** 1. Drag **Webhook** node to canvas 2. Configure: * Name: "TradingView Alert" * Path: `/flow/tradingview` **Step 2: Add Place Order Action** 1. Drag **Place Order** node to canvas 2. Connect Webhook output to Order input 3. Configure order parameters: * Symbol: `{{webhook.symbol}}` * Exchange: `NSE` * Action: `{{webhook.action}}` * Quantity: `100` * Price Type: `MARKET` * Product: `MIS` **Step 3: Add Notification** 1. Drag **Telegram** node to canvas 2. Connect Order output to Telegram input 3. Configure message: **Step 4: Save and Activate** 1. Click **Save** 2. Click **Activate** to enable the flow 3. Copy the webhook URL for TradingView ### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#using-variables) Using Variables #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#dynamic-values-from-webhook) Dynamic Values from Webhook #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#node-output-variables) Node Output Variables ### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#advanced-flow-examples) Advanced Flow Examples #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#example-1-smart-order-with-reversal) Example 1: Smart Order with Reversal Configuration: * Switch node routes by `{{webhook.action}}` * Smart Order: position\_size = `{{webhook.position_size}}` #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#example-2-conditional-order-based-on-price) Example 2: Conditional Order Based on Price #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#example-3-multi-symbol-basket-order) Example 3: Multi-Symbol Basket Order ### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#webhook-configuration) Webhook Configuration #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#making-flow-webhooks-accessible) Making Flow Webhooks Accessible Flow webhooks need to be accessible from the internet for external triggers (TradingView, ChartInk, etc.). **Recommended**: Deploy OpenAlgo on an Ubuntu server with your domain using `install.sh`: **Alternative**: Use tunneling services **for webhooks only**: Service Command **ngrok** `ngrok http 5000` **devtunnel** (Microsoft) `devtunnel host -p 5000` **Cloudflare Tunnel** `cloudflared tunnel --url http://localhost:5000` See Installation Guide for detailed setup. #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#webhook-url-format) Webhook URL Format #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#tradingview-alert-message) TradingView Alert Message #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#testing-webhooks) Testing Webhooks 1. Open flow in editor 2. Click **Test Webhook** 3. Enter sample payload 4. Click **Execute** 5. View results in right panel ### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#flow-templates) Flow Templates OpenAlgo provides pre-built templates: Template Description TradingView Basic Simple webhook to order Smart Reversal Position-aware trading Multi-Symbol Basket Trade multiple symbols Scheduled Square-off EOD position close Options Strategy Multi-leg options #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#using-templates) Using Templates 1. Click **Templates** in Flow Builder 2. Select desired template 3. Click **Use Template** 4. Customize parameters 5. Save with your name ### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#debugging-flows) Debugging Flows #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#view-execution-history) View Execution History 1. Go to **Flow** → select your flow 2. Click **History** tab 3. View past executions #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#execution-details) Execution Details #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#common-issues) Common Issues Issue Cause Solution Flow not triggering Not activated Activate flow Wrong symbol Variable mismatch Check variable names Order failed Invalid parameters Verify node configuration Timeout Slow external API Increase timeout ### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#best-practices) Best Practices #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#id-1.-test-before-activating) 1\. Test Before Activating Always test with sample data before going live. #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#id-2.-use-descriptive-names) 2\. Use Descriptive Names Name nodes clearly: * "TradingView Buy Signal" not "Node 1" * "SBIN Order" not "Place Order" #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#id-3.-add-error-handling) 3\. Add Error Handling #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#id-4.-add-notifications) 4\. Add Notifications Always add notification nodes for important events. #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#id-5.-version-your-flows) 5\. Version Your Flows * Save with version numbers * Keep backup copies * Document changes ### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#flow-security) Flow Security #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#access-control) Access Control * Flows are tied to your API key * Webhook URLs are unique per flow * Authentication required for editing #### [hashtag](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#webhook-security) Webhook Security * Use HTTPS only * Validate incoming data * Implement rate limiting * * * [PreviousPython Strategy Hostingchevron-left](https://docs.openalgo.in/new-features/python-strategy-hosting) [NextHistorifychevron-right](https://docs.openalgo.in/new-features/historify) Last updated 8 days ago * [Introduction](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#introduction) * [What is the Flow Builder?](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#what-is-the-flow-builder) * [Benefits](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#benefits) * [Accessing the Flow Builder](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#accessing-the-flow-builder) * [Interface Overview](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#interface-overview) * [Node Types](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#node-types) * [Building Your First Flow](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#building-your-first-flow) * [Using Variables](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#using-variables) * [Advanced Flow Examples](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#advanced-flow-examples) * [Webhook Configuration](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#webhook-configuration) * [Flow Templates](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#flow-templates) * [Debugging Flows](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#debugging-flows) * [Best Practices](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#best-practices) * [Flow Security](https://docs.openalgo.in/new-features/flow-visual-strategy-builder#flow-security) sun-brightdesktopmoon Copy ┌─────────────────────────────────────────────────────────────────────────────┐ │ Flow Builder [Save] [Run] [Stop] │ ├───────────────────┬─────────────────────────────────────────────────────────┤ │ │ │ │ Node Palette │ Canvas │ │ ─────────────── │ │ │ │ ┌────────┐ │ │ ▶ Triggers │ │Webhook │ │ │ • Webhook │ │ Input │───────┐ │ │ • Timer │ └────────┘ │ │ │ • Schedule │ ▼ │ │ │ ┌────────────┐ │ │ ▶ Conditions │ │ Price Check│ │ │ • If/Else │ └────────────┘ │ │ • Compare │ │ │ │ • Logic Gate │ ▼ │ │ │ ┌────────────┐ │ │ ▶ Actions │ │Place Order │ │ │ • Place Order │ └────────────┘ │ │ • Smart Order │ │ │ • Close All │ │ │ │ │ │ ▶ Utilities │ │ │ • Log │ │ │ • Telegram │ │ │ • Delay │ │ │ │ │ └───────────────────┴─────────────────────────────────────────────────────────┘ Copy Order placed: {{webhook.action}} {{webhook.symbol}} Order ID: {{order.orderid}} Copy Webhook Input: { "symbol": "SBIN", "action": "BUY", "quantity": "100" } Access as: Symbol: {{webhook.symbol}} → SBIN Action: {{webhook.action}} → BUY Quantity: {{webhook.quantity}} → 100 Copy Order Node Output: { "status": "success", "orderid": "230125000012345" } Access as: Status: {{order.status}} → success Order ID: {{order.orderid}} → 230125000012345 Copy ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ Webhook │────▶│ Switch │────▶│ Smart │────▶│ Telegram │ │ Input │ │ (action) │ │ Order │ │ Notify │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ Copy ┌──────────┐ ┌──────────┐ ┌──────────┐ │ Webhook │────▶│ Compare │────▶│ Place │ │ Input │ │Price>100 │ │ Order │ └──────────┘ └──────────┘ └──────────┘ │ ▼ (else) ┌──────────┐ │ Log │ │ "Skipped"│ └──────────┘ Copy ┌──────────┐ ┌──────────────────────────────────────────┐ │ Schedule │────▶│ For Each │ │ 9:20 AM │ │ Symbols: SBIN, HDFCBANK, ICICIBANK │ └──────────┘ └──────────────────────────────────────────┘ │ ▼ ┌──────────────┐ │ Place Order │ │ for {{item}} │ └──────────────┘ Copy https://yourdomain.com/api/v1/flow/{flow-id}/webhook Copy https://your-openalgo-url/api/v1/flow/{flow-id}/webhook Copy { "symbol": "{{ticker}}", "action": "{{strategy.order.action}}", "quantity": "{{strategy.order.contracts}}", "position_size": "{{strategy.position_size}}" } Copy ┌─────────────────────────────────────────────────────────────────────────────┐ │ Execution #12345 2025-01-21 10:30:15 │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ │ ✅ Webhook Input Duration: 2ms │ │ Input: {"symbol": "SBIN", "action": "BUY"} │ │ │ │ ✅ Place Order Duration: 150ms │ │ Output: {"status": "success", "orderid": "12345"} │ │ │ │ ✅ Telegram Notify Duration: 300ms │ │ Output: {"status": "sent"} │ │ │ │ Total Duration: 452ms │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ Copy ┌──────────┐ ┌──────────┐ ┌──────────┐ │ Order │────▶│ If Error │────▶│ Retry │ │ Node │ │ Occurred │ │ Node │ └──────────┘ └──────────┘ └──────────┘ │ ▼ (no error) ┌──────────┐ │ Success │ │ Handler │ └──────────┘ sun-brightdesktopmoon --- # Responsibilities | Documentation OpenAlgo is designed to be a transparent, open-source platform that allows individual traders to automate their own strategies. Unlike commercial black-box solutions, OpenAlgo gives you full control and visibility - but with that freedom comes complete responsibility. This section outlines the key responsibilities every user must understand before operating OpenAlgo. * * * ### [hashtag](https://docs.openalgo.in/responsibilities#id-1.-transparency-vs.-black-box-vendors) 1\. Transparency vs. Black-Box Vendors * **No hidden logic**: OpenAlgo is 100% transparent. All execution logic is visible and customizable. * **Comparison with paid platforms**: Many commercial algo platforms hide their execution rules or charge high fees for access, forcing users to trust them blindly. * **Freedom with risk**: In OpenAlgo, transparency means you control everything—but also bear responsibility for testing, and reliability. * * * ### [hashtag](https://docs.openalgo.in/responsibilities#id-2.-community-driven-nature) 2\. Community-Driven Nature * **Support model**: OpenAlgo is community-driven. Support happens through **Discord** and **GitHub issues**. * **No vendor hotline**: There is no centralized support desk. Users must learn, experiment, and engage with peers. * **Active participation**: Users are encouraged to ask **relevant questions** and contribute back. Passive “plug-and-play” expectations will not work. * * * ### [hashtag](https://docs.openalgo.in/responsibilities#id-3.-boundaries-of-the-platform) 3\. Boundaries of the Platform * **Single-user architecture**: OpenAlgo is built as a single-user tool, not a multi-tenant SaaS. * **Low-code, not no-code**: OpenAlgo simplifies complexity but still requires coding knowledge to design and test strategies. * **What OpenAlgo is not**: * Not a guaranteed profit system. * Not a compliance shield—users must follow broker and regulatory rules. * Not a broker replacement—orders still pass through your broker’s RMS. * * * ### [hashtag](https://docs.openalgo.in/responsibilities#id-4.-technical-and-infrastructure-responsibilities) 4\. Technical and Infrastructure Responsibilities * **System Maintenance**: Keep your installation updated with the latest patches and fixes. * **Security Practices**: Configure firewalls, SSL, and protect API keys. Secure hosting is your responsibility. * **Data Management**: You own your data. Maintain backups and secure sensitive credentials. * * * ### [hashtag](https://docs.openalgo.in/responsibilities#id-5.-compliance-and-regulatory-obligations) 5\. Compliance and Regulatory Obligations * **Broker API Rules**: Follow your broker’s API terms, including static IP use and respecting rate limits. * **Personal Use Only**: OpenAlgo is meant for individual trading. Commercial use requires proper regulatory empanelment. * **Risk Management Systems**: Broker RMS safeguards exist, but users are responsible for losses caused by system failures or poorly designed strategies. * * * ### [hashtag](https://docs.openalgo.in/responsibilities#id-6.-strategy-development-and-operational-discipline) 6\. Strategy Development and Operational Discipline * **Build your own strategies**: OpenAlgo does not provide trading systems—you must design them yourself. * **Testing before deployment**: Thorough backtesting and paper trading are mandatory before going live. * **Real-time Monitoring**: Algorithms must be continuously monitored. Users must be prepared to intervene when necessary. * **Documentation**: Keep records of strategies, trades, and performance for both analysis and regulatory needs. * * * ### [hashtag](https://docs.openalgo.in/responsibilities#id-7.-api-usage-and-abuse-prevention) 7\. API Usage and Abuse Prevention * **Rate Limit Adherence**: Respect all API limits for logins, order placements, and WebSocket connections. * **Connection Management**: Avoid repeated or unnecessary API calls that may overload systems or trigger broker restrictions. * * * ### [hashtag](https://docs.openalgo.in/responsibilities#id-8.-risk-acknowledgment) 8\. Risk Acknowledgment * **Financial Responsibility**: All profits and losses are the user’s responsibility. Neither the OpenAlgo team nor your broker can be held liable. * **System Reliability**: Failures such as internet downtime, server crashes, or coding errors can impact execution. Users must accept this risk. * **No Guaranteed Support**: OpenAlgo is community-supported. Immediate help during trading hours cannot be guaranteed. * * * ### [hashtag](https://docs.openalgo.in/responsibilities#id-9.-the-maintenance-era-philosophy) 9\. The Maintenance Era Philosophy OpenAlgo contributors focus on building and maintaining **core features first**, rather than rushing into “fancy” features. Even with AI-assisted development, every feature must be built, tested, and validated carefully. The **goal is simplicity**: reduce the complexity of algo infrastructure so traders and coders can focus on strategy development instead of low-level implementation. ### [hashtag](https://docs.openalgo.in/responsibilities#id-10.-upgrade-discipline) 10\. Upgrade Discipline * **When to upgrade**: Upgrade only when you are ready to test new features or security patches. Do not upgrade blindly during trading hours. * **How to upgrade**: Always test upgrades first in a **safe environment** such as GitHub Codespaces, Docker test containers, or a staging server before applying changes to your live setup. * **Backup first**: Before every upgrade, take a full backup of your OpenAlgo directory. A simple method is to **zip the entire folder** and store it safely. This ensures you can roll back if something goes wrong. * * * ### [hashtag](https://docs.openalgo.in/responsibilities#final-note) Final Note OpenAlgo is a **toolbox, not a solution**. It is designed to empower you with automation while keeping everything transparent and customizable. In return, you must accept the responsibilities of operating, securing, and maintaining your system. Open source thrives when freedom meets accountability. OpenAlgo gives you both—**the transparency of control, and the responsibility of ownership**. * * * [PreviousAction Centerchevron-left](https://docs.openalgo.in/new-features/action-center) [NextCompliancechevron-right](https://docs.openalgo.in/compliance) Last updated 6 months ago * [1\. Transparency vs. Black-Box Vendors](https://docs.openalgo.in/responsibilities#id-1.-transparency-vs.-black-box-vendors) * [2\. Community-Driven Nature](https://docs.openalgo.in/responsibilities#id-2.-community-driven-nature) * [3\. Boundaries of the Platform](https://docs.openalgo.in/responsibilities#id-3.-boundaries-of-the-platform) * [4\. Technical and Infrastructure Responsibilities](https://docs.openalgo.in/responsibilities#id-4.-technical-and-infrastructure-responsibilities) * [5\. Compliance and Regulatory Obligations](https://docs.openalgo.in/responsibilities#id-5.-compliance-and-regulatory-obligations) * [6\. Strategy Development and Operational Discipline](https://docs.openalgo.in/responsibilities#id-6.-strategy-development-and-operational-discipline) * [7\. API Usage and Abuse Prevention](https://docs.openalgo.in/responsibilities#id-7.-api-usage-and-abuse-prevention) * [8\. Risk Acknowledgment](https://docs.openalgo.in/responsibilities#id-8.-risk-acknowledgment) * [9\. The Maintenance Era Philosophy](https://docs.openalgo.in/responsibilities#id-9.-the-maintenance-era-philosophy) * [10\. Upgrade Discipline](https://docs.openalgo.in/responsibilities#id-10.-upgrade-discipline) * [Final Note](https://docs.openalgo.in/responsibilities#final-note) sun-brightdesktopmoon sun-brightdesktopmoon --- # Compliance | Documentation [hashtag](https://docs.openalgo.in/compliance#compliance-and-regulatory-position) Compliance and Regulatory Position ------------------------------------------------------------------------------------------------------------------------- This document describes what OpenAlgo is, how it operates, and where it stands in relation to the Securities and Exchange Board of India (SEBI) regulatory framework for algorithmic trading. It is intended as a plain-language reference for users, broker compliance teams, and anyone evaluating OpenAlgo in a regulated context. It is not legal advice. ### [hashtag](https://docs.openalgo.in/compliance#what-openalgo-is) What OpenAlgo Is OpenAlgo is open-source software published under its stated license on GitHub and PyPI. It is a broker-agnostic order execution library that helps traders connect their own code to their own broker accounts. OpenAlgo is not a service, a subscription platform, a hosted execution engine, an algo marketplace, a broker, or an advisory. ### [hashtag](https://docs.openalgo.in/compliance#how-openalgo-operates) How OpenAlgo Operates 1. **The trader downloads the source code** from GitHub or installs the Python package from PyPI. 2. **The trader deploys OpenAlgo on their own infrastructure**, such as a home PC, a VPS, a Mac Mini, or a Docker container they control. 3. **The trader configures their own broker API credentials** in a local environment file on that infrastructure. 4. **OpenAlgo makes API calls directly from the trader's machine to the trader's broker.** There is no intermediate server, proxy, relay, or observation point operated by creator/maintainer or any affiliated entity. Order flow, credentials, positions, and trade data never leave the trader's infrastructure. OpenAlgo or the creator/maintainer has no technical visibility into any of these. ### [hashtag](https://docs.openalgo.in/compliance#the-four-regulatory-facts) The Four Regulatory Facts Under the SEBI framework for algorithmic trading (circular SEBI/HO/MIRSD/MIRSD-PoD/P/2025/0000013 dated February 4, 2025, effective April 1, 2026), four facts define OpenAlgo's position: **1\. OpenAlgo is open-source software distributed on GitHub and PyPI.** It is published source code, not a service offering. The equivalent category is AmiBroker, MetaTrader, or any Python library on PyPI. **2\. OpenAlgo does not host, route, proxy, or observe any order flow.** Traders run OpenAlgo on their own infrastructure. The public IP that reaches the broker API gateway is the trader's own. The static IP registered with the broker under the SEBI framework is the trader's own. **3\. OpenAlgo does not distribute trading strategies.** OpenAlgo ships execution plumbing only. Traders write their own strategy logic or bring it from elsewhere. No strategies with performance claims are published or distributed through OpenAlgo. The SEBI Research Analyst licensing requirement for black-box strategy distribution does not apply because no such distribution takes place. **4\. OpenAlgo has no commercial association with any broker, research analyst, investment adviser, or financial services entity.** There are no referral arrangements, no brokerage revenue shares, no co-marketing deals, no bundled advisory partnerships, and no "sign up with broker X to get OpenAlgo" promotions. Broker integrations in the source code exist solely because traders use those brokers, not because of any relationship between creator/maintainer and the broker. ### [hashtag](https://docs.openalgo.in/compliance#trader-responsibilities) Trader Responsibilities Because the trader is the operator of their own OpenAlgo instance, the trader is the party responsible for all regulatory obligations that attach to the use of broker APIs. This includes: * Procuring and registering a static IP with their broker, as required by the SEBI framework effective April 1, 2026 * Keeping order flow within the 10 orders-per-second threshold, or registering their strategy with their broker and the exchange if they exceed it * Ensuring their use of the broker API complies with the broker's own API terms of service * Obtaining any required licenses if they distribute strategies or provide investment advice to others OpenAlgo does not mediate, monitor, or manage any of these responsibilities on the trader's behalf. ### [hashtag](https://docs.openalgo.in/compliance#note-to-broker-compliance-teams) Note to Broker Compliance Teams If you are a broker compliance or risk team evaluating OpenAlgo in connection with a client running it against your API, the relevant technical facts are: * OpenAlgo runs on the client's own infrastructure * Your API credentials remain on the client's machine * API calls originate from the client's own IP address * There is no OpenAlgo server, gateway, or relay in the path between the client and your API The source code is publicly available on GitHub for architectural verification. For any specific compliance questions, contact creator of openalgo through the channels listed in the repository. ### [hashtag](https://docs.openalgo.in/compliance#summary) Summary OpenAlgo is software. Traders run it on their own infrastructure using their own broker credentials and their own strategies. creator/maintainer has no visibility into any trader's activity and no commercial relationship with any broker or advisory entity. Responsibility for SEBI, exchange, and broker API compliance rests with the individual trader operating the software. * * * _This document describes the operational and regulatory position of OpenAlgo as of its publication date. It is provided for informational purposes and does not constitute legal advice. Traders should consult their own compliance advisors for questions specific to their situation._ [PreviousResponsibilitieschevron-left](https://docs.openalgo.in/responsibilities) [NextContributorschevron-right](https://docs.openalgo.in/contributors) Last updated 2 days ago * [Compliance and Regulatory Position](https://docs.openalgo.in/compliance#compliance-and-regulatory-position) * [What OpenAlgo Is](https://docs.openalgo.in/compliance#what-openalgo-is) * [How OpenAlgo Operates](https://docs.openalgo.in/compliance#how-openalgo-operates) * [The Four Regulatory Facts](https://docs.openalgo.in/compliance#the-four-regulatory-facts) * [Trader Responsibilities](https://docs.openalgo.in/compliance#trader-responsibilities) * [Note to Broker Compliance Teams](https://docs.openalgo.in/compliance#note-to-broker-compliance-teams) * [Summary](https://docs.openalgo.in/compliance#summary) sun-brightdesktopmoon sun-brightdesktopmoon --- # Monetization | Documentation **How Developers Can Monetize OpenAlgo (AGPL v3.0 License)** OpenAlgo is an open-source, algorithmic trading framework written in Python under the AGPL v3.0 license. The AGPL enforces that any modifications or use of the software over a network must be made available to users under the same license. If you take OpenAlgo, modify its core features (e.g., add a new trading algorithm or improve the user interface), and host it as a web service where users can log in and trade using your modified version. Under the AGPL-3.0 license, you are required to: i)Share the source code of the modified version with your users. ii)Ensure they have access to the exact changes you made to the original OpenAlgo. This requirement ensures that even if the software is accessed over a network (like through a web app or SaaS platform), the users still have the freedom to view, modify, and distribute the code. This ensures that any advancements built on OpenAlgo are contributed back to the community, but it does not preclude monetization efforts. Here’s how developers can monetize OpenAlgo within these constraints: **1\. Open-Source Foundation with AGPL Compliance:** OpenAlgo remains open-source under the AGPL v3.0 license, which mandates that any modifications must be shared with the community, including those used over a network. Developers can build new features and extensions but must ensure that any derivatives or services that expose OpenAlgo through a network also make the source code available to users. **2\. Paid Plugins and Extensions (With Source Code Disclosure):** Developers can create and sell plugins or extensions for OpenAlgo. However, under the AGPL license, if these plugins are used as part of a networked service (e.g., SaaS), the source code must be made available to the users of that service. Monetization can still happen by charging for the plugin itself, packaging, installation services, or enhanced support. **3\. Custom Solutions and Consulting:** One major avenue for monetization under AGPL is offering custom development or consulting services. While code must remain open, developers can charge for the expertise in creating tailored solutions for specific trading needs or strategies. This ensures that the code adheres to the licensing terms but allows developers to monetize their knowledge and implementation services. **4\. Hosted Services and Premium Features:** While AGPL requires the release of source code for any network service, developers can still offer value-added services around OpenAlgo, such as managed hosting, premium support, or data integrations that are separate from the core plugin functionality. These services can be charged for on a subscription basis while ensuring full compliance with AGPL by making any necessary source code available. **5\. Support, Training, and Documentation:** Developers can create value around the ecosystem by offering paid support plans, training sessions, or premium documentation. This could include webinars, one-on-one mentoring for algorithmic trading, or detailed guides for deploying OpenAlgo-based systems. Since these are services and not software, they do not require source code disclosure and are fully monetizable. **How OpenAlgo Should Not Be Monetized:** **1\. Closed-Source Modifications or Plugins:** Under the AGPL license, any modifications or extensions to OpenAlgo that are deployed over a network must be open-source. Developers should not attempt to sell closed-source versions of the framework or plugins that violate the AGPL by keeping modifications proprietary. **2\. Violation of AGPL Network Compliance:** Developers should avoid monetizing services that make use of OpenAlgo over a network without releasing the associated source code. Failure to comply with the AGPL network provisions could lead to legal challenges and compromise the integrity of the platform. **3\. Non-Disclosure of Derivatives:** Any attempts to monetize derivatives of OpenAlgo without making the source code publicly available will breach the AGPL license. Developers must ensure that all modifications, particularly those used to power online services or platforms, are properly disclosed under the same AGPL terms. The AGPL v3.0 license fosters a thriving community while ensuring transparency and sharing of innovations. Developers are encouraged to monetize responsibly by adhering to the open-source principles that benefit everyone involved in the OpenAlgo ecosystem. [PreviousContributorschevron-left](https://docs.openalgo.in/contributors) [NextBrokerschevron-right](https://docs.openalgo.in/connect-brokers/brokers) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Chartink Integration | Documentation OpenAlgo now supports seamless Chartink integration for automated trading based on scanner alerts. Key features include: • Automated Order Placement: Place orders automatically based on BUY, SELL, SHORT, or COVER alerts. **• Dual Queue System:** **• Entry Orders**: Fast processing for BUY/SHORT (up to 10 orders per second). • **Exit Orders**: Priority handling for SELL/COVER (1-second delay per order). • **Custom Strategy Setup**: Configure symbols, quantities, and product types (Intraday/Positional). **• Auto Square-off:** Automatically close intraday positions sequentially. Simply connect your Chartink webhook, configure strategies in OpenAlgo, and automate your trading flow. [PreviousTraffic/Latency Monitorchevron-left](https://docs.openalgo.in/new-features/traffic-latency-monitor) [NextAction Centerchevron-right](https://docs.openalgo.in/new-features/action-center) Last updated 2 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Fast Scalper | Documentation [hashtag](https://docs.openalgo.in/new-features/fast-scalper#fastscalper-a-new-rust-based-tool-for-scalping) FastScalper: A New Rust-Based Tool for Scalping ----------------------------------------------------------------------------------------------------------------------------------------------------------------- **FastScalper** is an innovative desktop application designed specifically for scalpers who need a lightweight, fast, and robust trading tool. Built using Rust, this cross-platform app integrates seamlessly with Open Algo, providing an intuitive interface to place and manage orders efficiently. This guide will walk you through the installation, configuration, and key features of FastScalper. * * * ### [hashtag](https://docs.openalgo.in/new-features/fast-scalper#key-features) Key Features 1. **Cross-Platform Compatibility** FastScalper is compatible with all major operating systems: * **Windows**: Supports multiple instances for tracking and managing various instruments. * **macOS**: Compatible with both Intel and Apple Silicon processors. * **Linux**: Available for distributions like Ubuntu, Debian, and Fedora. 2. **Tiny and Lightweight** A small, portable application optimized for speed, making it ideal for scalpers requiring instant order execution. 3. **Robust Order Management** * Supports multiple product types: * **CNC**: Cash and Carry (carry-forward trades). * **MIS**: Intraday trading for equities and derivatives. * **NRML**: Positional trading for derivatives. * Easy-to-use controls: * **L**: Place a long position. * **LX**: Close long positions. * **SE**: Place a short position. * **SX**: Close short positions. 4. **Voice Alerts** Configurable voice alerts provide audio confirmation for order placement. 5. **Seamless Integration** * Connects to Open Algo via an API key for real-time trading. * Orders can be monitored through trading terminals (desktop, mobile, or web). 6. **Customizable Settings** * API key and host URL configuration. * Exchange and product setup options. * Enable/disable voice alerts as needed. * * * ### [hashtag](https://docs.openalgo.in/new-features/fast-scalper#installation) Installation #### [hashtag](https://docs.openalgo.in/new-features/fast-scalper#prerequisites) Prerequisites * Ensure Open Algo is installed and running. * Obtain the FastScalper installer from the **Downloads** section in Open Algo. #### [hashtag](https://docs.openalgo.in/new-features/fast-scalper#steps) Steps 1. **Download FastScalper** Navigate to the **Downloads** section and select the appropriate installer for your operating system. 2. **Install FastScalper** Follow the platform-specific installation steps. Launch the application once installed. 3. **Configure FastScalper** * Open FastScalper and go to **Settings**. * Enter the following details: * **API Key**: Obtainable from the Open Algo API Key section. * **Host URL**: The URL where Open Algo is running. * Configure additional preferences (e.g., exchange, product type, and voice alerts). 4. **Start Trading** Begin placing and managing orders directly through the FastScalper interface. * * * ### [hashtag](https://docs.openalgo.in/new-features/fast-scalper#usage) Usage 1. **Launching Multiple Instances (Windows)** Open several instances to manage multiple instruments simultaneously. 2. **Order Placement** * Enter the symbol and quantity. * Use dedicated controls for: * **L**: Place a long order. * **LX**: Close long positions. * **SE**: Place a short order. * **SX**: Close short positions. 3. **Error Handling** FastScalper prevents invalid actions, such as attempting to close positions when none exist. 4. **Monitoring Orders** * View order status in the order book. * Monitor trades via trading terminals or web interfaces. * * * ### [hashtag](https://docs.openalgo.in/new-features/fast-scalper#known-limitations) Known Limitations * **Single Instance Support**: macOS and Linux currently support only one instance at a time. * **Feature Requests**: Additional features or configurations can be suggested via the Open Algo GitHub repository. [PreviousNew Featureschevron-left](https://docs.openalgo.in/new-features) [NextPython Strategy Hostingchevron-right](https://docs.openalgo.in/new-features/python-strategy-hosting) Last updated 2 months ago * [FastScalper: A New Rust-Based Tool for Scalping](https://docs.openalgo.in/new-features/fast-scalper#fastscalper-a-new-rust-based-tool-for-scalping) * [Key Features](https://docs.openalgo.in/new-features/fast-scalper#key-features) * [Installation](https://docs.openalgo.in/new-features/fast-scalper#installation) * [Usage](https://docs.openalgo.in/new-features/fast-scalper#usage) * [Known Limitations](https://docs.openalgo.in/new-features/fast-scalper#known-limitations) sun-brightdesktopmoon sun-brightdesktopmoon --- # API Analyzer | Documentation ### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#what-is-sandbox-mode) What is Sandbox Mode? **Sandbox Mode** (also called **API Analyzer Mode**) is like a **trading video game** where you can practice trading strategies with **fake money** but **real market prices**. Think of it as: * **Flight Simulator** for trading * **Real market prices** from live data * **Safe testing** - no real money at risk ### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#why-would-you-use-it) Why Would You Use It? #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#real-world-examples) Real-World Examples **Example 1: Learning Algorithmic Trading** * You wrote your first Python trading bot * You're scared to test it with real money * Enable Sandbox → Get ₹1 Crore fake money → Test your bot safely * If it loses all the money, no problem! Just reset and try again **Example 2: Testing a New Strategy** * You read about a new momentum trading strategy * Before risking ₹1 lakh real money, test it in sandbox * Run it for a week with fake money * If it works well, switch to live mode **Example 3: Practicing Manual Trading** * You're new to options trading * You want to practice buying/selling options without losing money * Sandbox gives you unlimited practice rounds **Example 4: Debugging Your Code** * Your trading bot has a bug that's placing wrong orders * Instead of debugging with real money (expensive!), use sandbox * Fix all bugs safely, then go live ### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#how-it-works) How It Works #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#the-magic-setup) The Magic Setup When you enable Sandbox Mode: 1. OpenAlgo provides virtual simulation of a portfolio 2. All your orders execute in a **simulated environment** 3. Prices come from **real-time market data** 4. **Everything else works exactly like live trading** 5. **Nothing touches your real broker account** #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#live-mode-vs-sandbox-mode) Live Mode vs Sandbox Mode Feature Live Mode Sandbox Mode **Money** Real ₹₹₹ Dummy Capital **Prices** Real market Real market (same) **Orders** Go to broker Stay in OpenAlgo **P&L** Real profit/loss Simulated P&L **Risk** HIGH ZERO **Can lose money?** Yes No **Good for** Making money Learning, testing ### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#step-by-step-setup) Step-by-Step Setup #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#step-1-enable-sandbox-mode) Step 1: Enable Sandbox Mode **Method A: Using Web UI** (Easiest) 1. Log in to OpenAlgo 2. Click **Settings** in the menu 3. Find **"API Analyzer Mode"** toggle 4. Switch it **ON** (it will turn green/blue) 5. Notice: Interface changes to a different theme (visual indicator) **Method B: Using API** (For Python users) #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#step-2-check-your-fake-money) Step 2: Check Your Fake Money Go to **Funds** page: * Available Balance: ₹10,000,000 * Used Margin: ₹0 * Total P&L: ₹0 #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#step-3-place-your-first-test-order) Step 3: Place Your First Test Order **Using Web UI:** 1. Go to any trading page 2. Enter symbol (e.g., "RELIANCE") 3. Choose BUY/SELL 4. Enter quantity (e.g., 10 shares) 5. Click "Place Order" 6. Order executes instantly with fake money! **Using Python Code:** #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#step-4-watch-it-work) Step 4: Watch It Work! 1. Check **Order Book** - Your order appears as "Complete" 2. Check **Positions** - Shows your position with P&L 3. Check **Funds** - Used margin deducted from available balance 4. P&L updates in real-time as market price changes! ### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#what-you-get-in-sandbox) What You Get in Sandbox #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#id-1.-starting-capital) 1\. Starting Capital * **Default**: ₹1 Crore (₹10,000,000) * **Configurable**: You can change it in sandbox settings * **Auto-reset**: Resets to starting amount every Sunday (configurable) #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#id-2.-all-order-types-work) 2\. All Order Types Work * **MARKET** - Buy/sell at current market price * **LIMIT** - Buy/sell at specific price * **SL (Stop Loss)** - Trigger at stop price * **SL-M (Stop Loss Market)** - Trigger and execute at market #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#id-3.-all-product-types-work) 3\. All Product Types Work * **MIS (Intraday)** - Squared off automatically at 3:15 PM * **CNC (Delivery)** - Converted to holdings at midnight * **NRML (F&O)** - Futures and options trading #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#id-4.-realistic-features) 4\. Realistic Features **Margin System:** * Equity Intraday (MIS): 5x leverage * Equity Delivery (CNC): 1x leverage (full payment) * Futures: 10x leverage * Options Buy: 1x (pay full premium) * Options Sell: 10x leverage **Auto Square-Off:** * MIS positions close automatically at: * NSE/BSE: 3:15 PM * MCX: 11:30 PM * CDS: 4:45 PM **Realistic Pricing:** * BUY orders execute at **ask price** (seller's price) * SELL orders execute at **bid price** (buyer's price) * Just like real market! ### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#sandbox-settings-page) Sandbox Settings Page Navigate to: `http://127.0.0.1:5000/sandbox` #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#what-you-can-configure) What You Can Configure **1\. Capital Settings** * Starting Capital: ₹10,000,000 (change it to any amount) * Auto-Reset Day: Sunday (pick any day) * Auto-Reset Time: 12:00 AM (pick any time) * Manual Reset: Click "Reset Now" button anytime **2\. Leverage Settings** * Equity MIS: 5x (how much you can borrow for intraday) * Futures: 10x (margin required for futures) * Options Sell: 10x (margin for selling options) * Options Buy: 1x (must pay full premium) **3\. Square-Off Times** * When MIS positions auto-close * Different times for NSE, MCX, CDS **4\. Performance Tuning** * How often to check pending orders (5 seconds) * How often to update P&L (5 seconds) ### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#how-sandbox-handles-different-scenarios) How Sandbox Handles Different Scenarios #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#scenario-1-buying-stocks-cnc) Scenario 1: Buying Stocks (CNC) **What you do:** **What happens:** 1. **Order placed** → ₹25,000 blocked from available balance 2. **Position created** → Shows in positions page 3. **Next day midnight** → Position converts to holdings automatically 4. **Holdings page** → Shows 10 RELIANCE shares #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#scenario-2-intraday-trading-mis) Scenario 2: Intraday Trading (MIS) **What you do:** **What happens:** 1. **Margin blocked** → ₹12,500 (₹62,500 / 5x leverage) 2. **Position shows** → +₹500 profit (100 shares × ₹5) 3. **At 3:15 PM** → Position automatically squared off 4. **Profit credited** → Available balance increases by ₹500 #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#scenario-3-options-trading) Scenario 3: Options Trading **What you do:** **What happens:** 1. **₹5,000 blocked** (full premium) 2. **If premium goes to ₹150** → Profit ₹2,500 3. **If premium goes to ₹50** → Loss ₹2,500 4. **Just like real options trading!** #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#scenario-4-running-out-of-money) Scenario 4: Running Out of Money **What happens:** **Result:** * Order rejected * Error: "Insufficient funds" * Just like real trading! ### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#understanding-p-and-l-profit-and-loss) Understanding P&L (Profit & Loss) #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#unrealized-p-and-l) Unrealized P&L * Profit/loss on **open positions** * Changes every second as market price changes * Not real until you close the position #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#realized-p-and-l) Realized P&L * Profit/loss on **closed positions** * Added to your available balance * This is "real" profit/loss in sandbox #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#example) Example ### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#common-questions) Common Questions #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#q-is-this-the-same-as-paper-trading) Q: Is this the same as "paper trading"? **A:** It's similar but better! It's a **self-hosted testing environment** that uses real market data. It's NOT a regulated paper trading platform (which SEBI doesn't allow in India). #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#q-does-my-broker-know-im-using-sandbox) Q: Does my broker know I'm using sandbox? **A:** **NO!** Sandbox runs entirely within OpenAlgo. No orders go to your broker. #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#q-can-i-test-my-algo-trading-strategies) Q: Can I test my algo trading strategies? **A:** **YES!** That's the main purpose. Test all your strategies safely before going live. #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#q-what-happens-when-i-switch-back-to-live-mode) Q: What happens when I switch back to live mode? **A:** All sandbox data stays in sandbox database. Your live trading starts fresh. They're completely separate. #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#q-can-i-reset-my-sandbox-funds) Q: Can I reset my sandbox funds? **A:** **YES!** Two ways: 1. **Auto-reset**: Every Sunday at midnight (configurable) 2. **Manual reset**: Click "Reset Now" button in sandbox settings #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#q-do-i-need-real-broker-api-keys-to-use-sandbox) Q: Do I need real broker API keys to use sandbox? **A:** Yes**!** Sandbox works with broker connection and it is mandatory #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#q-can-i-use-action-center-with-sandbox) Q: Can I use Action Center with Sandbox? **A:** **YES!** They work together: * Enable both Sandbox + Semi-Auto mode * Test orders → Go to Action Center → You approve/reject * Perfect for testing the full workflow ### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#when-to-use-sandbox-vs-live) When to Use Sandbox vs Live #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#use-sandbox-mode-when) Use Sandbox Mode When: * Testing new strategies * Learning algorithmic trading * Debugging your trading code * Practicing options/futures trading * Experimenting with order types * Validating your algorithm logic * You're not ready to risk real money #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#use-live-mode-when) Use Live Mode When: * Strategy tested and proven in sandbox * You understand the risks * Code is bug-free * You're ready to make real money (or lose it) * You've practiced enough ### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#best-practices) Best Practices #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#id-1.-always-test-first) 1\. Always Test First #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#id-2.-use-realistic-capital) 2\. Use Realistic Capital If you plan to trade live with ₹1 lakh, test sandbox with ₹1 lakh (not ₹1 crore). This gives realistic results. #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#id-3.-monitor-performance) 3\. Monitor Performance * Track win rate * Calculate average profit per trade * Measure maximum drawdown * Use this data to improve strategy #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#id-4.-dont-skip-sandbox) 4\. Don't Skip Sandbox Even experienced traders test new strategies in sandbox first. It's free insurance! #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#id-5.-combine-with-action-center) 5\. Combine with Action Center * Sandbox ON + Semi-Auto ON = Perfect testing environment * See every order before execution * Catch bugs early ### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#visual-indicators) Visual Indicators When sandbox is enabled: * **Theme changes** to "Garden" theme (different colors) * **Badge/label** shows "Analyzer Mode Active" * **Funds page** shows sandbox balance (₹1 Crore default) * **Separate database** (sandbox.db) When live mode is active: * **Default theme** * **Real broker funds** shown * **Real database** (openalgo.db) ### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#technical-details-optional) Technical Details (Optional) #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#database-separation) Database Separation * **Live**: `db/openalgo.db` * **Sandbox**: `db/sandbox.db` * Completely isolated - no data mixing #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#architecture) Architecture #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#thread-management) Thread Management * Sandbox runs in background thread * Monitors pending orders every 5 seconds * Updates P&L in real-time * Auto square-off runs on schedule * T+1 settlement at midnight #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#configuration-file) Configuration File Located at: `db/sandbox.db` in table `sandbox_config` Can be modified via sandbox settings page or directly in database. ### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#troubleshooting) Troubleshooting #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#problem-orders-not-executing-in-sandbox) Problem: Orders not executing in sandbox **Solution:** 1. Check if sandbox mode is ON (Settings → API Analyzer Mode) 2. Verify symbol exists (try RELIANCE, SBIN, INFY) 3. Check available balance (Funds page) 4. Look at logs for errors #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#problem-cant-see-positions) Problem: Can't see positions **Solution:** 1. Make sure you're looking at sandbox positions, not live 2. Check if order was actually placed (Order Book) 3. Verify order status is "Complete" #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#problem-wrong-p-and-l-calculation) Problem: Wrong P&L calculation **Solution:** 1. Remember: BUY @ ask price, SELL @ bid price 2. Check if using correct product type (MIS vs CNC) 3. Verify leverage settings in sandbox config #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#problem-funds-not-resetting) Problem: Funds not resetting **Solution:** 1. Check auto-reset day/time in sandbox settings 2. Use manual "Reset Now" button 3. Restart OpenAlgo application ### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#example-complete-trading-workflow) Example: Complete Trading Workflow Let's walk through a complete example: #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#step-1-enable-sandbox) Step 1: Enable Sandbox #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#step-2-check-starting-balance) Step 2: Check Starting Balance #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#step-3-place-first-order) Step 3: Place First Order #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#step-4-check-position) Step 4: Check Position #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#step-5-close-position) Step 5: Close Position #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#step-6-check-final-p-and-l) Step 6: Check Final P&L #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#step-7-analyze-and-learn) Step 7: Analyze and Learn * Strategy worked! * Made ₹50 profit (in sandbox) * Now optimize and test more * When confident → Switch to Live Mode ### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#regulatory-note) Regulatory Note #### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#is-sandbox-legal-in-india) Is Sandbox Legal in India? **YES** Sandbox is **NOT** a virtual/paper trading platform. It's a **personal testing environment** that: * Runs on your own computer * Uses your own OpenAlgo installation * For your own strategy development * Like a calculator or Excel spreadsheet It's a **development tool**, not a trading service. ### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#support-and-resources) Support & Resources * **Detailed Docs**: See `docs/sandbox/` folder for technical details * **Report Issues**: https://github.com/marketcalls/openalgo/issues * **Full Documentation**: https://docs.openalgo.in * **Community**: Join discussions on GitHub ### [hashtag](https://docs.openalgo.in/new-features/api-analyzer#summary) Summary **Sandbox Mode** = Your **safe playground** for trading * Free virtual money (₹1 Crore) * Real market prices * Zero risk * Perfect for learning * Test before going live **Remember**: The best traders test everything before risking real money. Sandbox makes that easy! * * * **Next Steps**: 1. Enable sandbox mode 2. Place a few test orders 3. Watch how P&L changes 4. Test your strategy for 1 week 5. If profitable, switch to Live Mode 6. Start making real money Good luck and happy testing! [PreviousHistorifychevron-left](https://docs.openalgo.in/new-features/historify) [NextPNL Trackerchevron-right](https://docs.openalgo.in/new-features/pnl-tracker) Last updated 8 days ago * [What is Sandbox Mode?](https://docs.openalgo.in/new-features/api-analyzer#what-is-sandbox-mode) * [Why Would You Use It?](https://docs.openalgo.in/new-features/api-analyzer#why-would-you-use-it) * [How It Works](https://docs.openalgo.in/new-features/api-analyzer#how-it-works) * [Step-by-Step Setup](https://docs.openalgo.in/new-features/api-analyzer#step-by-step-setup) * [What You Get in Sandbox](https://docs.openalgo.in/new-features/api-analyzer#what-you-get-in-sandbox) * [Sandbox Settings Page](https://docs.openalgo.in/new-features/api-analyzer#sandbox-settings-page) * [How Sandbox Handles Different Scenarios](https://docs.openalgo.in/new-features/api-analyzer#how-sandbox-handles-different-scenarios) * [Understanding P&L (Profit & Loss)](https://docs.openalgo.in/new-features/api-analyzer#understanding-p-and-l-profit-and-loss) * [Common Questions](https://docs.openalgo.in/new-features/api-analyzer#common-questions) * [When to Use Sandbox vs Live](https://docs.openalgo.in/new-features/api-analyzer#when-to-use-sandbox-vs-live) * [Best Practices](https://docs.openalgo.in/new-features/api-analyzer#best-practices) * [Visual Indicators](https://docs.openalgo.in/new-features/api-analyzer#visual-indicators) * [Technical Details (Optional)](https://docs.openalgo.in/new-features/api-analyzer#technical-details-optional) * [Troubleshooting](https://docs.openalgo.in/new-features/api-analyzer#troubleshooting) * [Example: Complete Trading Workflow](https://docs.openalgo.in/new-features/api-analyzer#example-complete-trading-workflow) * [Regulatory Note](https://docs.openalgo.in/new-features/api-analyzer#regulatory-note) * [Support & Resources](https://docs.openalgo.in/new-features/api-analyzer#support-and-resources) * [Summary](https://docs.openalgo.in/new-features/api-analyzer#summary) sun-brightdesktopmoon Copy import requests payload = { "apikey": "YOUR_API_KEY", "mode": True # True = Sandbox ON, False = Sandbox OFF } response = requests.post( "http://127.0.0.1:5000/api/v1/analyzer/toggle", json=payload ) print(response.json()) Copy import requests payload = { "apikey": "YOUR_API_KEY", "symbol": "RELIANCE", "exchange": "NSE", "action": "BUY", "quantity": 10, "pricetype": "MARKET", "product": "MIS" } response = requests.post( "http://127.0.0.1:5000/api/v1/placeorder", json=payload ) print(response.json()) Copy BUY 10 RELIANCE @ ₹2,500 (CNC) Copy BUY 100 SBIN @ ₹625 (MIS) Price goes up to ₹630 Copy BUY NIFTY 20000 CE @ ₹100 (1 lot = 50 qty) Total cost: ₹5,000 Copy Available Balance: ₹10,000 You try to BUY ₹50,000 worth of stock Copy 1. BUY 100 SBIN @ ₹625 2. Current price: ₹630 Unrealized P&L: +₹500 (not closed yet) 3. SELL 100 SBIN @ ₹630 Realized P&L: +₹500 (closed, profit credited) Copy New Strategy → Sandbox (1 week) → If profitable → Live Mode Copy Your Trading Bot ↓ OpenAlgo API ↓ [Analyzer Check] ↓ Sandbox? ↙ ↘ YES NO ↓ ↓ Sandbox Real Broker Engine API Copy Settings → API Analyzer Mode → ON Copy Funds page: ₹10,000,000 Copy # Buy RELIANCE { "symbol": "RELIANCE", "action": "BUY", "quantity": 10, "pricetype": "MARKET", "product": "MIS" } Copy Positions page: - Symbol: RELIANCE - Quantity: 10 - Avg Price: ₹2,500 - LTP: ₹2,505 - P&L: +₹50 Copy # Sell RELIANCE { "symbol": "RELIANCE", "action": "SELL", "quantity": 10, "pricetype": "MARKET", "product": "MIS" } Copy Trade Book: - BUY 10 @ ₹2,500 = -₹25,000 - SELL 10 @ ₹2,505 = +₹25,050 - Realized P&L: +₹50 Funds: - Available Balance: ₹10,000,050 - Profit: ₹50 ✅ sun-brightdesktopmoon --- # Brokers | Documentation List of OpenAlgo Supported Brokers 1. 5paisa 2. 5paisa (XTS) 3. Aliceblue 4. AngelOne 5. Compositedge (XTS) 6. Definedge Securities 7. Dhan 8. Dhan(Sandbox) 9. Firstock 10. Flattrade 11. Fyers 12. Groww 13. IIFL (XTS) 14. IndiaBulls 15. IndMoney 16. JainamXTS 17. Kotak Securities 18. Motilal Oswal 19. Mstock 20. Nubra 21. Paytm 22. Pocketful 23. Samco 24. Shoonya 25. Rmoney (XTS) 26. Tradejini 27. Upstox 28. Wisdom Capital (XTS) 29. Zebu 30. Zerodha [PreviousMonetizationchevron-left](https://docs.openalgo.in/monetization) [Next5Paisachevron-right](https://docs.openalgo.in/connect-brokers/brokers/5paisa) Last updated 1 month ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Exchanges | Documentation [Delta Exchangechevron-right](https://docs.openalgo.in/crypto/exchanges/delta-exchange) [PreviousZerodhachevron-left](https://docs.openalgo.in/connect-brokers/brokers/zerodha) [NextDelta Exchangechevron-right](https://docs.openalgo.in/crypto/exchanges/delta-exchange) sun-brightdesktopmoon sun-brightdesktopmoon --- # Firstock | Documentation Firstock is an Indian discount brokerage firm offering seamless trading services across various segments such as equities, commodities, currencies, and derivatives. Known for its user-friendly interface, Firstock provides mobile, web, and desktop platforms equipped with essential features like real-time market data, advanced charting tools, and order execution capabilities. Its competitive pricing structure and support for algorithmic trading make it an attractive option for both retail and professional traders. [hashtag](https://docs.openalgo.in/connect-brokers/brokers/firstock#getting-api-credentials) Getting API Credentials ------------------------------------------------------------------------------------------------------------------------- To integrate Firstock with OpenAlgo, follow these steps to obtain your API key and secret: 1\. Log in to Firstock Connect • Visit [https://connect.thefirstock.com/login?ref=wikiconnect.thefirstock.comarrow-up-right](https://connect.thefirstock.com/login?ref=wikiconnect.thefirstock.com) . • Enter your Firstock login credentials. 2\. Generate API Credentials: ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FeFpP3IeGW7b81knjYQmE%252FScreenshot%25202024-12-24%2520at%25202.49.27%25E2%2580%25AFPM.png%3Falt%3Dmedia%26token%3Dd26c6e85-3ee5-47ab-ace1-3fb741d52c7a&width=768&dpr=3&quality=100&sign=ac038709&sv=2) • After logging in, navigate to the API Key section in your profile settings. • Click on Generate API Key. • Your Vendor Code and API Key will be displayed. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FTQ2yYLjI9qPz0rB2hgEY%252FScreenshot%25202024-12-24%2520at%25202.49.44%25E2%2580%25AFPM.png%3Falt%3Dmedia%26token%3D78c1b4dd-e984-48e8-8d2b-e264747c6104&width=768&dpr=3&quality=100&sign=453067d&sv=2) 3\. Configure OpenAlgo: • In your OpenAlgo .env file, set the following variables: [PreviousDhan(Sandbox)chevron-left](https://docs.openalgo.in/connect-brokers/brokers/dhan-sandbox) [NextFlatTradechevron-right](https://docs.openalgo.in/connect-brokers/brokers/flattrade) Last updated 1 year ago sun-brightdesktopmoon Copy BROKER_API_KEY = 'Your Vendor Code' BROKER_API_SECRET = 'Your API Key' REDIRECT_URL = 'http://127.0.0.1:5000/firstock/callback' sun-brightdesktopmoon --- # 5paisa (XTS) | Documentation [hashtag](https://docs.openalgo.in/connect-brokers/brokers/5paisa-xts#id-5paisa-xts-broker-integration) 5Paisa (XTS) Broker Integration -------------------------------------------------------------------------------------------------------------------------------------------- OpenAlgo makes algorithmic trading accessible and straightforward by providing seamless integration with various brokers, including 5Paisa(XTS API). This documentation will guide you through the process of configuring your 5Paisa account to work with OpenAlgo * * * * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/5paisa-xts#step-1-create-api-applications) Step 1: Create API Applications Login to [XTS Developer Portalarrow-up-right](https://xtsmum.5paisa.com/dashboard#!/app) . Once logged in: 1. Go to `My App` > `Create New Application` ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FWF1H72NPtdO4czwE5OgL%252Fimage.png%3Falt%3Dmedia%26token%3D5d950dcc-ee13-4996-97f7-0f5d3fcd8832&width=768&dpr=3&quality=100&sign=cd5c815a&sv=2) 1. Create two separate apps: * **Interactive Order API** * **Market Data API** ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FfvJh23pkgiXm70o4RgqU%252Fimage.png%3Falt%3Dmedia%26token%3D0625fbff-71f7-445f-ac33-e019a520ddc4&width=768&dpr=3&quality=100&sign=988529bf&sv=2) #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/5paisa-xts#details-to-fill) Details to Fill: * **App Name**: OpenAlgo * **App Description**: OpenAlgo * **Redirect URL: (leave it empty)** * **Company Name**: OpenAlgo (or your own) * Choose the correct **API Package** depending on the app (Order or Market Data). ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FxJ2780miMX50oBWI6m4s%252Fimage.png%3Falt%3Dmedia%26token%3D00ec1e5e-a30f-44f8-8430-e9e9c2638cfa&width=768&dpr=3&quality=100&sign=c03688bb&sv=2) Once submitted, wait for approval from the broker. After approval, the status will turn **Active**. * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/5paisa-xts#step-2-setup-environment-variables) Step 2: Setup Environment Variables Refer to the `.sample.env` file in your OpenAlgo folder and prepare your `.env` as follows: Replace the values with actual credentials shown on your developer dashboard once approved. * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/5paisa-xts#step-3-start-openalgo) Step 3: Start OpenAlgo Once all environment variables are set and your apps are **Active**, you can now start OpenAlgo. > Ensure you have installed dependencies and set up the broker configuration properly. OpenAlgo will now be able to place orders and fetch market data through 5paisa's XTS API. * * * This completes the integration process for 5paisa (XTS API) with OpenAlgo. By following the steps outlined in this guide, you have successfully configured your 5Paisa (XTS API) account for use with OpenAlgo. You can now leverage the power of algorithmic trading to enhance your trading strategies and make data-driven decisions. Should you encounter any issues or need further assistance, please refer to the OpenAlgo community or support resources. Happy trading! [Previous5Paisachevron-left](https://docs.openalgo.in/connect-brokers/brokers/5paisa) [NextAliceBluechevron-right](https://docs.openalgo.in/connect-brokers/brokers/aliceblue) Last updated 1 year ago * [5Paisa (XTS) Broker Integration](https://docs.openalgo.in/connect-brokers/brokers/5paisa-xts#id-5paisa-xts-broker-integration) * [Step 1: Create API Applications](https://docs.openalgo.in/connect-brokers/brokers/5paisa-xts#step-1-create-api-applications) * [Step 2: Setup Environment Variables](https://docs.openalgo.in/connect-brokers/brokers/5paisa-xts#step-2-setup-environment-variables) * [Step 3: Start OpenAlgo](https://docs.openalgo.in/connect-brokers/brokers/5paisa-xts#step-3-start-openalgo) sun-brightdesktopmoon Copy # Broker Configuration BROKER_API_KEY = 'YOUR_BROKER_ORDER_API_KEY' BROKER_API_SECRET = 'YOUR_ORDER_API_SECRET' BROKER_API_KEY_MARKET = 'YOUR_BROKER_MARKET_API_KEY' BROKER_API_SECRET_MARKET = 'YOUR_BROKER_MARKET_API_SECRET' REDIRECT_URL = 'http://127.0.0.1:5000/fivepaisaxts/callback' sun-brightdesktopmoon --- # AliceBlue | Documentation OpenAlgo provides seamless integration with AliceBlue, enabling you to connect your trading strategies with AliceBlue’s brokerage services. Follow this guide to set up your AliceBlue broker account with OpenAlgo. ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/aliceblue#prerequisites) Prerequisites Before proceeding, ensure you have the following: * An active AliceBlue trading account. * Access to the AliceBlue ANT website. * OpenAlgo installed and configured on your local machine. ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/aliceblue#steps-to-create-the-aliceblue-api-secret-key) Steps to Create the AliceBlue API Secret Key ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FKpGc6dLD63He6auQqJij%252Fab1.png%3Falt%3Dmedia%26token%3D19ea45da-ee51-4f24-aad6-58c5783f3dbe&width=768&dpr=3&quality=100&sign=c7dcecc2&sv=2) 1. **To register as a Individual trader/Vendor,** * Navigate to the [https://a3.aliceblueonline.com/arrow-up-right](https://a3.aliceblueonline.com/) * Select **Login as Individual Trader** * Enter your credentials to log in. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FX9xrAbfnUxk8TtNeUzIr%252Fab2.PNG%3Falt%3Dmedia%26token%3D22dcf32b-ce8d-42b9-b94e-5b081166cb6a&width=768&dpr=3&quality=100&sign=5424eb15&sv=2) 1. **Access My Apps** * On the top right corner, click on **Create App**. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Fzwcs40WHqnKXjxHz51ue%252Fab3.png%3Falt%3Dmedia%26token%3D44f93cc9-f913-40c5-bed1-bc94664b45b8&width=768&dpr=3&quality=100&sign=f559874c&sv=2) * Fill up the Mandatory Fields. * Save it ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FWBLEZDPjgzln4u5NmYJk%252Fab4.png%3Falt%3Dmedia%26token%3D7f25085f-6285-49b1-bfe5-976b91921de7&width=768&dpr=3&quality=100&sign=bd44b37c&sv=2) * Fill up the Ip address , select the IP Type from the drop down and submit it. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FJefW3nNaqMFuF3tGH2DX%252Fab5.png%3Falt%3Dmedia%26token%3Db3fb7db5-2ed8-4cf0-bef1-e7dc2bb5dc41&width=768&dpr=3&quality=100&sign=d1f009ab&sv=2) 1. **Generate API Key** * If you don’t already have an API key, generate a new one by following the on-screen instructions. * Note down the **API Secret Key** as it will be required for configuring the `.env` file. ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/aliceblue#configuring-the-.env-file) Configuring the `.env` File The AliceBlue login user ID is used as the API key. Below is a sample configuration for the `.env` file: Replace `your_client_id` with your AliceBlue login user ID and `your_api_secret_here` with the generated API secret key. #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/aliceblue#important-notes) Important Notes * Ensure that your **API Secret Key** is stored securely and is not shared publicly. * The **REDIRECT\_URL** should match the one registered with your API application. Follow these steps to integrate AliceBlue with OpenAlgo successfully. If you encounter any issues, refer to the AliceBlue API documentation for further assistance. [Previous5paisa (XTS)chevron-left](https://docs.openalgo.in/connect-brokers/brokers/5paisa-xts) [NextAngelOnechevron-right](https://docs.openalgo.in/connect-brokers/brokers/angelone) Last updated 1 month ago * [Prerequisites](https://docs.openalgo.in/connect-brokers/brokers/aliceblue#prerequisites) * [Steps to Create the AliceBlue API Secret Key](https://docs.openalgo.in/connect-brokers/brokers/aliceblue#steps-to-create-the-aliceblue-api-secret-key) * [Configuring the .env File](https://docs.openalgo.in/connect-brokers/brokers/aliceblue#configuring-the-.env-file) sun-brightdesktopmoon Copy # AliceBlue Broker Configuration BROKER_API_KEY = 'your_api_key' BROKER_API_SECRET = 'your_api_secret_here' REDIRECT_URL = 'http://127.0.0.1:5000/aliceblue/callback' sun-brightdesktopmoon --- # AngelOne | Documentation AngelOne, previously known as Angel Broking, is a prominent Indian stock brokerage firm offering a wide range of trading and investment services. For developers and fintech companies looking to integrate algorithmic trading capabilities, AngelOne provides an API gateway through its platform. This API, often referred to in the context of OpenAlgo integration, enables automated trading strategies, real-time market data access, and more. The introductory phase of integrating with AngelOne's API typically involves: **Enable TOTP**: Developers must register for an API key through AngelOne's developer portal, which serves as the authentication mechanism for API requests. ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/angelone#what-is-2-factor-authentication-2-fa-3) **What is 2-factor authentication (2-FA)?** The 2FA or 2-factor authentication is a user authentication process where brokers offer to traders/investors any two of the following three types of authentication mechanisms to users for logging in to their online trading account- 1. Knowledge factor (i.e. something that only the user knows) e.g. PIN, password, etc. 2. Possession factor (i.e. something that only the user has) e.g. OTP, security token, authenticator apps on smartphones, etc. 3. Biometrics (i.e. biological identity markers of the person) e.g. fingerprint, face id, pattern, etc. ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/angelone#manual-totp-generation-process-using-google-authenticator) Manual TOTP Generation Process using Google Authenticator Step 1 – Visit [smartapi.angelbroking.com/enable-totparrow-up-right](http://smartapi.angelbroking.com/enable-totp) Step 2 – Enter your Angel One client id and trading terminal password **or MPIN** Step 3 – Enter the OTP sent to the Registered email & mobile. Once OTP is entered, you will see a QR code on the screen and a token number on the screen. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FKs2Rhy5kkj1tNskFBQ7X%252FAngel%2520TOTP.webp%3Falt%3Dmedia%26token%3D3b7e7eb7-bceb-47a8-a3fe-11217a79fcd7&width=768&dpr=3&quality=100&sign=e5f65016&sv=2) Enable TOTP Step 4 – Open the **Google Authenticator App**. Install it from the Android Playstore or Apple Store Step 5 – Scan the QR code generated from our site on your authenticator app Google authenticator now generates TOTP(Time-based OTP) and it is valid for 60 seconds. Use this for manual TOTP verification ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FLL1RTNvpWQ3Iry8t3CJI%252FGoogle-Authenticator.webp%3Falt%3Dmedia%26token%3D323094f9-7f4e-4cdc-88cc-4d7a7a719098&width=768&dpr=3&quality=100&sign=d00cdde2&sv=2) Google Authenticator ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FWIxNtr7XgtNk0E3A7hKu%252Fimage.png%3Falt%3Dmedia%26token%3Df9c15775-5a0d-440c-b744-46459220382a&width=768&dpr=3&quality=100&sign=8a9e0a32&sv=2) **API Key Registration**: Developers must register for an API key through AngelOne's developer portal, which serves as the authentication mechanism for API requests. Goto the [Smart API Developer Portalarrow-up-right](https://smartapi.angelbroking.com/signin) and login with your credentials. sign up if you are a new user. Enter the App name, Redirect URL (use dummy url https://google.com) and your Angel Client ID Save the generated apikey. Later we will be adding the apikey in the [environmental variablearrow-up-right](https://docs.openalgo.in/getting-started/windows-installation/environmental-variables) Here is a sample of how the details would appear in a .env file for reference: Integrating OpenAlgo with AngelOne's API opens up possibilities for automated trading strategies, providing a powerful tool for traders and developers to exploit market opportunities efficiently. It's essential to follow best practices for API integration, including handling rate limits, managing API keys securely, and ensuring robust error handling and logging mechanisms are in place. [PreviousAliceBluechevron-left](https://docs.openalgo.in/connect-brokers/brokers/aliceblue) [NextCompositedgechevron-right](https://docs.openalgo.in/connect-brokers/brokers/compositedge) Last updated 1 year ago * [What is 2-factor authentication (2-FA)?](https://docs.openalgo.in/connect-brokers/brokers/angelone#what-is-2-factor-authentication-2-fa-3) * [Manual TOTP Generation Process using Google Authenticator](https://docs.openalgo.in/connect-brokers/brokers/angelone#manual-totp-generation-process-using-google-authenticator) sun-brightdesktopmoon Copy BROKER_API_KEY = 'your_api_key_here' BROKER_API_SECRET = 'your_api_secret_here' REDIRECT_URL = 'http://127.0.0.1:5000/angel/callback' sun-brightdesktopmoon --- # 5Paisa | Documentation OpenAlgo makes algorithmic trading accessible and straightforward by providing seamless integration with various brokers, including 5Paisa. This documentation will guide you through the process of configuring your 5Paisa account to work with OpenAlgo, ensuring you can automate your trading strategies efficiently. Follow the steps below to enable TOTP, generate APIs, and set up your environment for a smooth trading experience. ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/5paisa#step-1-enable-totp) **Step 1: Enable TOTP** **Install Google Authenticator:** * Download and install the Google Authenticator app on your phone. **Set Up TOTP on 5Paisa:** * **Login to 5Paisa Website:** * Navigate to the [5Paisa websitearrow-up-right](https://tradestation.5paisa.com/dashboard) and log in with your credentials. * **Access TOTP Setup:** * Click on your login ID at the top right corner to bring out the menu. * Go to `Profile -> TOTP`. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F5mlUpuCUDW8WVfCJ9Xag%252Fimage.png%3Falt%3Dmedia%26token%3Da10c876f-c928-44e0-8f72-89f1665f5c3e&width=768&dpr=3&quality=100&sign=a2c186cd&sv=2) * **Enable TOTP:** * If you already have TOTP enabled but do not have the "TOTP Key," you will need to disable TOTP and then enable it again. * **Enable External TOTP:** * Click on "Enable external TOTP." * Enter the OTP received on your phone/email. * Enter your 6-digit MPIN. * Scan the QR code in your Google Authenticator app. * Copy the TOTP KEY shown below the QR code and save it in a notepad for later use. * Enter the TOTP shown in the Google Authenticator app. * Click the "Enable" button. * **Confirmation:** * You will see a message saying, "TOTP successfully enabled." ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/5paisa#step-2-generate-apis) **Step 2: Generate APIs** 1. **Login to 5Paisa Website:** * Navigate to the 5Paisa website and log in with your credentials. 2. **Access API Key Generation:** * Click on the menu on the top right next to your name. * Go to `Developer’s APIs -> Get API Keys`. * Keep this page open and proceed to the next step. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FxhOUbW4cQsB8iyXRBVn3%252Fimage.png%3Falt%3Dmedia%26token%3D43ee26aa-0723-4f06-a013-25a5b6bc8e0a&width=768&dpr=3&quality=100&sign=49d6547b&sv=2) ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/5paisa#step-3-save-api-details) **Step 3: Save API Details** 1. **Save API Details:** * Save the generated User Key, User ID. Encryption Key, Later, you will add these details to the environmental variables along with the redirect URL. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FYAl15mlOE3HofSXh9JCX%252Fimage.png%3Falt%3Dmedia%26token%3D4569e260-4c5f-4457-b4de-7b5ef9c7ce3e&width=768&dpr=3&quality=100&sign=ab1206b4&sv=2) **Get the Client ID** **Login to 5Paisa Website:** * Navigate to the [5Paisa websitearrow-up-right](https://tradestation.5paisa.com/dashboard) and log in with your credentials. **Access MyProfile** * Click on your login ID at the top right corner to bring out the menu. * Go to `Profile -> MyProfile and get the` `**Client ID**` `as shown below` ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FAT328WnN2kJNFa4HF2oJ%252Fimage.png%3Falt%3Dmedia%26token%3Dedfdc05c-c55d-47b5-8d41-df527f4acdc2&width=768&dpr=3&quality=100&sign=223c7717&sv=2) Save the generated User\_Key, User\_ID, client\_id and Encryption\_Key. Later we will be adding the apikey in the [environmental variablearrow-up-right](https://docs.openalgo.in/getting-started/windows-installation/environmental-variables) along with the redirect url Here is a sample of how the details would appear in a .env file for reference: **Sample .env File:** Here is a sample of how the details should appear in a `.env` file for reference: #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/5paisa#conclusion) Conclusion By following the steps outlined in this guide, you have successfully configured your 5Paisa account for use with OpenAlgo. You can now leverage the power of algorithmic trading to enhance your trading strategies and make data-driven decisions. Should you encounter any issues or need further assistance, please refer to the OpenAlgo community or support resources. Happy trading! [PreviousBrokerschevron-left](https://docs.openalgo.in/connect-brokers/brokers) [Next5paisa (XTS)chevron-right](https://docs.openalgo.in/connect-brokers/brokers/5paisa-xts) Last updated 1 year ago * [Step 1: Enable TOTP](https://docs.openalgo.in/connect-brokers/brokers/5paisa#step-1-enable-totp) * [Step 2: Generate APIs](https://docs.openalgo.in/connect-brokers/brokers/5paisa#step-2-generate-apis) * [Step 3: Save API Details](https://docs.openalgo.in/connect-brokers/brokers/5paisa#step-3-save-api-details) sun-brightdesktopmoon Copy BROKER_API_KEY = 'User_Key:::User_ID:::client_id' BROKER_API_SECRET = 'Encryption_Key' REDIRECT_URL = 'http://127.0.0.1:5000/fivepaisa/callback' sun-brightdesktopmoon --- # FlatTrade | Documentation FlatTrade is an Indian discount broker recognized for its flat-fee brokerage model, which ensures cost-effective trading solutions for investors. The platform supports trading across multiple asset classes, including stocks, derivatives, and commodities, via its intuitive mobile and web applications. With features like real-time data feeds, customizable charting tools, and fast order execution, FlatTrade is designed to cater to traders seeking affordability without compromising on essential functionality. [hashtag](https://docs.openalgo.in/connect-brokers/brokers/flattrade#getting-api-credentials) Getting API Credentials -------------------------------------------------------------------------------------------------------------------------- To integrate Flattrade with OpenAlgo, follow these steps to obtain your API key and secret: 1\. Log in to Flattrade Wall • Login to Wall [https://wall.flattrade.inarrow-up-right](https://wall.flattrade.in/) Enter your Flattrade login credentials. 2\. Navigate to Pi in top menu bar , select api(v2) and click on “CREATE NEW API KEY”. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FmwWO1L9smR5zM3UfULet%252Fflat1.PNG%3Falt%3Dmedia%26token%3D8663f9b4-4c3f-4405-a10b-2d8f72a6bcad&width=768&dpr=3&quality=100&sign=18ed90e6&sv=2) 3.Click on Create the New API Key, select Order Volume : ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FvVnact5OEkbQIUHKr9Mp%252Fflat4.PNG%3Falt%3Dmedia%26token%3Dd53ac64f-8704-448b-91b2-bf2560d3087b&width=768&dpr=3&quality=100&sign=7c278946&sv=2) 4.Enter your IP Configuration (Primary IP is required, Secondary is optional) → Click Next ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F3w3Tv2RJeFHgswFTm43S%252Fflat2.PNG%3Falt%3Dmedia%26token%3D6f018dcd-4460-44cf-8e4e-29816e825931&width=768&dpr=3&quality=100&sign=efb2a984&sv=2) 5.Fill out the URL Configuration ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FeZhDDHEOpFhF8him8HdG%252Fflat3.PNG%3Falt%3Dmedia%26token%3D8bbd55f9-7b67-47bd-a327-1e91ac992470&width=768&dpr=3&quality=100&sign=88864cb1&sv=2) 6.Review the Configuration Summary, tick the box to accept Terms & Conditions, and Submit 7.Your request will show as Pending — once approved, your API key is ready! 8.Your API key is now generated ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F8STzioEMF9KarCZdeHnp%252Fflat5.PNG%3Falt%3Dmedia%26token%3D12d3114d-81d0-4a1f-b351-f433d4c11182&width=768&dpr=3&quality=100&sign=39cb48bb&sv=2) 9.Click the eye icon to reveal your Secret Key — Copy both API and Secret Key and start building! 10\. Configure OpenAlgo: • In your OpenAlgo .env file, set the following variables: [PreviousFirstockchevron-left](https://docs.openalgo.in/connect-brokers/brokers/firstock) [NextFyerschevron-right](https://docs.openalgo.in/connect-brokers/brokers/fyers) Last updated 1 month ago sun-brightdesktopmoon Copy BROKER_API_KEY = 'client_id:::api_key' BROKER_API_SECRET = 'api_secret' REDIRECT_URL = 'http://127.0.0.1:5000/flattrade/callback' sun-brightdesktopmoon --- # Delta Exchange | Documentation Delta Exchange is a global cryptocurrency derivatives exchange founded in 2018 by Pankaj Balani, Jitender Tokas, and Saurabh Goyal, offering futures, perpetual swaps, and options trading on Bitcoin, Ethereum, and leading altcoins. Registered with India's Financial Intelligence Unit (FIU-India) and fully compliant with AML and KYC regulations, Delta Exchange stands as the first platform in India to offer crypto options trading. The platform specialises in cryptocurrency derivatives with INR settlement, allowing Indian traders to deposit and withdraw funds directly from their bank accounts without needing to hold any stablecoins or crypto tokens. Its derivatives trading model, settled entirely in INR, means trades are classified as speculative business income — exempting users from the 30% capital gains tax and 1% TDS that typically apply to direct crypto transactions in India. Delta Exchange offers a diverse product suite covering futures with daily, weekly, and monthly expiries on BTC, ETH, XRP, XLM, AAVE, and BNB; perpetual swaps for indefinite position holding; and options on BTC and ETH — the only platform in India to offer this. The exchange also launched "Trackers" in August 2025 — innovative derivative contracts that mirror crypto price movements without requiring direct asset ownership, available at a trading fee of just 0.05% compared to roughly 0.5% on spot markets. For developers and algo traders looking to integrate Delta Exchange into OpenAlgo, the platform provides a comprehensive REST API and WebSocket feed. ### [hashtag](https://docs.openalgo.in/crypto/exchanges/delta-exchange#api-key-registration) API Key Registration To integrate OpenAlgo with Delta Exchange India, you need to generate an API key from within your Delta Exchange account. The API key serves as the authentication mechanism for all programmatic trading requests. #### [hashtag](https://docs.openalgo.in/crypto/exchanges/delta-exchange#step-1-log-in-to-delta-exchange-india) Step 1 – Log in to Delta Exchange India Visit [delta.exchangearrow-up-right](https://delta.exchange/) and log in to your account using your Gmail and password ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FS7S3PbGRJOuWHfIX7nTA%252FDelta1.png%3Falt%3Dmedia%26token%3D08c1b3b7-c28b-4cd4-a868-f66cf66a8cae&width=768&dpr=3&quality=100&sign=50ec5c3b&sv=2) ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FhfzvjucWB3pYbmGOIifs%252FDelta2.png%3Falt%3Dmedia%26token%3D6108d17d-60e0-4ca6-a3f8-51fd3a30c0e2&width=768&dpr=3&quality=100&sign=4ff2edcd&sv=2) #### [hashtag](https://docs.openalgo.in/crypto/exchanges/delta-exchange#step-2-navigate-to-algohub-apis) Step 2 – Navigate to AlgoHub → APIs ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FFUCsV5ghzZGRZDDCPwks%252FDelta3.png%3Falt%3Dmedia%26token%3Dbe477395-d782-4a17-8ac4-dffe94877285&width=768&dpr=3&quality=100&sign=fb5b75bf&sv=2) Once logged in, click on the **AlgoHub** menu in the top navigation bar. From the dropdown, select **APIs** ("Create API key and Start Trading"). This takes you to the Delta Exchange API landing page where you can manage your API keys. #### [hashtag](https://docs.openalgo.in/crypto/exchanges/delta-exchange#step-3-create-a-new-api-key) Step 3 – Create a New API Key ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FBL659gqikGP8Le9IlEDU%252FDelat5.png%3Falt%3Dmedia%26token%3D49fa133e-4f34-4d58-b776-0618c1746d45&width=768&dpr=3&quality=100&sign=8e070439&sv=2) ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FxggIcaZONovRfh8ueGGz%252FDelta6.png%3Falt%3Dmedia%26token%3Dd7d998b9-5ff5-47e2-b004-fa42f7ea3d4f&width=768&dpr=3&quality=100&sign=1ba33be3&sv=2) Click the **Create API Key** button on the API page. You will be taken to the API key creation form at delta.exchange/app/account/manageapikeys . Fill in the following details: * **Account Name** – Select **Main** (or the sub-account you want the key associated with) * **API Key Name** – Enter a recognisable name, e.g., openalgo * **Whitelisted IP** – Enter the IP address of your OpenAlgo server. Only whitelisted IPs will be permitted to interact with the trading API. Add the IP and select it from the **IPs to whitelist** dropdown. * **Permissions** – Enable both: * **Read Data** – Enabled by default for all API keys * **Trading** – Must be explicitly selected to allow order placement #### [hashtag](https://docs.openalgo.in/crypto/exchanges/delta-exchange#step-4-save-the-api-key-and-secret) Step 4 – Save the API Key and Secret After submitting the form, Delta Exchange will display your **API Key** and **API Secret**. Copy and store them securely — the secret will not be shown again. Add them to your OpenAlgo `.env` file as follows: Integrating OpenAlgo with Delta Exchange opens up possibilities for automated crypto derivatives trading — futures, perpetuals, and options — within a fully compliant Indian regulatory framework. As with all broker integrations, it is essential to follow best practices including secure API key management, IP whitelisting, robust error handling, and thorough testing on the testnet environment before going live. [PreviousExchangeschevron-left](https://docs.openalgo.in/crypto/exchanges) [NextGetting Startedchevron-right](https://docs.openalgo.in/installation-guidelines/getting-started) Last updated 1 month ago sun-brightdesktopmoon Copy BROKER_API_KEY = 'your_api_key_here' BROKER_API_SECRET = 'your_api_secret_here' REDIRECT_URL = 'http://127.0.0.1:5000/deltaexchange/callback' sun-brightdesktopmoon --- # Fyers | Documentation Fyers is a cutting-edge technology-driven brokerage firm that offers a comprehensive trading and investment platform. Renowned for their user-friendly applications and robust trading tools, Fyers aims to provide traders with an efficient and streamlined trading experience. They cater to a wide spectrum of users from casual investors to active day traders with services designed to accommodate various trading styles and strategies. For developers and algo traders interested in leveraging the Fyers API, the integration process typically includes the following steps: ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FbWMjLrnf3QMd19CB45pJ%252FFyers%2520App%2520Details.png%3Falt%3Dmedia%26token%3D9ffad45e-d05d-4914-b282-c6d8809382a3&width=768&dpr=3&quality=100&sign=41a82380&sv=2) 1. **Navigate to the Fyers MyAPI Dashboard**: Access the [MyAPI Dashboardarrow-up-right](https://myapi.fyers.in/dashboard) . This dashboard is the central hub for all API-related activities. 2. **Create an Application**: Within the dashboard, there's an option to 'Create App'. This is the initial step in registering a new application that will interact with the Fyers platform through the API. 3. **Fill in Application Details**: You'll be prompted to provide essential details about your application such as the App Name and Redirect URL. The Redirect URL is critical as it's used for securely redirecting users after they have authenticated with Fyers. 4. **Optional App Description and Logo**: Although optional, adding a description and a logo for your app is recommended as it provides users with additional information about your application's purpose and branding. 5. **Save Changes**: Once all the information is provided, save the changes to register the application with Fyers. 6. **Copy the App Credentials**: After saving your app, you'll receive an APP ID (apikey) and a Secret ID (apisecret). These credentials are essential for authenticating API requests and should be stored securely. 7. **Utilize in .env File**: The obtained credentials, along with the Redirect URL, are typically used in a .env file for environment variables which your application can use to interact with the API. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FKhMkntDtKY0F43eRJtOQ%252FFyers%2520App%2520Credentials.png%3Falt%3Dmedia%26token%3D406c0282-4d4a-49bd-96ba-afd28e47c49a&width=768&dpr=3&quality=100&sign=5e04f0d1&sv=2) Here is a sample of how the details would appear in a .env file for reference: Integrating with Fyers API marks the beginning of a new realm of possibilities for automated and algorithmic trading strategies, offering traders and developers a sophisticated platform to tap into market opportunities with agility and precision. To maximize the potential of the Fyers API, it's crucial to adhere to best practices for API integration. This includes being vigilant about handling rate limits, ensuring the secure management of API keys, and implementing comprehensive error handling and logging mechanisms. By doing so, one can ensure a reliable and effective trading experience that leverages the full capabilities of Fyers' advanced trading infrastructure. [PreviousFlatTradechevron-left](https://docs.openalgo.in/connect-brokers/brokers/flattrade) [NextGrowwchevron-right](https://docs.openalgo.in/connect-brokers/brokers/groww) Last updated 1 month ago sun-brightdesktopmoon Copy BROKER_API_KEY = 'your_api_key_here' BROKER_API_SECRET = 'your_api_secret_here' REDIRECT_URL = 'http://127.0.0.1:5000/fyers/callback' sun-brightdesktopmoon --- # Definedge | Documentation OpenAlgo provides seamless integration with Definedge Securities, enabling you to connect your trading strategies with Definedge’s brokerage services. Follow this guide to set up your Definedge broker account with OpenAlgo. **Prerequisites** Before proceeding, ensure you have the following: * An active Definedge Securities trading account. * Access to [Definedge Securities Portalarrow-up-right](https://myaccount.definedgesecurities.com/) . * OpenAlgo installed and configured on your local machine. ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/definedge#steps-to-create-the-definedge-api-secret-key) Steps to Create the Definedge API Secret Key #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/definedge#id-1.-login-to-definedge-securities-portal) 1\. Login to Definedge Securities Portal * Navigate to [https://myaccount.definedgesecurities.com/arrow-up-right](https://myaccount.definedgesecurities.com/) . * Enter your **UCC (Account ID)** and **password**. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Fq9YJEBjpJzu0oSHngZSW%252Fone.png%3Falt%3Dmedia%26token%3Dae215854-1edc-4758-98f8-57c023635a95&width=768&dpr=3&quality=100&sign=5d0a4997&sv=2) * Complete with OTP authentication send to your registered mobile and email ID. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FOlt1EmPsCdmV78WtRFRU%252Ftwo.png%3Falt%3Dmedia%26token%3D7077cdea-0136-4eb4-8a21-911e9d6db0f8&width=768&dpr=3&quality=100&sign=5a0cf02b&sv=2) * This will take you to your dashboard. #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/definedge#id-2.-access-api-key-section) 2\. Access API Key Section * From the dashboard, go to the **Account** section. * Click on **Show my API Secret**. * Here you will find your **API Token** and **API Secret**. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FRXUeQiUKttFGcNW79kxT%252Fthree.png%3Falt%3Dmedia%26token%3Da46b5c36-6b61-4f28-b0a4-551a576f95b2&width=768&dpr=3&quality=100&sign=bf53a15f&sv=2) **Configuring the .env File** The Definedge API Token is used as the API key and API Secrets as API Secret itself. Below is a sample configuration for the .env file #Definedge Broker Configuration **Important Notes** * Ensure that your **API Secret Key and API Token** are stored securely and is not shared publicly. * The **REDIRECT\_URL** should match the one registered with your API application. Follow these steps to integrate Definedge with OpenAlgo successfully. If you encounter any issues, refer to the Definedge API documentation for further assistance. [PreviousCompositedgechevron-left](https://docs.openalgo.in/connect-brokers/brokers/compositedge) [NextDhanchevron-right](https://docs.openalgo.in/connect-brokers/brokers/dhan) Last updated 7 months ago sun-brightdesktopmoon Copy # Definedge Broker Configuration BROKER_API_KEY = 'your_API_Token_here' BROKER_API_SECRET = 'your_API_Secret_here' REDIRECT_URL = 'http://127.0.0.1:5000/definedge/callback' sun-brightdesktopmoon --- # Compositedge | Documentation [hashtag](https://docs.openalgo.in/connect-brokers/brokers/compositedge#compositedge-xts-broker-integration) Compositedge (XTS) Broker Integration ------------------------------------------------------------------------------------------------------------------------------------------------------- Compositedge is a Bangalore-based discount broker that provides API access via the XTS (Symphony Fintech) platform. This guide will help you integrate Compositedge with OpenAlgo. * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/compositedge#step-1-enable-totp-two-factor-authentication) Step 1: Enable TOTP (Two-Factor Authentication) 1. Login to [Compositedge XTSarrow-up-right](https://xts.compositedge.com/#!/app) . ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F8sNeS8vbN8JqYWDjBVKv%252Fimage.png%3Falt%3Dmedia%26token%3Daaede65f-1990-4c1f-8ff3-32b3f7583934&width=768&dpr=3&quality=100&sign=17577253&sv=2) Go to `My Profile` from the top-right menu. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FYIhYxVfs4a8imfm22De4%252Fimage.png%3Falt%3Dmedia%26token%3D4841f911-fae9-48e4-914e-5b465f7e8120&width=768&dpr=3&quality=100&sign=92161123&sv=2) Scan the **QR Code** shown using Google Authenticator. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FbZ7w2sg576g7FTEtRuYn%252Fimage.png%3Falt%3Dmedia%26token%3D9157f0fd-2ab4-47f5-9460-57f9729c8d64&width=768&dpr=3&quality=100&sign=537cc4bb&sv=2) Save the **Secret Key** and enable **TOTP**. > This is required for secure API login during authentication. * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/compositedge#step-2-create-api-applications) Step 2: Create API Applications Login to [XTS Developer Portalarrow-up-right](https://xts.compositedge.com/dashboard#!/login) . Once logged in: 1. Go to `My App` > `Create New Application` ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F9nwrLvACtUDamQsMokhD%252Fimage.png%3Falt%3Dmedia%26token%3D24ad67e2-add7-4c69-bbaf-f39712b71934&width=768&dpr=3&quality=100&sign=b40e0b46&sv=2) 1. Create two separate apps: * **Interactive Order API** * **Market Data API** ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F3I7O10Ff3C2tAPX1hj6O%252Fimage.png%3Falt%3Dmedia%26token%3D9de37937-9be4-4e95-bb2e-e1109cf4c57f&width=768&dpr=3&quality=100&sign=72a5dee5&sv=2) #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/compositedge#details-to-fill) Details to Fill: * **App Name**: OpenAlgo * **App Description**: OpenAlgo * **Redirect URL(required only for Interactive Order API)**: `http://127.0.0.1:5000/compositedge/callback` * **Company Name**: OpenAlgo (or your own) * Choose the correct **API Package** depending on the app (Order or Market Data). ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FQ69zM07gqrzNWRV0djTy%252Fimage.png%3Falt%3Dmedia%26token%3D6f66d835-869d-462b-af27-5ef1e29d11e4&width=768&dpr=3&quality=100&sign=beedfa35&sv=2) Once submitted, wait for approval from the broker. After approval, the status will turn **Active**. * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/compositedge#step-3-setup-environment-variables) Step 3: Setup Environment Variables Refer to the `.sample.env` file in your OpenAlgo folder and prepare your `.env` as follows: Replace the values with actual credentials shown on your developer dashboard once approved. * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/compositedge#step-4-start-openalgo) Step 4: Start OpenAlgo Once all environment variables are set and your apps are **Active**, you can now start OpenAlgo. > Ensure you have installed dependencies and set up the broker configuration properly. OpenAlgo will now be able to place orders and fetch market data through Compositedge's XTS API. * * * This completes the integration process for Compositedge broker with OpenAlgo. Integrating OpenAlgo with Compositedge’s XTS API empowers traders and developers to automate and streamline their trading workflows with precision and speed. By leveraging both order execution and market data APIs, users can build robust trading systems capable of reacting to market conditions in real time. Always ensure secure handling of API credentials, implement proper error handling, and monitor your integration to maintain reliability and compliance. [PreviousAngelOnechevron-left](https://docs.openalgo.in/connect-brokers/brokers/angelone) [NextDefinedgechevron-right](https://docs.openalgo.in/connect-brokers/brokers/definedge) Last updated 1 year ago * [Compositedge (XTS) Broker Integration](https://docs.openalgo.in/connect-brokers/brokers/compositedge#compositedge-xts-broker-integration) * [Step 1: Enable TOTP (Two-Factor Authentication)](https://docs.openalgo.in/connect-brokers/brokers/compositedge#step-1-enable-totp-two-factor-authentication) * [Step 2: Create API Applications](https://docs.openalgo.in/connect-brokers/brokers/compositedge#step-2-create-api-applications) * [Step 3: Setup Environment Variables](https://docs.openalgo.in/connect-brokers/brokers/compositedge#step-3-setup-environment-variables) * [Step 4: Start OpenAlgo](https://docs.openalgo.in/connect-brokers/brokers/compositedge#step-4-start-openalgo) sun-brightdesktopmoon Copy # Broker Configuration BROKER_API_KEY = 'YOUR_BROKER_ORDER_API_KEY' BROKER_API_SECRET = 'YOUR_ORDER_API_SECRET' BROKER_API_KEY_MARKET = 'YOUR_BROKER_MARKET_API_KEY' BROKER_API_SECRET_MARKET = 'YOUR_BROKER_MARKET_API_SECRET' REDIRECT_URL = 'http://127.0.0.1:5000/compositedge/callback' sun-brightdesktopmoon --- # IndiaBulls Securities | Documentation Work in Progress [PreviousIndMoney (INDstocks)chevron-left](https://docs.openalgo.in/connect-brokers/brokers/indmoney) [NextJainamXTSchevron-right](https://docs.openalgo.in/connect-brokers/brokers/jainamxts) Last updated 9 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # IIFL (XTS) | Documentation Documentation in Progress [PreviousGrowwchevron-left](https://docs.openalgo.in/connect-brokers/brokers/groww) [NextIndMoney (INDstocks)chevron-right](https://docs.openalgo.in/connect-brokers/brokers/indmoney) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Shoonya | Documentation Shoonya, developed by Finvasia, is a trading platform in India that allows users to trade across multiple segments—including equities, commodities, currencies, and derivatives. The platform is accessible via mobile, web, and desktop applications, offering features like advanced charting tools, real-time data, and integration with third-party platforms for algorithmic trading. [hashtag](https://docs.openalgo.in/connect-brokers/brokers/shoonya#getting-api-credentials) Getting API Credentials ------------------------------------------------------------------------------------------------------------------------ To integrate Shoonya with OpenAlgo, follow these steps to obtain your API key and secret: 1\. Log in to Shoonya Prism: • Visit [https://trade.shoonya.com/arrow-up-right](https://trade.shoonya.com/) . • Enter your Shoonya login credentials. 2\. Generate API Credentials: ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FH1BaS4xAEmDyGE4yMiNL%252Fshoonya4.PNG%3Falt%3Dmedia%26token%3D4486a793-9a1b-4ec7-b096-e90606b842b6&width=768&dpr=3&quality=100&sign=bf138e1f&sv=2) • After logging in, navigate to the API Key section in your profile dropdown. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FyF3WxZMHUPc0aGKn1FXs%252Fshoonya2.png%3Falt%3Dmedia%26token%3Db8461c9f-39d3-46d5-855c-abc5ca32d8a4&width=768&dpr=3&quality=100&sign=273ca8e8&sv=2) • Click on API Key. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FgvAixETmEAqtDU7VkxJj%252Fshoonya6.PNG%3Falt%3Dmedia%26token%3Ddb08feed-2a5d-4ee7-9dfb-a3060f926a22&width=768&dpr=3&quality=100&sign=bbbad84d&sv=2) • Your client ID and Secret code will be displayed. 3\. Configure OpenAlgo: • In your OpenAlgo .env file, set the following variables: [PreviousSamcochevron-left](https://docs.openalgo.in/connect-brokers/brokers/samco) [NextRMoney (XTS)chevron-right](https://docs.openalgo.in/connect-brokers/brokers/rmoney-xts) Last updated 17 days ago sun-brightdesktopmoon Copy BROKER_API_KEY = 'your_userid_here:::your_ClientId_here' BROKER_API_SECRET = 'your_Secretcode_here' REDIRECT_URL = 'http://127.0.0.1:5000/shoonya/callback' sun-brightdesktopmoon --- # Dhan(Sandbox) | Documentation **What is Dhan SandBox API?** Dhan SandBox API is a simulated testing environment designed for developers and traders to experiment with Dhan’s trading and market data APIs without needing a live brokerage account or actual capital. It replicates the real trading environment but ensures zero risk by not executing trades on the actual exchange. It is ideal for testing integrations, validating order logic, and experimenting with strategies. * * * **Who Should Integrate Dhan SandBox API with OpenAlgo?** OpenAlgo is an open-source algo trading automation framework that connects with platforms like TradingView, Amibroker, and custom dashboards. Integrating Dhan’s SandBox API with OpenAlgo is highly recommended for: * **Algo Developers** building broker connectors. * **Traders** who want to simulate real-time automated strategies before going live. * **Educators and Trainers** who want a safe demo environment. * **Early-stage Fintech Builders** exploring trading APIs. * **QA and Support Teams** needing to replicate live bugs or behaviors in a controlled setup. * * * **Step-by-Step: How to Get Started with Dhan SandBox API** Here’s how to register, access tokens, and start testing with OpenAlgo: #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/dhan-sandbox#id-1.-visit-dhanhq-devportal) 1\. **Visit DhanHQ DevPortal** You’ll land on a login screen where you can enter your email or mobile number. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FIzgdPzoEZpMQ8DMg6F0X%252Fimage.png%3Falt%3Dmedia%26token%3Dbece3781-d1fb-4b3b-a50a-36eb8a02d064&width=768&dpr=3&quality=100&sign=6b65c81c&sv=2) * * * #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/dhan-sandbox#id-2.-register-if-new) 2\. **Register (if new)** If you’re a new user, click to register. Provide: * Email ID * Mobile Number * Your Name Proceed to the next step. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FaOapZO5BFQ1QR0ucXSBx%252Fimage.png%3Falt%3Dmedia%26token%3Df6c6f317-02d8-4aed-992d-37729646567e&width=768&dpr=3&quality=100&sign=7c7cb3ec&sv=2) * * * #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/dhan-sandbox#id-3.-otp-verification) 3\. **OTP Verification** You will receive two OTPs: * One on your **email** * One on your **mobile** Enter both to complete verification. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FjyFu4RGXropouL8ainGS%252Fimage.png%3Falt%3Dmedia%26token%3Dd5869073-d12e-4287-acf7-fbe81a2ad75d&width=768&dpr=3&quality=100&sign=1ca4a456&sv=2) * * * #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/dhan-sandbox#id-4.-access-your-sandbox-token-and-client-id) 4\. **Access Your Sandbox Token and Client ID** Once inside, go to the **Sandbox** tab. You’ll see: * Application Name (e.g., `openalgo`) * **Access Token** (JWT for authorization) * **Client ID** (unique to your application) * API Playground and documentation links ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FxSkIpsVEwZZ3t9mhJAOK%252Fimage.png%3Falt%3Dmedia%26token%3Df71ae9c3-57fa-4df2-9557-c5ad6f985062&width=768&dpr=3&quality=100&sign=7230e88d&sv=2) These credentials are what you will use inside OpenAlgo’s configuration or `.env` file to test trading orders programmatically. * * * #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/dhan-sandbox#retrieve-api-credentials) Retrieve API Credentials Once you've successfully logged into the DhanHQ DevPortal and created your sandbox application: 1. **Copy the Client ID** * This is your `BROKER_API_KEY` * It uniquely identifies your application (e.g., `2505178942`) 2. **Copy the Access Token** * This is your `BROKER_API_SECRET` It acts like a password (JWT format) to authenticate your API requests. #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/dhan-sandbox#configuration-for-openalgo) Configuration for OpenAlgo Inside your OpenAlgo project (or any backend using Dhan APIs), create or update the `.env` file with the following keys: **Summary: Why It Matters for OpenAlgo** Integrating Dhan SandBox with OpenAlgo means: * Safer testing for order placement, cancellation, and position handling. * No compliance delay since no KYC is needed. * Faster debugging and integration turnaround. * Enables workshops, testing, and community support for algo development. By setting up your sandbox environment with Dhan and OpenAlgo, you accelerate your readiness for live algorithmic trading while ensuring a risk-free development experience. [PreviousDhanchevron-left](https://docs.openalgo.in/connect-brokers/brokers/dhan) [NextFirstockchevron-right](https://docs.openalgo.in/connect-brokers/brokers/firstock) Last updated 11 months ago sun-brightdesktopmoon Copy BROKER_API_KEY = 'your_dhan_sandbox_clientid_here' BROKER_API_SECRET = 'your_dhan_sandbox_token_here' REDIRECT_URL = 'http://127.0.0.1:5000/dhan_sandbox/callback' sun-brightdesktopmoon --- # Dhan | Documentation Dhan is a new-generation financial services platform that empowers traders and investors to build, automate, and execute their trading strategies. Through **DhanHQ APIs**, users can connect their Dhan account with tools like **OpenAlgo** and create their own trading automation setup — fully self-hosted and secure. * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/dhan#overview) Overview Dhan provides two main types of APIs: API Type Features Cost **Trading APIs** Order Placement, Position Management, Portfolio & Funds, Order Postbacks, Statement Reports **Free of Cost** **Data APIs** Real-time Prices, Historical Data (5 years), 20-Level Market Depth, Option Chain APIs, Expired Options Data ₹499/month or ₹399/month (₹4,788/year) * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/dhan#steps-for-integration) Steps for Integration #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/dhan#step-1-log-in-to-dhan-web-portal) **Step 1: Log in to Dhan Web Portal** Visit [web.dhan.coarrow-up-right](https://web.dhan.co/) and sign in to your Dhan account. * * * #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/dhan#step-2-access-dhanhq-apis) **Step 2: Access DhanHQ APIs** Click on your profile icon at the top-right and select **“Access DhanHQ APIs”**. From this page, you can: * Generate API Keys * Enable TOTP * Setup Static IP * Manage Trading & Data APIs ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Fcl3ZrS6sahdXldCb4bqd%252Fimage.png%3Falt%3Dmedia%26token%3Da37a29cd-a596-44dd-adc1-f59e0f804422&width=768&dpr=3&quality=100&sign=4bac5966&sv=2) * * * #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/dhan#step-3-switch-to-api-key-mode) **Step 3: Switch to API Key Mode** By default, DhanHQ opens in **Access Token** mode. Use the toggle on the top-right to switch to **API Key Mode**. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Fv5Fat0tC0iRQcLONciOs%252Fimage.png%3Falt%3Dmedia%26token%3D6cb10cf6-2feb-4249-b4d9-2352e12b2241&width=768&dpr=3&quality=100&sign=e12a07aa&sv=2) * * * #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/dhan#step-4-generate-a-new-api-key) **Step 4: Generate a New API Key** 1. Under **Generate new API Key**, enter: * **Application Name** → e.g. `openalgo` * **Redirect URL** → `http://127.0.0.1:5000/dhan/callback` * (Optional) **Postback URL** if your system supports order postbacks 2. Click **Generate API Key**. 3. Copy your: * **API Key** * **API Secret** ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F4kSaBTPLSYn8cJtJdj9H%252Fimage.png%3Falt%3Dmedia%26token%3D71777ede-5b64-4016-bea3-e2579ec25a4b&width=768&dpr=3&quality=100&sign=bda419b&sv=2) * * * #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/dhan#step-5-retrieve-client-id) **Step 5: Retrieve Client ID** 1. From the same profile menu, select **“My Profile on Dhan.”** 2. Scroll to **Profile Details** and copy your **Client ID**. This will be used as part of your API credentials. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Fh1dJ6RC8ZuA1DbND7N67%252Fimage.png%3Falt%3Dmedia%26token%3D4a32b150-11dd-4d30-9869-e7c74b935fea&width=768&dpr=3&quality=100&sign=305f6cc9&sv=2) * * * #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/dhan#step-6-enable-totp-mandatory) **Step 6: Enable TOTP (Mandatory)** * Under **Optional Settings - down below the API Key section**, click **Set-up TOTP.** * Follow the instructions to configure two-factor authentication for API access. * This is **mandatory** for all Dhan API users. * * * #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/dhan#step-7-setup-static-ip-optional-mandatory-from-jan-2026) **Step 7: Setup Static IP (Optional / Mandatory from Jan 2026)** * Click **Static IP Setting** under Optional Settings. * Add up to two IP addresses (e.g., your server or office IP). * You can update these every 7 days. * From **January 2026**, setting at least one **Static IP** will become mandatory. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FGBcU50fom7nbIra12iud%252Fimage.png%3Falt%3Dmedia%26token%3Dafd59cd9-84ae-463f-8bb3-26965c13b308&width=768&dpr=3&quality=100&sign=f80e6f7d&sv=2) * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/dhan#environment-configuration) Environment Configuration Once your credentials are generated, configure them in your `.env` file: * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/dhan#api-costs-summary) API Costs Summary API Type Description Cost **Trading APIs** Order, Position, Portfolio, Funds & Report APIs ✅ **Free of Cost** **Data APIs** Real-time + Historical Data (5 years), Market Depth, Option Chain 💸 ₹499/month (or ₹399/month billed yearly) * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/dhan#best-practices) Best Practices * Keep your **API Key, Secret, and Client ID private**. * Do not share credentials with third-party applications. * Always enable **TOTP** for added security. * Use **Static IPs** when deploying in production environments. * **Daily login to OpenAlgo Portal is mandatory.** * * * Integrating with **DhanHQ APIs** unlocks the ability to automate strategies, execute trades, and analyze data directly within your own infrastructure. When used with **OpenAlgo**, you can self-host and run your entire algo trading stack — with full control and zero vendor lock-in. * * * [PreviousDefinedgechevron-left](https://docs.openalgo.in/connect-brokers/brokers/definedge) [NextDhan(Sandbox)chevron-right](https://docs.openalgo.in/connect-brokers/brokers/dhan-sandbox) Last updated 6 months ago * [Overview](https://docs.openalgo.in/connect-brokers/brokers/dhan#overview) * [Steps for Integration](https://docs.openalgo.in/connect-brokers/brokers/dhan#steps-for-integration) * [Environment Configuration](https://docs.openalgo.in/connect-brokers/brokers/dhan#environment-configuration) * [API Costs Summary](https://docs.openalgo.in/connect-brokers/brokers/dhan#api-costs-summary) * [Best Practices](https://docs.openalgo.in/connect-brokers/brokers/dhan#best-practices) sun-brightdesktopmoon Copy BROKER_API_KEY = 'your_dhan_clientid:::your_dhan_apikey' BROKER_API_SECRET = 'your_dhan_apisecret' REDIRECT_URL = 'http://127.0.0.1:5000/dhan/callback' sun-brightdesktopmoon --- # Getting Started | Documentation * [Windows Desktop](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation) * [Windows Server](https://docs.openalgo.in/installation-guidelines/getting-started/windows-server-installation) * [Mac OS Installation](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation) * [Amazon Elastic Beanstalk](https://docs.openalgo.in/installation-guidelines/getting-started/amazon-elastic-beanstalk) * [Ubuntu Linux Server (No Custom Domain)](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-no-custom-domain) * [Ubuntu Server with Custom Domain](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation) * [Docker Developement](https://docs.openalgo.in/installation-guidelines/getting-started/docker-development) * [Testing OpenAlgo in the Cloud (Github Codespace / Google Colab)](https://docs.openalgo.in/installation-guidelines/getting-started/testing-openalgo-in-cloud) * [SMTP Settings](https://docs.openalgo.in/installation-guidelines/getting-started/smtp-settings) * [TOTP Configuration](https://docs.openalgo.in/installation-guidelines/getting-started/totp-configuration) * [Forgot Password](https://docs.openalgo.in/installation-guidelines/getting-started/forgot-password) * [Upgrade](https://docs.openalgo.in/installation-guidelines/getting-started/upgrade) [PreviousDelta Exchangechevron-left](https://docs.openalgo.in/crypto/exchanges/delta-exchange) [NextWindows Installationchevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation) Last updated 8 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Static IP | Documentation ### [hashtag](https://docs.openalgo.in/installation-guidelines/static-ip#key-faqs-about-static-ip-regulation) Key FAQs About Static IP Regulation **1) Can I deploy my algo on AWS or other cloud services without extra cost for IPs?** You can deploy on AWS or other cloud platforms, but for **API-based order placement** you still need a **static public IP** mapped with your broker if your setup falls under the client API/static-IP model. Whether the cloud provider charges separately for that IP depends on the provider and plan. The regulation requires the **static IP**, not that it must be free. VPS providers often include a fixed public IP by default, but you should verify this before setup. **2) What if I travel often or work from different locations?** If your live order flow depends on a registered static IP, frequent location changes are not practical unless your trading system remains hosted on the same server. Exchange implementation standards allow clients to update mapped static IPs, but **not more than once in a calendar week**, except in extraordinary cases handled by the broker. **3) Is it possible to register more than one static IP?** Yes. The client may provide **one primary static IP** and may also provide **one secondary static IP** for redundancy. **4) Do I need a static IP if I’m just streaming market data?** The framework and FAQ focus the client static-IP requirement on **API use for placing orders** by a tech-savvy investor. So if your application is only consuming market data and not placing/modifying/cancelling orders, the static-IP requirement is generally **not the main trigger**. In practice, you should still check your broker/API portal requirements because implementation details can differ operationally. **5) Can I use an IP address from any country?** The core SEBI/NSE framework I checked does **not** state a general “approved countries / restricted countries” list for client static IPs in the cited documents. So it is safer **not** to claim that any country is automatically allowed. The more reliable statement is: use a stable public static IP that your broker accepts and can map under its onboarding/compliance process. I did not find an authoritative exchange/SEBI source in the materials above establishing a blanket country rule. **6) What if I’m a service provider placing trades for clients?** If you are offering algos to others, the treatment changes. Under the framework, **algo providers** have to be empanelled, and **black box algos** require the algo provider to register as a **Research Analyst** and maintain the required research documentation. Also, exchange FAQ guidance says all such strategies are to be hosted on the broker’s server, not freely run from a shared outside setup. So simply placing trades for multiple clients from one shared IP is **not** enough for compliance. **7) Will I need to register if my app sends too many orders?** The implementation standards set an initial threshold of **10 orders per second per exchange**. Above that, the algo/strategy generally falls into the exchange registration framework and needs the required approvals and identification. It is safer not to describe repeated spikes as automatically “okay”; the practical standard is to design the system so it stays within the permitted unregistered limits unless formally registered. **8) Can I use one static IP for multiple trading accounts?** A static IP can be mapped to **only one client at a time**. The main exception in the implementation standards is that it may be shared among clients belonging to the **same family**, subject to the required request/authentication process. So the older wording should be tightened: one IP is **not** generally a free-for-all across multiple accounts with the same broker. Cross-broker usage is not explicitly addressed in the cited standards the same way, so avoid making a broad claim there unless your brokers confirm it. * * * [PreviousUpgradechevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/upgrade) [NextLatencychevron-right](https://docs.openalgo.in/installation-guidelines/latency) Last updated 1 month ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Pocketful | Documentation * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/pocketful#pocketful) Pocketful Pocketful is a SEBI-registered Indian stock broker offering a modern trading platform with support for multiple asset classes and a powerful API suite. With a focus on automation, speed, and flexibility, Pocketful provides developers and trading system builders direct access to its brokerage services through the [developer portalarrow-up-right](https://api.pocketful.in/) . For OpenAlgo integration, Pocketful enables algorithmic trading with secure API authentication, real-time data streaming, and efficient order placement across equities and derivatives. * * * #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/pocketful#app-registration-and-api-credentials) App Registration and API Credentials The integration begins with creating an app via the Pocketful Developer Portal. This app generates the required credentials for secure API access. * * * **Step-by-Step Guide to Registering Your App** **Step 1 – Visit the Developer Portal** Go to [https://api.pocketful.inarrow-up-right](https://api.pocketful.in/) and log in with your registered email ID or client ID. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FdVquqhCILFM4myBeqj7Y%252Fimage.png%3Falt%3Dmedia%26token%3Dd7aa7882-0eaf-4953-a21f-5195c0920d12&width=768&dpr=3&quality=100&sign=7d0c90e&sv=2) **Step 2 – Navigate to 'Apps' and Create a New App** Click on “+ Create App”. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FZgX1Dc2WEB1ReUJjfKrM%252Fimage.png%3Falt%3Dmedia%26token%3D56f37e5d-37c8-48a6-8f82-fe38df4e4863&width=768&dpr=3&quality=100&sign=d22acc5&sv=2) **Step 3 – Fill App Details** * App Name: `OpenAlgo` * Redirect URL: `http://127.0.0.1:5000/pocketful/callback` * Accept the terms and conditions and click **Create App** ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FFwgwWUBvZ0BhKze5Q7cb%252Fimage.png%3Falt%3Dmedia%26token%3D7f5f674e-59eb-40d2-9488-125b89d18506&width=768&dpr=3&quality=100&sign=6d364a92&sv=2) Once created, the following credentials will be generated: * App ID → use as `API_KEY` * App Secret → use as `API_SECRET` ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F81M5ahl94QSqipLyh8Iu%252Fimage.png%3Falt%3Dmedia%26token%3D21d0e4a5-e5af-4378-ae15-8a7f4248de19&width=768&dpr=3&quality=100&sign=920ca4f8&sv=2) * * * #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/pocketful#api-authentication) API Authentication Pocketful follows OAuth2-based authentication using redirect URI and access tokens. After app creation, OpenAlgo uses the client credentials to initiate authorization and securely fetch access tokens. Here is a sample of how the details would appear in a `.env` file for reference: * * * #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/pocketful#connecting-pocketful-to-openalgo) Connecting Pocketful to OpenAlgo Once your `.env` file is populated with the credentials, OpenAlgo can initiate the login flow. This can be triggered locally: You will be redirected to Pocketful’s login screen. After successful login, the access token will be retrieved and stored locally, completing the authentication process. * * * Integrating OpenAlgo with Pocketful's API allows traders and developers to leverage a powerful, cost-effective, and scalable infrastructure for building and deploying fully automated trading strategies. To ensure smooth performance, it is advisable to manage API limits, rotate tokens securely, and build retry/error-handling logic in production systems. * * * [PreviousPaytmchevron-left](https://docs.openalgo.in/connect-brokers/brokers/paytm) [NextSamcochevron-right](https://docs.openalgo.in/connect-brokers/brokers/samco) Last updated 4 months ago sun-brightdesktopmoon Copy BROKER_API_KEY = 'your_app_id_here' BROKER_API_SECRET = 'your_app_secret_here' REDIRECT_URL = 'http://127.0.0.1:5000/pocketful/callback' Copy http://127.0.0.1:5000/pocketful/login sun-brightdesktopmoon --- # Tradejini | Documentation TradeJini is a progressive brokerage firm known for its reliable execution, low-cost trading, and developer-friendly CubePlus API platform. Designed to support modern algo trading systems, TradeJini provides a robust infrastructure for both retail and institutional traders. Whether you're an individual trader or building advanced trading automation, TradeJini offers the right tools to seamlessly integrate market data and trading functionalities. ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/tradejini#steps-for-integration) Steps for Integration: #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/tradejini#id-1.-log-in-to-the-tradejini-developer-portal) 1\. Log in to the TradeJini Developer Portal Start by accessing the CubePlus Developer Portal at [https://api.tradejini.com/developer-portal/mainarrow-up-right](https://api.tradejini.com/developer-portal/main) ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FUxIZgc1j8csJa0XBVHW0%252F1.JPG%3Falt%3Dmedia%26token%3Da33cc3c4-c9a8-4e4b-ac43-d6bf93c2b0fc&width=768&dpr=3&quality=100&sign=9b570f0f&sv=2) * Click on **Login**. * You can log in using either: * Your **email address and password**, or * By clicking the **TradeJini** logo for broker login. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Fu14PF7DSL4GvazV5mKWv%252F4.JPG%3Falt%3Dmedia%26token%3D77d4e7d7-62ca-4f39-8985-e5028699f7f4&width=768&dpr=3&quality=100&sign=ee1ffae3&sv=2) #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/tradejini#id-2.-create-a-new-app) 2\. Create a New App After logging in: * Navigate to the **Apps** section. * Under **Individual Access**, click **Create New App/Edit App .** * Click **Submit** to register your app. * An **API Key** will be created for authenticated API usage ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Fw8flZqAerVpUZ7ENO2GW%252Fimage.png%3Falt%3Dmedia%26token%3D5c50a4d3-8ab2-495f-830f-80fbc932d702&width=768&dpr=3&quality=100&sign=11b6898f&sv=2) ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FmbOo7r9YGoH9pqOGuk6N%252Ftradejini2.PNG%3Falt%3Dmedia%26token%3D5d1db72b-7c94-41ea-a2d4-4fa3c263f26d&width=768&dpr=3&quality=100&sign=210f30bf&sv=2) #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/tradejini#id-3.-retrieve-api-credentials) 3\. Retrieve API Credentials After generating the API Key: * **Client Code** will be your `api_key`. * **API Key** from the app will serve as your `api_secret`. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FlhNyMtDilrgF7WCaKXLA%252Ftradejini3.PNG%3Falt%3Dmedia%26token%3D791b063d-5064-4baa-ab09-3359d0693dfe&width=768&dpr=3&quality=100&sign=62a8ad96&sv=2) ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/tradejini#configuration) Configuration: Here is how you would typically set up your environment variables in a `.env` file for TradeJini: These credentials will be used by OpenAlgo to authenticate, fetch session tokens, and access market feeds or place orders. ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/tradejini#integration-benefits) Integration Benefits Integrating with the TradeJini API via OpenAlgo opens up a world of possibilities for algorithmic trading and real-time data access. The CubePlus API offers: * High-performance WebSocket feed for LTP, OHLC, depth, and indices. * REST API endpoints for order management and historical data. * Support for complex order types and multi-segment instruments. To ensure a reliable experience with TradeJini’s API: * Handle rate limits and WebSocket throttling appropriately. * Store and manage tokens securely. * Implement robust error handling, retry mechanisms, and logging. By following best practices, developers and traders can leverage the TradeJini infrastructure to build high-frequency, data-driven strategies with confidence. [PreviousRMoney (XTS)chevron-left](https://docs.openalgo.in/connect-brokers/brokers/rmoney-xts) [NextUpstoxchevron-right](https://docs.openalgo.in/connect-brokers/brokers/upstox) Last updated 13 days ago * [Steps for Integration:](https://docs.openalgo.in/connect-brokers/brokers/tradejini#steps-for-integration) * [Configuration:](https://docs.openalgo.in/connect-brokers/brokers/tradejini#configuration) * [Integration Benefits](https://docs.openalgo.in/connect-brokers/brokers/tradejini#integration-benefits) sun-brightdesktopmoon Copy BROKER_API_KEY = 'your_tradejini_clientcode_here' BROKER_API_SECRET = 'your_tradejini_apikey_here' REDIRECT_URL = 'http://127.0.0.1:5000/tradejini/callback' sun-brightdesktopmoon --- # Accessing OpenAlgo | Documentation After starting the openalgo application, access the OpenAlgo platform by navigating to [http://127.0.0.1:5000arrow-up-right](http://127.0.0.1:5000/) in your web browser. If ngrok is configured then access your custom ngrok domain name in the web broker. After completing the setup, access the OpenAlgo platform by navigating to [http://127.0.0.1:5000arrow-up-right](http://127.0.0.1:5000/) in your web browser. setup the account using [http://127.0.0.1:5000/setuparrow-up-right](http://127.0.0.1:5000/setup) Login into openalgo with the credentials and start using OpenAlgo for Automation. [PreviousSSL Verification Failedchevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/ssl-verification-failed) [NextWindows Server Installationchevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/windows-server-installation) Last updated 2 years ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Start OpenAlgo | Documentation From the `openalgo` directory, start the Flask application with the command: `python app.py` ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F6GViS2Zo1wIK2IAAsfSL%252FRunning%2520OpenAlgo%2520Application.png%3Falt%3Dmedia%26token%3Dbf3de9d2-a86a-48d3-a8d4-555171046690&width=768&dpr=3&quality=100&sign=aee9e7de&sv=2) [PreviousEnvironmental Variableschevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/environmental-variables) [NextSSL Verification Failedchevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/ssl-verification-failed) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Upstox | Documentation Upstox, a leading online stock trading platform in India, offers a comprehensive suite of services for traders and investors alike. Catering to the evolving needs of the fintech ecosystem, Upstox extends a robust API interface to developers and fintech startups keen on embedding or leveraging algorithmic trading solutions. This API facilitates the automation of trading strategies, grants access to live market data, and supports a myriad of other financial services functions. Initiating integration with Upstox's API generally involves several key steps: ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/upstox#generating-api-key-and-api-secret) Generating API Key and API Secret **API Key Registration**: Developers must register for an API key through Upstox Accounts - Developer Apps portal, which serves as the authentication mechanism for API requests. Goto the [Upstox Accounts - Developer Appsarrow-up-right](https://account.upstox.com/developer/apps) Portal and login with your upstox login credentials. Press Create New App and Enter the App name, Redirect the URL and select I accept the terms and conditions check box, and press the Done button ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FnT7v2eSVqOUtpiF2IxcF%252Fimage.png%3Falt%3Dmedia%26token%3D2d8f6382-6346-419c-a903-c79784972df3&width=768&dpr=3&quality=100&sign=88687c2a&sv=2) API Key and API Secret Key generated for the app OpenAlgo ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FOCgQMNQOprFm0lbAJXd5%252Fimage.png%3Falt%3Dmedia%26token%3D8aaaa3ff-2e71-472d-b0d5-548914fa99bc&width=768&dpr=3&quality=100&sign=1c1a4081&sv=2) Save the generated apikey and apisecret. Later we will be adding the apikey in the [environmental variablearrow-up-right](https://docs.openalgo.in/getting-started/windows-installation/environmental-variables) along with the redirect url Here is a sample of how the details would appear in a .env file for reference: Integrating OpenAlgo with Upstox'sAPI opens up possibilities for automated trading strategies, providing a powerful tool for traders and developers to exploit market opportunities efficiently. It's essential to follow best practices for API integration, including handling rate limits, managing API keys securely, and ensuring robust error handling and logging mechanisms are in place. [PreviousTradejinichevron-left](https://docs.openalgo.in/connect-brokers/brokers/tradejini) [NextWisdom Capitalchevron-right](https://docs.openalgo.in/connect-brokers/brokers/wisdom-capital) Last updated 11 months ago sun-brightdesktopmoon Copy BROKER_API_KEY = 'your_api_key_here' BROKER_API_SECRET = 'your_api_secret_here' REDIRECT_URL = 'http://127.0.0.1:5000/upstox/callback' sun-brightdesktopmoon --- # RMoney (XTS) | Documentation ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/rmoney-xts#rmoney-raghunandan-capital-pvt-ltd-broker-integration) RMoney - (Raghunandan Capital Pvt Ltd) Broker Integration RMoney is a Gandhinagar(Gujarat)-based deep discount broker that provides API access via the XTS (Symphony Fintech) platform. This guide will help you integrate RMoney with OpenAlgo. #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/rmoney-xts#step-1-create-api-applications) **Step 1: Create API Applications** Login to [https://xts.rmoneyindia.co.in:3000/dashboard#!/loginarrow-up-right](https://xts.rmoneyindia.co.in:3000/dashboard#!/login) ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Fs9SJtxcIoN2loBDoKjYe%252FRmoney9.png%3Falt%3Dmedia%26token%3D6283c05b-c26e-486f-a93b-9ec261c12eb5&width=768&dpr=3&quality=100&sign=236ca1eb&sv=2) Once logged in: 1. Go to `My App` > `Create New Application` 2. Create two separate apps: * **Interactive Order API** * **Market Data API** ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Fm6fBlM0rCtU1cdFvzpOd%252FRmoney4.png%3Falt%3Dmedia%26token%3Dc2f98a5e-bee6-433c-8cfc-7d1bec426474&width=768&dpr=3&quality=100&sign=4917d5&sv=2) **Details to Fill:** * **App Name**: OpenAlgo * **App Description**: OpenAlgo * **Redirect URL: (leave it empty)** * **Company Name**: OpenAlgo (or your own) * Choose the correct **API Package** depending on the app (Order or Market Data). ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FC9dSJDTZQ9yTnuiR7hJT%252FRmoney7.png%3Falt%3Dmedia%26token%3D17436660-fa84-46e4-923d-211957181f09&width=768&dpr=3&quality=100&sign=f1f67aae&sv=2) #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/rmoney-xts#step-2-setup-environment-variables) Step 2: Setup Environment Variables Refer to the `.sample.env` file in your OpenAlgo folder and prepare your `.env` as follows: Replace the values with actual credentials shown on your developer dashboard once approved. #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/rmoney-xts#step-3-start-openalgo) **Step 3: Start OpenAlgo** Once all environment variables are set and your apps are Active, you can now start OpenAlgo. Ensure you have installed dependencies and set up the broker configuration properly. OpenAlgo will now be able to place orders and fetch market data through RMoney's XTS API. This completes the integration process for RMoney broker with OpenAlgo. Integrating OpenAlgo with RMoney’s XTS API empowers traders and developers to automate and streamline their trading workflows with precision and speed. Users can build robust trading systems capable of reacting to market conditions in real time. Always ensure secure handling of API credentials, implement proper error handling, and monitor your integration to maintain reliability and compliance. [PreviousShoonyachevron-left](https://docs.openalgo.in/connect-brokers/brokers/shoonya) [NextTradejinichevron-right](https://docs.openalgo.in/connect-brokers/brokers/tradejini) Last updated 1 month ago sun-brightdesktopmoon Copy # Broker Configuration BROKER_API_KEY = 'YOUR_BROKER_ORDER_API_KEY' BROKER_API_SECRET = 'YOUR_ORDER_API_SECRET' BROKER_API_KEY_MARKET = 'YOUR_BROKER_MARKET_API_KEY' BROKER_API_SECRET_MARKET = 'YOUR_BROKER_MARKET_API_SECRET' REDIRECT_URL = 'http://127.0.0.1:5000/rmoney/callback' sun-brightdesktopmoon --- # Pre-Requesties | Documentation * **Mac OS 11** or Higher * Install **HomeBrew** * **Visual Studio Code (VS Code)** is installed. * **Python** version 3.10 or higher version installed * **Git** for cloning the repository (Download from terminal using the command brew install github). [PreviousMac OS Installationchevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation) [NextSetupchevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/setup) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Nubra | Documentation Nubra, by Zanskar Securities Private Limited, is a modern trading platform built for algorithmic and institutional traders. It provides REST-like resource-based endpoints with low-latency order execution, comprehensive market data access including quotes, Greeks, and historical candles, and secure MPIN-based authentication — making it an excellent choice for automated trading with OpenAlgo. 1. **Navigate** to the Nubra's Dashboard Login [https://nubra.io/arrow-up-right](https://nubra.io/) Open Demat ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F5Q7M7GA7JH2YSz4hfKI8%252Fnubra1.png%3Falt%3Dmedia%26token%3Da1fd8aac-ef47-4af4-a7c2-f6c8fd0a4770&width=768&dpr=3&quality=100&sign=ea9f746b&sv=2) 1. All REST requests require: 1. **API Key (client\_id)** 2. **MPIN-based session (MPIN → session token)** ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FKsfRqs59sVnFISMAhxpb%252Fnubra4.PNG%3Falt%3Dmedia%26token%3Dfbd0326a-8afa-4e8e-bb6a-d3b43b2bde27&width=768&dpr=3&quality=100&sign=a9eb165f&sv=2) 1. Click on the **Profile** icon located at the bottom-left corner of the page ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FntGm0GYkVyIDSpBj0Sly%252Fnubra5.PNG%3Falt%3Dmedia%26token%3D6ac7cdc6-1244-44f9-b18e-4d29ea33051e&width=768&dpr=3&quality=100&sign=a0f9a47d&sv=2) 1. Go to **API Credentials** and Select **Two-Factor Authentication**. ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/nubra#environment-configuration) **Environment Configuration** Once your credentials are generated, configure them in your `.env` file: Integrating with **Nubra APIs** unlocks the ability to automate strategies, execute trades, and analyze data directly within your own infrastructure. When used with **OpenAlgo**, you can self-host and run your entire algo trading stack — with full control and zero vendor lock-in. [PreviousMstockchevron-left](https://docs.openalgo.in/connect-brokers/brokers/mstock) [NextPaytmchevron-right](https://docs.openalgo.in/connect-brokers/brokers/paytm) Last updated 2 months ago sun-brightdesktopmoon Copy BROKER_API_KEY = 'your_nubra_clientid' BROKER_API_SECRET = 'your_nubra_mpin' REDIRECT_URL = 'http://127.0.0.1:5000/nubra/callback' sun-brightdesktopmoon --- # Groww | Documentation Groww is currently the #1 stockbroker in India by active clients, offering a seamless digital investing experience to millions of retail investors. With its recent launch of trading APIs, Groww has opened the door for developers and fintech platforms to integrate custom trading workflows. In the context of OpenAlgo integration, Groww’s trading APIs provide capabilities for automated order placement, real-time market data access, and custom strategy execution for retail traders. ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/groww#how-to-get-groww-api-key-and-secret) How to Get Groww API Key and Secret? ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FPvJlsjhUWTgG2T69z3b4%252Fimage.png%3Falt%3Dmedia%26token%3D8b8fcae4-34de-4574-ad2f-636a02719389&width=768&dpr=3&quality=100&sign=d17a0c30&sv=2) To integrate OpenAlgo with Groww, follow the steps below to generate your API key (access token): 1. Visit the [Groww Trade API Portalarrow-up-right](https://groww.in/trade-api) and click on **Getting Started**. 2. Login using your Groww account credentials. 3. Click the **Generate API Token** button to create APIKey and APISecret ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F8hGSrKXLCtHOwBmPUVo8%252Fgroww1.png%3Falt%3Dmedia%26token%3D99ef2ede-9cb4-40fe-be1c-c93177513679&width=768&dpr=3&quality=100&sign=22236621&sv=2) Click on the **Generate API Keys** ,Enter the Token Name as "OpenAlgo" or any name of your choice and press **continue** #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/groww#now-generate-the-generated-grow-api-key-and-api-secret-from-the-generate-api-key) Now Generate the generated Grow API Key and API Secret from the Generate API Key ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FWP5N879Dhm7z0CKHNeUp%252Fimage.png%3Falt%3Dmedia%26token%3D335ec8d6-957f-42f9-802b-a5f46a8b4c40&width=768&dpr=3&quality=100&sign=8d90a85f&sv=2) Click "**Add/Update Static IP**" next to Generate API Key ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FxY27rTJNFxFHVv2TibEj%252FGroww1.PNG%3Falt%3Dmedia%26token%3D94e7ee0d-42f3-4c8a-a4a4-78e61c96820d&width=768&dpr=3&quality=100&sign=8aecd047&sv=2) ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/groww#important-points) Important Points * Do **not share** your access token with untrusted third-party platforms or individuals. #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/groww#configuration) Configuration: Here is how you would typically set up your environment variables in a .env file for Groww's API: Integrating OpenAlgo with Groww's trading API allows retail traders to leverage India’s most popular stockbroking platform for building and deploying their own algorithmic trading strategies. It’s a powerful combination for automating trading decisions while using a broker trusted by millions. As with any integration, be sure to handle token management carefully, log errors effectively, and build retry mechanisms to handle token expiry and downtime. [PreviousFyerschevron-left](https://docs.openalgo.in/connect-brokers/brokers/fyers) [NextIIFL (XTS)chevron-right](https://docs.openalgo.in/connect-brokers/brokers/iifl-xts) Last updated 9 days ago * [How to Get Groww API Key and Secret?](https://docs.openalgo.in/connect-brokers/brokers/groww#how-to-get-groww-api-key-and-secret) * [Important Points](https://docs.openalgo.in/connect-brokers/brokers/groww#important-points) sun-brightdesktopmoon Copy BROKER_API_KEY = 'your_groww_apikey_here' BROKER_API_SECRET = 'your_groww_apisecret_here' REDIRECT_URL = 'http://127.0.0.1:5000/groww/callback' sun-brightdesktopmoon --- # Kotak Securities | Documentation Kotak Securities is a prominent Indian stock broker offering services on major Indian stock exchanges, including NSE, BSE, and MCX. Known for its comprehensive financial services and advanced trading solutions, Kotak Securities provides a robust platform for traders and investors. By leveraging Kotak's Trading APIs, developers and algo traders can seamlessly integrate their trading strategies with the OpenAlgo platform. For developers and algo traders looking to use the Kotak API, the integration process generally involves the following steps: ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/kotak-securities#step-by-step-integration) Step-by-Step Integration #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/kotak-securities#step-1-prepare-your-trading-credentials) Step 1: Prepare Your Trading Credentials Ensure you have your Kotak Securities Trading User ID and Password ready. #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/kotak-securities#step-2-register-for-api-access) Step 2: Register for API Access 1. Navigate to the [Kotak Securities API registration page.arrow-up-right](https://neo.kotaksecurities.com/) login with your trading credentials 2. Navigate to: Invest → TradeAPI → API Dashboard ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FfVRpmkMsIX9QgmjyCWhp%252Fimage.png%3Falt%3Dmedia%26token%3Dce9d4b01-1797-4e50-9141-8168b1f2b0d8&width=768&dpr=3&quality=100&sign=f5498ecf&sv=2) 1. Click "Create Application" 2. Copy the token shown after creation **Token format example**: ec6a746c-e44b-455e-abf2-c13352b2fc45 ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FYIZoKNUU4rcsCqFqSx0N%252Fimage.png%3Falt%3Dmedia%26token%3D4960b94b-4967-4200-84ec-d869757ac9a7&width=768&dpr=3&quality=100&sign=323e1af5&sv=2) #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/kotak-securities#step-3-register-totp-authentication) **Step 3: Register TOTP Authentication** Register for TOTP from the Menu Section ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FBBGLeF9mT6pz3AO53ZK5%252Fimage.png%3Falt%3Dmedia%26token%3D774ccaf7-eaef-4cf5-acbc-3ddb1dc11fe9&width=768&dpr=3&quality=100&sign=95cb341c&sv=2) **What is TOTP?** Time-based One-Time Password generates a new 6-digit code every 30 seconds in an authenticator app. This is your dynamic password for API login. **Steps:** 1. In API Dashboard, click **"TOTP Registration"** 2. Verify with your mobile number and OTP 3. Download **Google Authenticator** or **Microsoft Authenticator** from app store 4. Scan the QR code displayed on screen 5. Enter the 6-digit TOTP code shown in the authenticator app 6. Confirm when you see "TOTP successfully registered" Example: 1. TOTP Registration screen: on verification of mobile number, otp and client code ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Fz5Q6B85NbDnzBvIqhoIx%252Fimage%2520%281%29.png%3Falt%3Dmedia%26token%3Da23d4658-7d46-4b63-beb6-d83333600c1c&width=768&dpr=3&quality=100&sign=5e9a9c7d&sv=2) 1. Scan QR from authenticator app, Enter these 6 digits reflecting on authenticator app for Kotak-NEO, and click continue. You will get success toast which means registration of totp is complete. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FMyi7Qwi0tvEYMaAW5PAJ%252Fimage%2520%282%29.png%3Falt%3Dmedia%26token%3Db485a9e4-a8aa-435f-8b9b-b0e8df325aa1&width=768&dpr=3&quality=100&sign=caef9f&sv=2) #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/kotak-securities#step-4-find-your-ucc-client-code) Step 4: Find Your UCC (Client Code) 1. Go to NEO app/web Profile section 2. Your UCC is displayed as "Client Code" 3. Format: 5 characters (e.g., "AB123") ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Fi7dC0BFpleeocbS8pTTI%252Fimage.png%3Falt%3Dmedia%26token%3Dad9d4b79-7200-4a67-b446-280427616a2f&width=768&dpr=3&quality=100&sign=89930b5f&sv=2) #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/kotak-securities#step-5-your-6-digit-mpin) Step 5 : Your 6-digit MPIN * This is your trading PIN used to authorize orders in NEO app * You use the same MPIN for API authentication **If you don't remember it:** * NEO app → Profile → Settings → Change MPIN #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/kotak-securities#retrieve-api-credentials) Retrieve API Credentials: * Copy the Unique Client Code as Format: 5 characters (e.g., "AB123") , which will be your API Key. * Copy the Token generated from step 2 as Token format example: ec6a746c-e44b-455e-abf2-c13352b2fc45, which will serve as your API Secret ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/kotak-securities#configuration) Configuration: Set up your environment variables in a `.env` file for Kotak's API: Integrating with the Kotak API opens up new possibilities for implementing automated and algorithmic trading strategies. It provides developers and traders with a robust platform to access market opportunities efficiently and effectively. To fully leverage the capabilities of the Kotak API, it is essential to follow best practices for API integration. This includes careful management of API rate limits, secure handling of API keys, and thorough error handling and logging. These practices help ensure a dependable and optimal trading experience using Kotak's advanced technological infrastructure. [PreviousJainamXTSchevron-left](https://docs.openalgo.in/connect-brokers/brokers/jainamxts) [NextMotilal Oswalchevron-right](https://docs.openalgo.in/connect-brokers/brokers/motilal-oswal) Last updated 5 months ago * [Step-by-Step Integration](https://docs.openalgo.in/connect-brokers/brokers/kotak-securities#step-by-step-integration) * [Configuration:](https://docs.openalgo.in/connect-brokers/brokers/kotak-securities#configuration) sun-brightdesktopmoon Copy BROKER_API_KEY = 'your_kotak_unique_client_code' BROKER_API_SECRET = 'your_kotak_token_generated' REDIRECT_URL = 'http://127.0.0.1:5000/kotak/callback' sun-brightdesktopmoon --- # Motilal Oswal | Documentation Motilal Oswal Financial Services Limited (MOFSL) is one of India's leading financial services companies, offering a comprehensive suite of investment and trading services. Their API platform provides developers and algo traders with programmatic access to trading capabilities including order placement, portfolio management, and market data. OpenAlgo seamlessly integrates with Motilal Oswal's API, enabling you to execute automated trading strategies across equity, derivatives, currency, and commodity segments. ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/motilal-oswal#getting-api-credentials) **Getting API Credentials** #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/motilal-oswal#step-1-access-the-api-portal) **Step 1: Access the API Portal** Visit the Motilal Oswal OpenAPI registration portal: [https://invest.motilaloswal.com/moAPI/arrow-up-right](https://invest.motilaloswal.com/moAPI/) #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/motilal-oswal#step-2-register-your-application) **Step 2: Register Your Application** 1. Log in with your Motilal Oswal trading credentials ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FcVfR8AbikZiPBrMx60Wz%252Fmot_1.PNG%3Falt%3Dmedia%26token%3D2249e2a0-f0b2-4cb2-ae80-3fda60efc7d8&width=768&dpr=3&quality=100&sign=c24680eb&sv=2) ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FoQHc2G1LDqw7VmXgPCxU%252Fmot_2.PNG%3Falt%3Dmedia%26token%3Dae3f01d4-e39b-4c29-85e3-95cd8a8a0b27&width=768&dpr=3&quality=100&sign=8f5c8ff6&sv=2) 1. Navigate to **My APIs** ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FKdBN2ml34ZtuiIXvYsOf%252FMot_4.PNG%3Falt%3Dmedia%26token%3De394449f-a118-47e4-b37a-cef9566bb8d1&width=768&dpr=3&quality=100&sign=f47e1088&sv=2) 1. Set Up TOTP - Copy the 32-character secret key and Add this key to your preferred authenticator app 2. Click on **Create on API Key** ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FcVPJ3cQ5MhzI7PfMO1M1%252Fmot_3.PNG%3Falt%3Dmedia%26token%3D818b0817-5c14-473b-a1c6-0a4f6bc0cf27&width=768&dpr=3&quality=100&sign=82d89a1d&sv=2) 1. Fill in the required details: * **App Name:** Your application name (e.g., "OpenAlgo Trading") * **Redirect URL:** `http://127.0.0.1:5000/motilal/callback` 1. Submit the registration #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/motilal-oswal#step-3-obtain-your-api-key) **Step 3: Obtain Your API Key** * Your trading account number or Client Code will be your API Key. * Copy the API Key generated and use as your API Secret #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/motilal-oswal#configuration) **Configuration** Set up your environment variables in a `.env` file for motilal's : Integrating with M**otilal APIs** unlocks the ability to automate strategies, execute trades, and analyze data directly within your own infrastructure. When used with **OpenAlgo**, you can self-host and run your entire algo trading stack — with full control and zero vendor lock-in. [PreviousKotak Securitieschevron-left](https://docs.openalgo.in/connect-brokers/brokers/kotak-securities) [NextMstockchevron-right](https://docs.openalgo.in/connect-brokers/brokers/mstock) Last updated 5 months ago sun-brightdesktopmoon Copy # Motilal Oswal API Configuration BROKER_API_KEY = 'your_client_code' #Use your client code as api key BROKER_API_SECRET = 'your_api_key_here' #Use your generated API Key as API secret in .env file sun-brightdesktopmoon --- # Paytm | Documentation **Paytm Money** is a technology-first investment platform backed by one of India’s leading fintech companies. With its secure and scalable API infrastructure, Paytm Money empowers developers and traders to build powerful trading systems that can manage portfolios, place real-time orders, and stream live market data with ease. Whether you're building retail trading applications or complex algorithmic strategies, Paytm Money offers a reliable and developer-friendly gateway to the markets. * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/paytm#step-1-create-app) Step 1: Create App 1. Go to [Paytm Developer Portalarrow-up-right](https://developer.paytmmoney.com/) 2. Click on **Create New App** 1. Choose the following APIs: * ✅ **Trading API** * ✅ **Live Broadcast API** (optional, but recommended for real-time data) ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F45T8OspqqKeeYoBl0DZC%252Fimage.png%3Falt%3Dmedia%26token%3De52834b5-fc5e-469a-b71c-1b3baec26a25&width=768&dpr=3&quality=100&sign=3396f92c&sv=2) 2. Click **Proceed** ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F6wGHqktfiZklAzMnCOOD%252Fimage.png%3Falt%3Dmedia%26token%3D473cdfb3-0a22-4d7c-85c7-1dada3069315&width=768&dpr=3&quality=100&sign=146c6ddd&sv=2) * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/paytm#step-2-enter-app-details) Step 2: Enter App Details Fill out the app details as shown below: * **App Name:** `openalgo` * **Product Type:** `Trading Bridge` * **Redirect URL:** `http://127.0.0.1:5000/paytm/callback` * **Postback URL:** _(leave empty)_ * **Description:** `openalgo` * Upload a logo (optional) ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F27kGXJwtkXD4smGUmvdN%252Fimage.png%3Falt%3Dmedia%26token%3D6a2c04d3-d4df-4f2f-aa59-f56993b082cc&width=768&dpr=3&quality=100&sign=c138dbe9&sv=2) Click **Create App** * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/paytm#step-3-copy-api-key-and-secret) Step 3: Copy API Key and Secret Once your app is in **Active** status: 1. Go to **My Apps** 2. Locate your app (e.g., `openalgo`) 3. Copy the **API Key** and **API Secret** ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F6GZdwVqycqZHPc3GCrMY%252Fimage.png%3Falt%3Dmedia%26token%3D0e7ea5d2-374b-4eae-8982-75bcff0fd419&width=768&dpr=3&quality=100&sign=8d125a98&sv=2) Use these credentials in your OpenAlgo broker configuration. * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/paytm#configuration) Configuration Once you have the credentials, add them to your OpenAlgo configuration: Make sure your local server is running and accessible at the callback URL you defined earlier. * * * #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/paytm#whats-next) What's Next? Integrating with the Paytm Money API opens the door to building high-performance, automated trading workflows within the OpenAlgo ecosystem. To ensure seamless integration and performance, it’s essential to follow recommended practices such as securely storing your API credentials, managing session states effectively, and implementing robust logging and error-handling routines. With the right setup, Paytm Money becomes a dependable backbone for executing your trading strategies with precision and confidence. * * * [PreviousNubrachevron-left](https://docs.openalgo.in/connect-brokers/brokers/nubra) [NextPocketfulchevron-right](https://docs.openalgo.in/connect-brokers/brokers/pocketful) Last updated 1 year ago * [Step 1: Create App](https://docs.openalgo.in/connect-brokers/brokers/paytm#step-1-create-app) * [Step 2: Enter App Details](https://docs.openalgo.in/connect-brokers/brokers/paytm#step-2-enter-app-details) * [Step 3: Copy API Key and Secret](https://docs.openalgo.in/connect-brokers/brokers/paytm#step-3-copy-api-key-and-secret) * [Configuration](https://docs.openalgo.in/connect-brokers/brokers/paytm#configuration) sun-brightdesktopmoon Copy BROKER_API_KEY = 'your_api_key_here' BROKER_API_SECRET = 'your_api_secret_here' REDIRECT_URL = 'http://127.0.0.1:5000/paytm/callback' sun-brightdesktopmoon --- # Samco | Documentation Samco Securities is a leading discount broker in India offering equity, derivatives, commodity, and currency trading. Samco Trade API is a powerful RESTful API that allows traders to build customized trading applications, automate their strategies, and integrate with various algorithmic trading platforms. ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/samco#steps-for-integration) **Steps for Integration** #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/samco#step-1-login-to-samco-website) **Step 1: Login to Samco website** Visit [https://web.samco.in/arrow-up-right](https://web.samco.in/) and login with your client ID/Mobile number. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FdSI2FsJ9GxwySNGTqOQc%252Fsam_1.PNG%3Falt%3Dmedia%26token%3D42fd17f0-c57b-4e9a-8dd2-7365626625cc&width=768&dpr=3&quality=100&sign=b707d51&sv=2) **Step 2: Navigate to Login to Back Office** From the dashboard, navigate to the profile dropdown and then to Login to Back Office ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FuO8DiWXSMSnXFuA7aT5F%252Fsam_5.png%3Falt%3Dmedia%26token%3D23a50061-33de-4a86-9791-12a4f12bd568&width=768&dpr=3&quality=100&sign=2ecc18a6&sv=2) #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/samco#step-3-activate-trade-api) **Step 3: Activate Trade API** Navigate to subscription menu , Samco Trade API ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Fya7b4iQGwdDXnckX5CAm%252Fsam_3.png%3Falt%3Dmedia%26token%3D2330f197-c6f2-467e-90b3-7fc25a99d58f&width=768&dpr=3&quality=100&sign=9f3da576&sv=2) Now activate your subscription ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FBi8EgGaInUa2SNaPNSP9%252Fsam_4.PNG%3Falt%3Dmedia%26token%3Deaa0fbb0-81a1-40b6-b112-b1f22fd8dadc&width=768&dpr=3&quality=100&sign=5b76ab16&sv=2) #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/samco#step-4-environment-configuration) **Step 4 :** **Environment Configuration** After activating Samco Trade API , configure your samco login crdentials in .env file #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/samco#step-5-process-of-static-ip-whitelisting) Step 5 : Process of Static IP Whitelisting When you select Samco from the broker selection page, you will see a multi-step wizard with four steps: ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FNQ5c1gqntqPlKMkZLA1w%252Fsamco1.png%3Falt%3Dmedia%26token%3De4a79bda-2606-4a89-aac1-65bbba346e28&width=768&dpr=3&quality=100&sign=487a25ff&sv=2) **Step A : Generate OTP** 1. Click the Send OTP button 2. An OTP will be sent to your registered mobile number and email 3. Enter the OTP you received and click Generate Secret Key **Note :**If you have already completed the one-time setup before, this step will show a warning that a Secret API Key is already saved. You only need to repeat this step if you want to generate a new secret key. **Step B : Save Secret API Key** ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Fc3OszRuiz9ZiBsic30Eu%252Fsamco2.png%3Falt%3Dmedia%26token%3D1daf6b68-55b7-4122-a4f6-eabf33082ea4&width=768&dpr=3&quality=100&sign=8dbf8421&sv=2) 1. After entering the OTP, Samco will send a Secret API Key to your registered email 2. Open your email, copy the Secret API Key 3. Paste it in the input field and click Save Secret Key ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FxHMyWBAe7WiGfqbDmscg%252Fsamco3.png%3Falt%3Dmedia%26token%3D4da45075-9635-4395-9a6a-a6f15a38ce30&width=768&dpr=3&quality=100&sign=8ba876e&sv=2) **Important:** The Secret API Key never expires. Keep it secure and do not share it with anyone. You only need to do this step once. If you generate a new OTP and create a new secret key, you must update the saved key as well. **Step 3: IP Management** ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Ftuz1la3sJZYQ4rtNg0Tq%252Fsamco4.png%3Falt%3Dmedia%26token%3Dafd69308-f047-4808-9331-3da6a53c42c4&width=768&dpr=3&quality=100&sign=a8465988&sv=2) 1. Enter your server's Primary IP Address (the static IP of the machine running OpenAlgo) 2. Optionally enter a Secondary IP Address as a backup 3. Click Register IP (or Update IP if already registered) 4. A confirmation dialog will appear before submitting **IP Update Restriction:** Samco allows IP changes only once per calendar week. If you have already updated your IP this week, the fields will be locked and a message will show the next available edit date. Make sure you enter the correct IP before confirming. **Note:** Only IPv4 addresses are supported. After registration, Samco will reject API requests from any IP address that is not registered. **Step D: Login** ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FutNZYJiKcvqRtHg9Ofrs%252Fsamco5.png%3Falt%3Dmedia%26token%3D10490f07-33f1-43f2-9bc6-d99528478159&width=768&dpr=3&quality=100&sign=1e1bdeb3&sv=2) 1. Click Login to Samco 2. OpenAlgo will automatically generate an access token using your stored Secret API Key and log you in 3. On success, you will be redirected to the Trading Dashboard **Daily Login** Once the one-time setup is complete (Steps 1-3), your daily login is simple: 1. Select Samco from the broker selection page 2. The wizard will skip directly to the IP Management step (showing your registered IPs) 3. Click Continue to Login, then click Login to Samco 4. You will be logged in and redirected to the dashboard **Troubleshooting** Problem Solution OTP not received Check your registered mobile and email. Wait a minute and try Resend OTP. Secret API Key email not received Check your spam/junk folder. The OTP and secret key use different not received email services. Wait a few minutes. "Secret key does not match" The saved key may be incorrect. Go to Step 1, generate a new OTP, match" get a fresh secret key from email, and save it again. "The IP is not the registered static IP" Your server's public IP does not match what is registered with registered static IP" Samco. Check your server's IP and update it in Step 3 (if the weekly lock has expired). IP fields are locked IPs can only be updated once per calendar week. Wait until the date shown in the warning message. "Failed to save secret API key" Make sure you are logged into OpenAlgo first (via the login page) before starting the Samco auth wizard. Integrating with Samco **APIs** unlocks the ability to automate strategies, execute trades, and analyze data directly within your own infrastructure. When used with **OpenAlgo**, you can self-host and run your entire algo trading stack — with full control and zero vendor lock-in. [PreviousPocketfulchevron-left](https://docs.openalgo.in/connect-brokers/brokers/pocketful) [NextShoonyachevron-right](https://docs.openalgo.in/connect-brokers/brokers/shoonya) Last updated 22 days ago sun-brightdesktopmoon Copy BROKER_API_KEY = 'your_samco_clientid' BROKER_API_SECRET = 'your_samco_password' REDIRECT_URL = 'http://127.0.0.1:5000/sao/callback' sun-brightdesktopmoon --- # Start OpenAlgo | Documentation From the `openalgo` directory, start the Flask application with the command: `python3 app.py` ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FdeF5SKFXgSRdQDir9moa%252Frunning%2520openalgo.png%3Falt%3Dmedia%26token%3D899d8453-4b7b-4604-8bb2-0fa1cfa190d6&width=768&dpr=3&quality=100&sign=202ad11d&sv=2) [PreviousEnvironmental Variableschevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/environmental-variables) [NextInstall certifichevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/install-certifi) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Setup | Documentation #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/setup#setup) Setup 1. **Install VS Code Extensions**: Open VS Code, navigate to the Extensions section on the left tab, and install the Python, Pylance, and Jupyter extensions. 2. **Clone the Repository**: Open the VS Code Terminal and clone the OpenAlgo repository with the command: `git clone` [`https://github.com/marketcalls/openalgo`arrow-up-right](https://github.com/marketcalls/openalgo) ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F0PPG2JmmogRyFc5VrGaG%252FOpenAlgo%2520Github%2520Clone.png%3Falt%3Dmedia%26token%3D7da94b2c-988e-43c9-9144-2a44222e17db&width=768&dpr=3&quality=100&sign=c4f40028&sv=2) [PreviousPre-Requesiteschevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/pre-requesites) [NextInstall Dependencieschevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/install-dependencies) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # IndMoney (INDstocks) | Documentation IndMoney (INDstocks) is a modern trading infrastructure platform offering APIs that allow traders and developers to build, automate, and execute trading strategies. Using IndMoney APIs, users can connect their IndMoney trading account with tools like **OpenAlgo** and create their own fully self-hosted, secure algo-trading setup. ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/indmoney#steps-for-integration) Steps for Integration IndMoney uses a simple **Bearer Token** authentication model. To generate a token: Visit [**https://www.indstocks.com/app/api-trading**arrow-up-right](https://www.indstocks.com/app/api-trading) ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FFbkuola8t67Vhw8xQ8Zk%252Find1.PNG%3Falt%3Dmedia%26token%3De4018403-7525-42b0-9b5f-6946e7a00266&width=768&dpr=3&quality=100&sign=f2af583f&sv=2) 1. Enter your registered mobile number and login with the help of OTP ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FYNZr5XiEuI7KKui7TnI5%252Find2.PNG%3Falt%3Dmedia%26token%3D8753b80b-5490-422a-ae39-720e9b48a99f&width=768&dpr=3&quality=100&sign=c7d5435a&sv=2) 1. Open the **API Dashboard** ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FN29YHHOUxrURK9TtqFDO%252Find5.PNG%3Falt%3Dmedia%26token%3Dd763994b-caf1-46bd-bcdf-c1f511559026&width=768&dpr=3&quality=100&sign=55d6350a&sv=2) 1. Click **New Token** and generate token ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FrOwpMjZd0i0PiZNg97BP%252Find3.PNG%3Falt%3Dmedia%26token%3Dc16de7ac-be48-480c-a67a-d1e1e2262b27&width=768&dpr=3&quality=100&sign=a1330cf&sv=2) 1. Copy the token shown on screen This token will be used in OpenAlgo for all authenticated API requests. **Note:** Tokens usually expire within **24 hours**. You must generate a fresh token when expired. 1. **Setup Static IP:** Click the small **hexagon icon** next to **New Token** to enable and assign your **static IP**, and then save it. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FLCT7OTEYeaGC9AtPDdfD%252Find4.PNG%3Falt%3Dmedia%26token%3De2b54b71-cccf-437f-b2ad-dfae7612ee83&width=768&dpr=3&quality=100&sign=10381aba&sv=2) **Note :**A static IP is mandatory, and it must be whitelisted for all API calls to work. Without whitelisting, INDmoney will reject your API requests. ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/indmoney#environment-configuration) Environment Configuration The generated access token is used as the API SECRET and keep any dummy variable as API KEY. Below is a sample configuration for the `.env` file: Integrating OpenAlgo with Indmoney's API opens up possibilities for automated trading strategies, providing a powerful tool for traders and developers to exploit market opportunities efficiently. It's essential to follow best practices for API integration, including handling rate limits, managing API keys securely, and ensuring robust error handling and logging mechanisms are in place. [PreviousIIFL (XTS)chevron-left](https://docs.openalgo.in/connect-brokers/brokers/iifl-xts) [NextIndiaBulls Securitieschevron-right](https://docs.openalgo.in/connect-brokers/brokers/indiabulls-securities) Last updated 5 months ago * [Steps for Integration](https://docs.openalgo.in/connect-brokers/brokers/indmoney#steps-for-integration) * [Environment Configuration](https://docs.openalgo.in/connect-brokers/brokers/indmoney#environment-configuration) sun-brightdesktopmoon Copy # Indmoney Broker Configuration BROKER_API_KEY = 'wxyz123' #any dummy key BROKER_API_SECRET = 'your_generated_access_token' REDIRECT_URL = 'http://127.0.0.1:5000/indmoney/callback' sun-brightdesktopmoon --- # HouseOfFoss | Documentation * * * [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss#installing-openalgo-in-the-cloud-with-house-of-foss) 🧩 Installing OpenAlgo in the Cloud with House of FOSS ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss#overview) Overview You can now install **OpenAlgo**, the 100% open-source algorithmic trading platform, directly in the cloud - with just **one click** — using [**House of FOSS**arrow-up-right](https://www.houseoffoss.com/) . No complex setups. No manual server configuration. Just pure **self-hosted freedom**. House of FOSS provides a platform to install and manage open-source software just like SaaS — but you **own everything**. It’s designed for developers, traders, and startups who want full control without worrying about backend infrastructure. * * * ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss#id-1.-what-is-house-of-foss) 1\. What is House of FOSS? **House of FOSS** is a managed open-source software platform. It allows you to deploy and run applications like OpenAlgo, Excalidraw, or Anything LLM with a single click. You don’t need any knowledge of Linux, Docker, or cloud setup — House of FOSS takes care of: * Installation * SSL and domain management * Backups * Updates * Scaling You just choose the app, give it a name, and launch it. * * * ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss#id-2.-getting-started) 2\. Getting Started 1. Visit [**houseoffoss.com**arrow-up-right](https://www.houseoffoss.com/) . 2. Click on **“Get Started”**. 3. Log in or create your workspace. 4. In your workspace, go to **Search** and type **“Open Algo”**. 5. Select the app from the search results. 6. Enter a reference name (e.g., `openalgo`). 7. Click **Launch Application**. Within a few minutes, House of FOSS will automatically: * Create the instance * Deploy OpenAlgo * Configure networking and SSL After installation, you can click **“Visit Application”** to access OpenAlgo. * * * ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss#id-3.-initial-configuration) 3\. Initial Configuration After the instance is live, allow **2–3 minutes** for backend configuration. Then go to: * **View Application → Config** This section is where you’ll add your **broker API credentials as per the openalgo broker config docs**. * * * ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss#id-4.-performance-and-latency-considerations) 4\. Performance and Latency Considerations OpenAlgo performs best when hosted **close to the exchange region**. If you’re trading on Indian exchanges (like NSE or MCX), choose the **Mumbai region** while deploying in House of FOSS for lower latency and faster order execution. * * * ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss#id-5.-requested-enhancements-from-the-community) 5\. Requested Enhancements from the Community We’ve suggested a few improvements to House of FOSS for traders: Feature Description Status **Mumbai Region Hosting** Hosting near exchange to reduce latency. 🔄 Planned **Static IP Support** Required for broker whitelisting. 🔄 Under consideration **Custom Domain Mapping** Use personal domains like `myalgo.houseoffoss.net`. 🔄 Planned * * * ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss#id-6.-why-house-of-foss) 6\. Why House of FOSS? * One-click deployment for OpenAlgo and other open-source tools. * No server management — everything is automated. * Pay only for **usage**, not monthly subscription. * 100% open-source and self-hosted — **you own the data and code**. * * * ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss#id-7.-conclusion) 7\. Conclusion With **House of FOSS**, deploying OpenAlgo is as easy as clicking a button. You get: * Self-hosted control * Free forever open-source trading infrastructure * Broker integrations * TradingView automation support Whether you’re a trader, developer, or algo enthusiast — this setup gives you the same power as a professional cloud deployment with minimal effort. * * * #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss#useful-links) 🔗 Useful Links * 🌐 [House of FOSSarrow-up-right](https://www.houseoffoss.com/) * 💻 [OpenAlgo GitHubarrow-up-right](https://github.com/marketcalls/openalgo) * 💬 [Join Discord Communityarrow-up-right](https://openalgo.in/discord) [PreviousAmazon Elastic Beanstalkchevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/amazon-elastic-beanstalk) [NextUbuntu (No Custom Domain)chevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-no-custom-domain) Last updated 6 months ago * [🧩 Installing OpenAlgo in the Cloud with House of FOSS](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss#installing-openalgo-in-the-cloud-with-house-of-foss) * [Overview](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss#overview) * [1\. What is House of FOSS?](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss#id-1.-what-is-house-of-foss) * [2\. Getting Started](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss#id-2.-getting-started) * [3\. Initial Configuration](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss#id-3.-initial-configuration) * [4\. Performance and Latency Considerations](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss#id-4.-performance-and-latency-considerations) * [5\. Requested Enhancements from the Community](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss#id-5.-requested-enhancements-from-the-community) * [6\. Why House of FOSS?](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss#id-6.-why-house-of-foss) * [7\. Conclusion](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss#id-7.-conclusion) sun-brightdesktopmoon sun-brightdesktopmoon --- # TOTP Configuration | Documentation Once you logged into openalgo for the first time. goto Profile -> My Profile and select the tab TOTP Authentication This procedure is easier when compared to [SMTP Settings](https://docs.openalgo.in/installation-guidelines/getting-started/smtp-settings) ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/totp-configuration#steps-to-reset-your-openalgo-credentials-using-authenticator-app) Steps to Reset your openalgo credentials using Authenticator App 1)Launch your Google Authenticator or any other trusted authenticator and Scan the QR Code or enter the QR token ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F9oUMm4f2fNOTW5x4Jdc5%252Fimage.png%3Falt%3Dmedia%26token%3D709886a7-ba83-4000-826e-d1efa3b6cc9c&width=768&dpr=3&quality=100&sign=7e1a4e9f&sv=2) 2)and when you want to reset your password if in case you forgot password then from the login page goto forgot password and enter your registered email and press continue ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FK2wTXdPnPJPsQJlxfeHy%252Fimage.png%3Falt%3Dmedia%26token%3Dd6762f19-7536-41e4-82a7-39134ece8842&width=768&dpr=3&quality=100&sign=f2b66933&sv=2) 3)select the verification method as Authenticator App (TOTP) ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FrlLWvYoQlzt7TVunInml%252Fimage.png%3Falt%3Dmedia%26token%3Dc8914d91-9a78-41ae-b0f1-47a1a84df201&width=768&dpr=3&quality=100&sign=43b24bc1&sv=2) 4)Enter the 6 digit TOTP from your Authenticator App ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FX4zFhWpi0drf3D4unYQ5%252Fimage.png%3Falt%3Dmedia%26token%3Dc0697b52-8efe-4fb9-8f11-82b15e9eb6f3&width=768&dpr=3&quality=100&sign=d80d4880&sv=2) 5)reset with the new password ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FdNARG1q5tqpYpfMOnnED%252Fimage.png%3Falt%3Dmedia%26token%3D8ca4b56b-595f-4e46-8f46-ce2715654c26&width=768&dpr=3&quality=100&sign=55f37088&sv=2) 6)now login with your newer credentials and start using openalgo [PreviousSMTP Settingschevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/smtp-settings) [NextForgot Passwordchevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/forgot-password) Last updated 8 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # V1 | Documentation OpenAlgo API is a set of **REST APIs** that provide integration with multiple brokers with which you can build your own customized trading applications [hashtag](https://docs.openalgo.in/api-documentation/v1#endpoint-url) Endpoint URL --------------------------------------------------------------------------------------- Copy Local Host : http://127.0.0.1:5000/api/v1/placeorder Ngrok Domain : https://.ngrok-free.app/api/v1/placeorder Custom Domain: https:///api/v1/placeorder [PreviousThemeschevron-left](https://docs.openalgo.in/installation-guidelines/themes) [NextAccounts APIchevron-right](https://docs.openalgo.in/api-documentation/v1/accounts-api) Last updated 2 years ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Mstock | Documentation MStock is a modern Indian stock broker by Mirae Asset, offering commission-free trading and robust REST-based APIs. These APIs enable traders and developers to automate trading, retrieve account information, and integrate market data seamlessly. By connecting mStock OpenAPI with OpenAlgo, algo traders can efficiently execute strategies, manage positions, and automate workflows. For developers and algo traders looking to use the mStock API, the integration process involves the following steps: ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/mstock#step-by-step-integration) **Step-by-Step Integration** #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/mstock#step-1-prepare-your-trading-credentials) **Step 1: Prepare Your Trading Credentials** Ensure you have your mStock **Client Code** (Login ID) and **Trading Password** ready. You will also need access to your registered mobile number/email for OTP verification unless TOTP is enabled. #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/mstock#step-2-register-for-api-access) **Step 2: Register for API Access** mStock provides API access via its OpenAPI portal. * Visit the API Key genration website: [**https://www.mstock.com/trading-api**arrow-up-right](https://www.mstock.com/trading-api) ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FTbo3BJRSGunHcZD9TSeC%252F2ms.PNG%3Falt%3Dmedia%26token%3Da24c2898-9164-4523-8383-73cc4fa3b411&width=768&dpr=3&quality=100&sign=42d0445e&sv=2) * Log in using your trading account credentials. * **Open Menu** - Click on the hamburger menu icon located at the top-left corner of the screen. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FCL6VTyOImgCPdeb84l5Q%252F4ms.PNG%3Falt%3Dmedia%26token%3Dbba067b4-c987-4c0c-a8f6-b72b2bb5034d&width=768&dpr=3&quality=100&sign=4d2b5f56&sv=2) * **Navigate to Trading APIs** - In the menu, go to **Products** - Then click on **Trading APIs** ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F5qhLGKwXRMmDcEtKpA0u%252F5ms.PNG%3Falt%3Dmedia%26token%3D28ee039b-56e2-43bb-9570-46ce1b0211c4&width=768&dpr=3&quality=100&sign=b28b1a40&sv=2) * Click **Generate New API Key** and give API Type as Type B. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FfqiWwfzS5DS66Pudoy4e%252F6ms.png%3Falt%3Dmedia%26token%3D6565feb7-d71f-4a6e-8957-703f66399c49&width=768&dpr=3&quality=100&sign=7b55e840&sv=2) * **Enable TOTP** - You will see an option labeled "Generate TOTP" - Click on it to begin the TOTP setup process * Copy your API Key. #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/mstock#retrieve-api-credentials) **Retrieve API Credentials:** * Your trading account number or Client Code will be your API Key. * Copy the API Key generated and use as your API Secret #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/mstock#configuration) Configuration: Set up your environment variables in a `.env` file for mstock's API: Integrating with **mstock APIs** unlocks the ability to automate strategies, execute trades, and analyze data directly within your own infrastructure. When used with **OpenAlgo**, you can self-host and run your entire algo trading stack — with full control and zero vendor lock-in. [PreviousMotilal Oswalchevron-left](https://docs.openalgo.in/connect-brokers/brokers/motilal-oswal) [NextNubrachevron-right](https://docs.openalgo.in/connect-brokers/brokers/nubra) Last updated 5 months ago sun-brightdesktopmoon Copy BROKER_API_KEY = 'your_mstock_unique_client_code' BROKER_API_SECRET = 'your_mstock_api_key_generated' REDIRECT_URL = 'http://127.0.0.1:5000/mstock/callback' sun-brightdesktopmoon --- # SSL Verification Failed | Documentation If you’ve encountered the SSL: CERTIFICATE\_VERIFY\_FAILED error while using OpenAlgo on Windows, there’s good news. A user from the OpenAlgo community has shared a comprehensive solution that resolved this issue on their Windows system. Here’s a detailed guide on how to implement this solution. **Understanding the Issue** The SSL: CERTIFICATE\_VERIFY\_FAILED error usually indicates that the SSL certificate presented by the server cannot be verified by the client. This can happen due to several reasons, including outdated or missing root certificates on your system. **Proposed Solution** A user successfully resolved this issue by updating the root certificates on their Windows system. The solution involves using the certutil tool to update and install root certificates. Here are the detailed steps: **1\. Update Certificates Using Certutil** First, you need to update the root certificates on your Windows system. Follow these steps using Command Prompt with administrative access: 1\. **Open Command Prompt with Admin Access**: Right-click on the Command Prompt icon and select “Run as administrator”. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FMjG8v3CmcbGHxuDZHnnU%252Fimage.png%3Falt%3Dmedia%26token%3D714276c4-1315-466f-b07b-a414ee7c87cf&width=768&dpr=3&quality=100&sign=4c21aa6e&sv=2) 2\. **Generate Root Certificates File**: Run the following command to generate the root certificates file. 3\. **Install Root Certificates**: Once the roots.sst file is generated, run the following command to install the certificates. **2\. Verify and Reinstall** After updating the root certificates, you can verify if the issue is resolved by running your OpenAlgo application. Here’s an additional step-by-step verification process shared by the user: 1\. **Uninstall Existing Python Installation**: If you still face issues, uninstall the existing Python installation. 2\. **Reboot the Server**: Reboot your Windows system to ensure all changes take effect. 3\. **Install Latest Python Version**: Download and install the latest version of Python (e.g., python-3.12.4-amd64). 4\. **Run OpenAlgo Application**: Run your OpenAlgo application to verify if the SSL error is resolved. By updating the root certificates using certutil and ensuring that your system has the latest Python installation, you can resolve the SSL: CERTIFICATE\_VERIFY\_FAILED error on Windows systems. This method has been tested and confirmed to work by couple of users in the OpenAlgo community. For more details and context, you can refer to [this issue on GitHubarrow-up-right](https://github.com/marketcalls/openalgo/issues/43) . If you’re encountering SSL-related errors on Windows, give these Command Prompt actions a try. Your feedback and experiences are valuable, so feel free to share them in the comments below. Happy coding with OpenAlgo! [PreviousStart OpenAlgochevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/start-openalgo) [NextAccessing OpenAlgochevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/accessing-openalgo) Last updated 1 year ago sun-brightdesktopmoon Copy certutil -generateSSTFromWU roots.sst Copy certutil -addstore -f root roots.sst sun-brightdesktopmoon --- # Mac OS Installation | Documentation [PreviousWindows Server Installationchevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/windows-server-installation) [NextPre-Requestieschevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/pre-requesties) Last updated 3 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Windows Installation | Documentation This section provides OpenAlgo Installation Guideline for Windows Users [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation#how-to-configure-ngrok-for-openalgo-to-automate-tradingview-strategies) How to Configure Ngrok for OpenAlgo to Automate Tradingview Strategies --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation#how-to-upgrade-openalgo-to-latest-version) How to Upgrade OpenAlgo to Latest Version ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [PreviousGetting Startedchevron-left](https://docs.openalgo.in/installation-guidelines/getting-started) [NextPre-Requesiteschevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/pre-requesites) Last updated 4 months ago * [How to Configure Ngrok for OpenAlgo to Automate Tradingview Strategies](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation#how-to-configure-ngrok-for-openalgo-to-automate-tradingview-strategies) * [How to Upgrade OpenAlgo to Latest Version](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation#how-to-upgrade-openalgo-to-latest-version) sun-brightdesktopmoon sun-brightdesktopmoon --- # Setup | Documentation #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/setup#setup) Setup 1. **Install VS Code Extensions**: Open VS Code, navigate to the Extensions section on the left tab, and install the Python, Pylance, and Jupyter extensions. 2. **Clone the Repository**: Open the VS Code Terminal , open folder where you want to download and clone the OpenAlgo repository with the command: `git clone` [`https://github.com/marketcalls/openalgo`arrow-up-right](https://github.com/marketcalls/openalgo) ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FQEnksLtRY1cUzNMdMQyz%252FClone%2520OpenAlgo.png%3Falt%3Dmedia%26token%3D51eb4be1-84f1-4eed-a571-0ec2a95a56fb&width=768&dpr=3&quality=100&sign=2bcc254b&sv=2) [PreviousPre-Requestieschevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/pre-requesties) [NextInstall Dependencieschevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/install-dependencies) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # JainamXTS | Documentation ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/jainamxts#jainam-xts-broker-integration) **Jainam XTS Broker Integration** OpenAlgo makes algorithmic trading accessible and straightforward by providing seamless integration with various brokers, including JainamXTS API. This documentation will guide you through the process of configuring your jainamxts account to work with OpenAlgo #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/jainamxts#step-1-create-api-applications) **Step 1: Create API Applications** Login to [https://jtrade.jainam.in:5000/dashboard#!/loginarrow-up-right](https://jtrade.jainam.in:5000/dashboard#!/login) ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FUphc2WtBkqRCyUvhkhTz%252Fjaianam1.PNG%3Falt%3Dmedia%26token%3D0f826a7c-4c5a-4eee-9169-1f42fac20cad&width=768&dpr=3&quality=100&sign=54858b45&sv=2) Once logged in: 1. Go to `My App` > `Create New Application` 2. Create two separate apps: * **Interactive Order API** * **Market Data API** ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FpMHB47eWPjYsnk0R5M7I%252FWhatsApp%2520Image%25202025-12-05%2520at%252012.21.12%2520PM.jpeg%3Falt%3Dmedia%26token%3D0349fe96-27b9-42be-b6b3-48a3c43a9be8&width=768&dpr=3&quality=100&sign=a2c198a6&sv=2) **Details to Fill:** * **App Name**: OpenAlgo * **App Description**: OpenAlgo * **Redirect URL: (leave it empty)** * **Company Name**: OpenAlgo (or your own) * Choose the correct **API Package** depending on the app (Order or Market Data). ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FniCcfxk5mkwr4Orv00jF%252FWhatsApp%2520Image%25202025-12-05%2520at%252012.21.25%2520PM.jpeg%3Falt%3Dmedia%26token%3Dddd015f8-eb4f-4396-88ed-387c698ff5ff&width=768&dpr=3&quality=100&sign=e65d52e8&sv=2) Once submitted, wait for approval from the broker. After approval, the status will turn **Active**. #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/jainamxts#step-2-setup-environment-variables) Step 2: Setup Environment Variables Refer to the `.sample.env` file in your OpenAlgo folder and prepare your `.env` as follows: Replace the values with actual credentials shown on your developer dashboard once approved. #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/jainamxts#step-3-start-openalgo) **Step 3: Start OpenAlgo** Once all environment variables are set and your apps are **Active**, you can now start OpenAlgo. This completes the integration process for JainamXTS API with OpenAlgo. By following the steps outlined in this guide, you have successfully configured your JainamXTS API account for use with OpenAlgo. You can now leverage the power of algorithmic trading to enhance your trading strategies and make data-driven decisions. Should you encounter any issues or need further assistance, please refer to the OpenAlgo community or support resources. Happy trading! [PreviousIndiaBulls Securitieschevron-left](https://docs.openalgo.in/connect-brokers/brokers/indiabulls-securities) [NextKotak Securitieschevron-right](https://docs.openalgo.in/connect-brokers/brokers/kotak-securities) Last updated 4 months ago sun-brightdesktopmoon Copy # Broker Configuration BROKER_API_KEY = 'YOUR_BROKER_ORDER_API_KEY' BROKER_API_SECRET = 'YOUR_ORDER_API_SECRET' BROKER_API_KEY_MARKET = 'YOUR_BROKER_MARKET_API_KEY' BROKER_API_SECRET_MARKET = 'YOUR_BROKER_MARKET_API_SECRET' REDIRECT_URL = 'http://127.0.0.1:5000/jainamxts/callback' sun-brightdesktopmoon --- # Install Dependencies | Documentation Windows users Navigate to the directory where OpenAlgo is cloned and execute: `pip3 install -r requirements.txt` ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F2yttSeo3jHXAdAZCkMNk%252FInstall%2520dependencies.png%3Falt%3Dmedia%26token%3D40f0ae87-adb2-42c0-8d4a-e16a65be8537&width=768&dpr=3&quality=100&sign=fa211ef3&sv=2) [PreviousSetupchevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/setup) [NextNgrok Configchevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/ngrok-config) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Install certifi | Documentation If you’re encountering, SSLCertVerificationError: \[SSL: CERTIFICATE\_VERIFY\_FAILED\] certificate verify failed: unable to get local issuer certificate, is common on macOS when Python is unable to verify SSL certificates due to a missing or inaccessible certificate store. This usually affects the ability to fetch data over HTTPS, such as when attempting to download or use resources like ngrok. To resolve this issue on macOS, you need to install the certificates for Python. Follow these steps: In this example I used python3.11 as the version replace it with python3.xx version in the below commands **1\. Locate the Correct Path of Python Installation:** To find out where Python 3.11 is installed on your system, use the which command. Open your Terminal and type: Copy which python3.11 Locate and Run the Install Certificates Script: ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FjNIidEvTmbvHer9wUHkM%252FInstall%2520Python%2520SSL%2520Certifications.png%3Falt%3Dmedia%26token%3D2722fceb-41b8-4576-848f-571d390c6de6&width=768&dpr=3&quality=100&sign=5d48e415&sv=2) Once you have the correct path to Python 3.11, you can attempt to locate the Install Certificates.command script. Typically, if you installed Python via Homebrew, the command might not directly exist, but Python installations downloaded from the official Python website typically include it. Assuming you installed Python using Homebrew, you might not find an Install Certificates.command. Instead, you can ensure the certificates are installed by manually installing the certifi package and configuring your environment to use it. Here’s how you can do that: 1. **Install certifi:** 1. **Set the SSL\_CERT\_FILE Environment Variable:** To manually specify the certificate file for Python to use, you can set the SSL\_CERT\_FILE environment variable to point to the certifi certificate file: 1. **Retry Running Your Python Code:** After setting up the certificates through certifi, try running your Python code again. This should resolve any SSL certificate issues. If you installed Python using a method other than Homebrew and the Python installation includes the Install Certificates.command, you would typically find it in the Python application directory within /Applications/Python 3.11 or similar. If this is the case, navigate to this directory in Finder, and you should be able to run the Install Certificates.command by double-clicking on it. Ensure that you are using the correct paths and commands based on how and where Python is installed on your system. [PreviousStart OpenAlgochevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/start-openalgo) [NextAccessing OpenAlgochevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/accessing-openalgo) Last updated 1 year ago sun-brightdesktopmoon Copy python3.11 -m pip install certifi Copy export SSL_CERT_FILE=$(python3.11 -m certifi) sun-brightdesktopmoon --- # Install Dependencies | Documentation Windows users Navigate to the directory where OpenAlgo is cloned and execute: `pip install -r requirements.txt` ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FyrQDKMfVVtBvQI7wMr0O%252Fpip%2520install.png%3Falt%3Dmedia%26token%3Db6ecc633-edc5-4b58-a34a-964bd75370ef&width=768&dpr=3&quality=100&sign=31271c9a&sv=2) [PreviousSetupchevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/setup) [NextNgrok Configchevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/ngrok-config) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Zerodha | Documentation Zerodha is a leading name in the Indian financial services industry, acclaimed for its discount brokerage model and tech-centric approach to trading. Kite by Zerodha is their flagship trading platform, known for its intuitive user interface and powerful performance. Kite API is a set of REST-like APIs that exposes Zerodha's trading functionalities programmatically, allowing developers to harness the capabilities of the Kite platform within their own custom applications. The Kite API by Zerodha is particularly popular among algorithmic traders and fintech developers, as it provides real-time data feeds, order placement, portfolio management, and a host of other critical trading operations. The API ensures seamless integration with Zerodha's services, enabling the development of automated trading bots, analytical tools, and other innovative trading solutions. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FNpsYCwcT7PxL4M1coJoS%252Fimage.png%3Falt%3Dmedia%26token%3Da62e154e-5eb3-4bfa-ae0a-ee2ea6b0b8a1&width=768&dpr=3&quality=100&sign=60534190&sv=2) #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/zerodha#api-key-and-api-secret-creation-process) API Key and API Secret Creation Process The process to create an API key and API secret for Zerodha's Kite API involves the following steps: 1. **Visit the Zerodha Kite Developer Portal**: Access the developer portal by visiting `https://developers.kite.trade/login`. 2. **Create an Application**: Click on the 'Create App' button to start the process of registering a new application. 3. **Enter Application Details**: You will be asked to provide details such as the App Name, your Zerodha Client ID, and the Redirect URL. The Redirect URL is important for OAuth authentication, as users will be redirected here after successful authentication with Zerodha. 4. **Optional App Logo**: Uploading an app logo is optional, but it can help users recognize your application. 5. **Save Changes**: After filling in all required fields, click on 'Save Changes' to register your application with Zerodha. 6. **Copy API Credentials**: Post-registration, you will be given an API Key and API Secret. These credentials are essential for making API requests and should be stored securely. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FYkVwgbgwmQesPN0VgOEe%252FZerodha%2520Kite%2520Connect.png%3Falt%3Dmedia%26token%3Da2158fd3-e711-4fe6-b863-1259ee28bf1c&width=768&dpr=3&quality=100&sign=1fcaa830&sv=2) Here is how you would typically store these details in a `.env` file: Utilizing the Kite API from Zerodha presents a wealth of opportunities for developers and traders aiming to create bespoke trading tools and strategies. Leveraging this API effectively calls for a commitment to best practices such as secure storage and management of API keys, mindful adherence to API rate limits, and the implementation of solid error handling and logging mechanisms. When harnessed properly, the Kite API can become a powerful asset in the arsenal of any trader or fintech application developer, enabling them to capitalize on the dynamism of financial markets with precision and efficiency. [PreviousZebuchevron-left](https://docs.openalgo.in/connect-brokers/brokers/zebu) [NextExchangeschevron-right](https://docs.openalgo.in/crypto/exchanges) Last updated 9 months ago sun-brightdesktopmoon Copy BROKER_API_KEY = 'your_api_key_here' BROKER_API_SECRET = 'your_api_secret_here' REDIRECT_URL = 'http://127.0.0.1:5000/zerodha/callback' sun-brightdesktopmoon --- # Ngrok Config | Documentation [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/ngrok-config#undefined) --------------------------------------------------------------------------------------------------------------------------- [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/ngrok-config#download-ngrok) Download Ngrok ------------------------------------------------------------------------------------------------------------------------------------------------ 1. Visit the [Ngrok arrow-up-right](https://ngrok.com/) website and sign up or log in. 2. Navigate to the [download sectionarrow-up-right](https://dashboard.ngrok.com/get-started/setup/windows) and select the version for Windows. 3. Download the ZIP file. 4. Copy the Auth Token and keep it separately later this will be used to set the **ngrok.yml** config file ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Fp5yGbSOn1ObwdvrWzKZO%252FNgrok%2520Windows%2520Download.webp%3Falt%3Dmedia%26token%3De2ba63f6-0100-4689-9738-d4e573df499c&width=768&dpr=3&quality=100&sign=e15e0736&sv=2) [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/ngrok-config#extract-the-zip-file) Extract the Zip File ------------------------------------------------------------------------------------------------------------------------------------------------------------ Once downloaded, extract the ZIP file to a folder of your choice, such as `C:\ngrok\`. This folder will contain the `ngrok.exe` executable. [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/ngrok-config#add-ngrok-path-to-environmental-variable) Add Ngrok Path to Environmental Variable ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- For Windows users: 1. Unzip the `ngrok` executable to a directory, e.g., `C:\ngrok\`. 2. Right-click on ‘This PC’ or ‘Computer’ on your desktop and select ‘Properties’. 3. Click on ‘Advanced system settings’. 4. Click on the ‘Environment Variables‘ button. 5. In the ‘System variables’ section, find the ‘Path‘ variable and click ‘Edit’. 6. Click ‘New’ and add the path to the directory where you unzipped `ngrok` (e.g., `C:\ngrok\`). 7. Click ‘OK’ to close the dialogs and apply the changes. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F9L4PjwWkWZ5ApFGgeYzV%252FNgrok%2520Environmental%2520Variables.webp%3Falt%3Dmedia%26token%3Ddf1e6078-ddc5-428a-9590-9627a5f20baf&width=768&dpr=3&quality=100&sign=9f017961&sv=2) Now, `ngrok` can be run from the command line regardless of the current directory. [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/ngrok-config#setting-up-the-ngrok-free-custom-domain) Setting up the Ngrok Free Custom Domain -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Go to the **Ngrok portal**, navigate to **Domains -> New Domain**, and create your free domain. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Fga6ttI0qb1fKE5408nPm%252FNgrok%2520Free%2520Custom%2520Domain.webp%3Falt%3Dmedia%26token%3D52211b6d-d144-4904-af81-923da134008d&width=768&dpr=3&quality=100&sign=6e2b91c8&sv=2) [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/ngrok-config#setting-up-the-ngrok-config-file) Setting up the Ngrok Config File ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 1. Open the command prompt in Windows. 2. Enter the command `ngrok config edit`. 3. This opens the ngrok config file. Enter your Auth Token, Tunnel Name, hostname, and addr as follows: Replace `` with your actual Ngrok authentication token and `` with the hostname you’ve set up. #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/ngrok-config#undefined-1) [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/ngrok-config#security-best-practices-when-using-ngrok) Security Best Practices When Using Ngrok ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * **Keep Your Ngrok Auth Token Secure**: Your Ngrok authentication token is the key to creating tunnels with your account. Keep it secure to prevent unauthorized access. * **Use Strong Authentication for Exposed Services**: If you’re exposing a web service or application, ensure it has its own strong authentication mechanism. * **Monitor Tunnel Usage**: Regularly review logs and monitor tunnel usage for any unexpected or unauthorized access. * **Limit Exposure Time**: Only keep tunnels open for as long as necessary. The longer a tunnel is open, the higher the potential security risk. [PreviousInstall Dependencieschevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/install-dependencies) [NextEnvironmental Variableschevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/environmental-variables) Last updated 4 months ago * [](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/ngrok-config#undefined) * [Download Ngrok](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/ngrok-config#download-ngrok) * [Extract the Zip File](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/ngrok-config#extract-the-zip-file) * [Add Ngrok Path to Environmental Variable](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/ngrok-config#add-ngrok-path-to-environmental-variable) * [Setting up the Ngrok Free Custom Domain](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/ngrok-config#setting-up-the-ngrok-free-custom-domain) * [Setting up the Ngrok Config File](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/ngrok-config#setting-up-the-ngrok-config-file) * [Security Best Practices When Using Ngrok](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/ngrok-config#security-best-practices-when-using-ngrok) sun-brightdesktopmoon Copy version: "3" tunnels: flask: proto: http hostname: .ngrok-free.app addr: 127.0.0.1:5000 agent: authtoken: sun-brightdesktopmoon --- # Windows Server Installation | Documentation Windows Server Installation (Updated) Why Choose a Server over a Desktop? * Reliability and Stability: Servers provide a stable and dedicated environment for your trading software. Unlike a desktop, servers are designed for constant operation and are less susceptible to disruptions like power outages, system crashes, or internet issues. * Scalability: If your trading algorithms become more complex or require access to vast amounts of data, you can easily scale up your server resources to accommodate those needs. * Security: Servers offer enhanced security measures to protect your trading strategies and data. You can control access, enforce strict firewall rules, and implement encryption protocols for better data protection. * Accessibility: You can access your server and trading platform remotely, regardless of your location. This allows for greater flexibility and control over your operations. This updated guide focuses on a minimal, high-performance installation of OpenAlgo on a Windows Server (Vultr/AWS/Azure), specifically targeting regions like Mumbai for optimal trading latency. It introduces the uv package manager for significantly faster dependency management compared to standard pip. Step-by-Step Installation Process: 1. Deploy a Cloud Instance: Deploy a Windows Server 2022 instance via your preferred cloud provider. For Indian markets, choose the Mumbai data center. A minimum of 8GB RAM is recommended. 2. Access via RDP: Log into your instance using the Remote Desktop Connection tool with the Administrator credentials provided by your cloud console. 3. Install Google Chrome: Open the default browser (Edge) to download and install Google Chrome for a better browsing experience on the server. 4. Install Visual C++ Redistributable: Download and install the latest VC++ Redistributable (both x86 and x64). This is essential for libraries like Numba, which OpenAlgo uses for high-performance calculations. 5. Install Python: Download the latest stable version of Python from python.org. Important: During installation, ensure you check the box "Add python.exe to PATH". 6. Install Git: Download and install Git for Windows from git-scm.com. This is required to clone and update the OpenAlgo source code. 7. Install uv Package Manager: Open Windows PowerShell as Administrator and run the following command to install uv: pip install uv 8. Download OpenAlgo: Navigate to your C: drive in PowerShell (cd C:) and clone the repository: git clone https://github.com/marketcalls/openalgo 9. Configure .env File: * Enter the folder: cd openalgo * Create a copy of the sample config: copy .sample.env .env * Open the .env file in Notepad and enter your Broker API Key and API Secret. Save and close. 10. Set Server Timezone: For Indian markets, adjust your server time settings to (UTC +05:30) Chennai, Kolkata, Mumbai, New Delhi. Ensure you click "Sync now" to align with exchange timings. 11. Update Static IP at Broker: Copy your server's Public IP address. Log in to your broker's API portal and whitelist this IP in your App settings. This is a critical security step required by most brokers. 12. Initial Launch: Run OpenAlgo for the first time by typing: uv run app.py Note: The first launch will take a few minutes as uv builds the virtual environment and installs 175+ dependencies. Create a One-Click Launch Script To simplify the startup process, you can create a PowerShell script on your desktop: 1. Open Notepad and paste the following code: [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/windows-server-installation#start-openalgo-using-uv-on-windows-server-2022) Start OpenAlgo using uv on Windows Server 2022 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- $OpenAlgoPath = "C:\\openalgo" Write-Host "Starting OpenAlgo..." Write-Host "Folder: $OpenAlgoPath" [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/windows-server-installation#go-to-openalgo-folder) Go to OpenAlgo folder -------------------------------------------------------------------------------------------------------------------------------------------------------- Set-Location $OpenAlgoPath [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/windows-server-installation#check-uv-is-available) Check uv is available -------------------------------------------------------------------------------------------------------------------------------------------------------- if (-not (Get-Command uv -ErrorAction SilentlyContinue)) { Write-Host "ERROR: uv is not installed or not available in PATH." -ForegroundColor Red exit 1 } [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/windows-server-installation#run-openalgo) Run OpenAlgo -------------------------------------------------------------------------------------------------------------------------------------- uv run app.py 1. Save the file to your Desktop as StartOpenAlgo.ps1. 2. To start OpenAlgo, Right-click the file and select "Run with PowerShell". [PreviousAccessing OpenAlgochevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/accessing-openalgo) [NextMac OS Installationchevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation) Last updated 3 hours ago * [Start OpenAlgo using uv on Windows Server 2022](https://docs.openalgo.in/installation-guidelines/getting-started/windows-server-installation#start-openalgo-using-uv-on-windows-server-2022) * [Go to OpenAlgo folder](https://docs.openalgo.in/installation-guidelines/getting-started/windows-server-installation#go-to-openalgo-folder) * [Check uv is available](https://docs.openalgo.in/installation-guidelines/getting-started/windows-server-installation#check-uv-is-available) * [Run OpenAlgo](https://docs.openalgo.in/installation-guidelines/getting-started/windows-server-installation#run-openalgo) sun-brightdesktopmoon sun-brightdesktopmoon --- # Testing OpenAlgo in Cloud | Documentation ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/testing-openalgo-in-cloud#testing-openalgo-in-the-github-codespaces) Testing OpenAlgo in the Github Codespaces ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/testing-openalgo-in-cloud#test-openalgo-in-google-colab) Test OpenAlgo in Google Colab [PreviousRaspberry Pichevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/raspberry-pi) [NextSMTP Settingschevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/smtp-settings) Last updated 1 year ago * [Testing OpenAlgo in the Github Codespaces](https://docs.openalgo.in/installation-guidelines/getting-started/testing-openalgo-in-cloud#testing-openalgo-in-the-github-codespaces) * [Test OpenAlgo in Google Colab](https://docs.openalgo.in/installation-guidelines/getting-started/testing-openalgo-in-cloud#test-openalgo-in-google-colab) sun-brightdesktopmoon sun-brightdesktopmoon --- # Wisdom Capital | Documentation Wisdom Capital provides API access through the Symphony Fintech XTS platform. This guide helps you integrate Wisdom Capital with OpenAlgo for both order execution and market data streaming. * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/wisdom-capital#step-1-create-api-applications) Step 1: Create API Applications Login to the [Wisdom Capital Developer Portalarrow-up-right](https://trade.wisdomcapital.in/dashboard#!/login) . After logging in: 1. Go to `My App` > `Create New Application` 2. You need to create two applications: * One for **Interactive Order API** * One for **Market Data API** ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F5qi4GuFPCZZdmxL4e3kL%252Fimage.png%3Falt%3Dmedia%26token%3D1e9595d2-00fe-4a6d-bc47-ad9012ee2a1c&width=768&dpr=3&quality=100&sign=5bed41a&sv=2) #### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/wisdom-capital#application-setup) Application Setup: For each app, fill in the following: * **App Name**: OpenAlgo * **App Description**: OpenAlgo * **Select API Package**: Choose `Interactive Order API` or `Market Data API` depending on the app. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Fmpa5UsQwon2TmicqMKqy%252Fimage.png%3Falt%3Dmedia%26token%3Db9d7933a-1c51-4f3a-bee4-54750dd0ec61&width=768&dpr=3&quality=100&sign=16318836&sv=2) Repeat the process for both API packages. Once submitted, wait for the apps to be **approved**. The API status will show as **Active** once approved. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FBc40MyQwplzMRMjhriCs%252Fimage.png%3Falt%3Dmedia%26token%3D8131253b-78ee-49f1-8f40-fc62c26a53a7&width=768&dpr=3&quality=100&sign=b1747b95&sv=2) * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/wisdom-capital#step-2-setup-environment-variables) Step 2: Setup Environment Variables Refer to the `.sample.env` file in OpenAlgo and prepare your `.env` with the following structure: Replace placeholder values with actual credentials obtained after app approval. * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/wisdom-capital#step-3-start-openalgo) Step 3: Start OpenAlgo Ensure `.env` is correctly configured and that both APIs (order and market data) are active. Then, start OpenAlgo. > You can now place live orders and get real-time market data via Wisdom Capital’s XTS API inside OpenAlgo. * * * ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/wisdom-capital#final-note) Final Note Integrating OpenAlgo with Wisdom Capital's XTS API gives you access to real-time market data and order execution in a programmable environment. Follow best practices—keep your API keys secure, implement appropriate error handling, and regularly monitor your API usage to ensure a smooth trading experience. [PreviousUpstoxchevron-left](https://docs.openalgo.in/connect-brokers/brokers/upstox) [NextZebuchevron-right](https://docs.openalgo.in/connect-brokers/brokers/zebu) Last updated 1 year ago * [Step 1: Create API Applications](https://docs.openalgo.in/connect-brokers/brokers/wisdom-capital#step-1-create-api-applications) * [Step 2: Setup Environment Variables](https://docs.openalgo.in/connect-brokers/brokers/wisdom-capital#step-2-setup-environment-variables) * [Step 3: Start OpenAlgo](https://docs.openalgo.in/connect-brokers/brokers/wisdom-capital#step-3-start-openalgo) * [Final Note](https://docs.openalgo.in/connect-brokers/brokers/wisdom-capital#final-note) sun-brightdesktopmoon Copy # Broker Configuration BROKER_API_KEY = 'YOUR_WISDOM_ORDER_API_KEY' BROKER_API_SECRET = 'YOUR_ORDER_API_SECRET' BROKER_API_KEY_MARKET = 'YOUR_WISDOM_MARKET_API_KEY' BROKER_API_SECRET_MARKET = 'YOUR_MARKET_API_SECRET' REDIRECT_URL = 'http://127.0.0.1:5000/wisdom/callback' sun-brightdesktopmoon --- # Pre-Requesites | Documentation #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/pre-requesites#prerequisites) Prerequisites Before we begin, ensure you have the following: * **Windows 10** or Higher * **Visual Studio Code (VS Code)** is installed. * **Python** version 3.10 or higher version installed * **Git** for cloning the repository (Download from [https://git-scm.com/downloadsarrow-up-right](https://git-scm.com/downloads) ). [PreviousWindows Installationchevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation) [NextSetupchevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/windows-installation/setup) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Accessing OpenAlgo | Documentation After starting the openalgo application, access the OpenAlgo platform by navigating to [http://127.0.0.1:5000arrow-up-right](http://127.0.0.1:5000/) in your web browser. If ngrok is configured then access your custom ngrok domain name in the web broker. After completing the setup, access the OpenAlgo platform by navigating to [http://127.0.0.1:5000arrow-up-right](http://127.0.0.1:5000/) in your web browser. setup the account using [http://127.0.0.1:5000/setuparrow-up-right](http://127.0.0.1:5000/setup) Login into openalgo with the credentials and start using OpenAlgo for Automation. [PreviousInstall certifichevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/install-certifi) [NextAmazon Elastic Beanstalkchevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/amazon-elastic-beanstalk) Last updated 2 years ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Zebu | Documentation Zebu, a leading stock trading platform, offers robust API services for traders and developers looking to integrate algorithmic trading solutions into their platforms. The Zebu MYNT API enables access to real-time market data, portfolio management, and trade execution for stocks, commodities, and mutual funds. To integrate Zebu’s API, follow the steps below: ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/zebu#api-key-registration) API Key Registration Before using the API, you need to generate an API key and API secret. 1\. Login to Zebu MYNT Go to the [https://mynt.zebuetrade.com/loginarrow-up-right](https://mynt.zebuetrade.com/login) and log in with your Zebu credentials. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F0RY6MOHnxnAkOS0IDmtQ%252Fzebu1.PNG%3Falt%3Dmedia%26token%3D3f8d44cf-ab5c-4833-a5d2-ecf5e7e6a0e6&width=768&dpr=3&quality=100&sign=1074fa17&sv=2) 2\. Access API Key Generation Navigate to Profile ,click on the Client Code at the top right corner and select setting. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Fkpsc8J22JANJOl3aQuku%252Fzebu2.PNG%3Falt%3Dmedia%26token%3D7b3b0579-6ecd-440b-867c-2c84a6e4c3df&width=768&dpr=3&quality=100&sign=d0bfc094&sv=2) click the OAuth Key button and fill in the details and Update. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F7Ssp0DtnD3QkkQappw0i%252Fzebu3.PNG%3Falt%3Dmedia%26token%3D11824907-6bc1-45ad-90d6-3a00f34c95bf&width=768&dpr=3&quality=100&sign=ad976e0c&sv=2) Once generated, the client Id and Secret Code will be provided for the app. These keys are essential for authenticating API requests. Here’s how your .env file might look: Make sure to store your API credentials securely and handle them with care to prevent unauthorized access. ### [hashtag](https://docs.openalgo.in/connect-brokers/brokers/zebu#zebu-api-integration) Zebu API Integration Integrating OpenAlgo with Zebu’s MYNT API opens opportunities for algorithmic trading and portfolio management. By using the Zebu API, developers can automate trading strategies and enhance trading experiences for users. Be sure to implement best practices for API rate limits, security, and error handling. For further assistance or troubleshooting, refer to [Zebu API Documentationarrow-up-right](https://zebumyntapi.web.app/) . [PreviousWisdom Capitalchevron-left](https://docs.openalgo.in/connect-brokers/brokers/wisdom-capital) [NextZerodhachevron-right](https://docs.openalgo.in/connect-brokers/brokers/zerodha) Last updated 28 days ago * [API Key Registration](https://docs.openalgo.in/connect-brokers/brokers/zebu#api-key-registration) * [Zebu API Integration](https://docs.openalgo.in/connect-brokers/brokers/zebu#zebu-api-integration) sun-brightdesktopmoon Copy BROKER_API_KEY = 'your_userid_here':::'your_ClientId_here' BROKER_API_SECRET = 'your_Secretcode_here' REDIRECT_URL = 'http://127.0.0.1:5000/zebu/callback' sun-brightdesktopmoon --- # Ngrok Config | Documentation [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/ngrok-config#download-ngrok) Download Ngrok ----------------------------------------------------------------------------------------------------------------------------------------------- 1. Visit the [Ngrok arrow-up-right](https://ngrok.com/) website and sign up or log in. 2. Navigate to the [download sectionarrow-up-right](https://dashboard.ngrok.com/get-started/setup/macos) and select the version for Mac OS. 3. Install Ngrok using the brew command Copy brew install ngrok/ngrok/ngrok 1. Copy the Auth Token and keep it separately later this will be used to set the **ngrok.yml** config file ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FoIH25tXJu4o6TY704FFM%252Fngrok%2520download%2520macos.png%3Falt%3Dmedia%26token%3D84b505b0-8e0f-4d60-8dae-49628f8c1b93&width=768&dpr=3&quality=100&sign=c8d1f4cf&sv=2) [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/ngrok-config#setting-up-the-ngrok-free-custom-domain) Setting up the Ngrok Free Custom Domain ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Go to the **Ngrok portal**, navigate to **Domains -> New Domain**, and create your free domain. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Fga6ttI0qb1fKE5408nPm%252FNgrok%2520Free%2520Custom%2520Domain.webp%3Falt%3Dmedia%26token%3D52211b6d-d144-4904-af81-923da134008d&width=768&dpr=3&quality=100&sign=6e2b91c8&sv=2) [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/ngrok-config#setting-up-the-ngrok-config-file) Setting up the Ngrok Config File ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1. Open the terminal in Mac 2. Enter the command `ngrok config edit`. 3. This opens the ngrok config file. Enter your Auth Token, Tunnel Name, hostname, and addr as follows: Replace `` with your actual Ngrok authentication token and `` with the hostname you’ve set up. [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/ngrok-config#security-best-practices-when-using-ngrok) Security Best Practices When Using Ngrok --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * **Keep Your Ngrok Auth Token Secure**: Your Ngrok authentication token is the key to creating tunnels with your account. Keep it secure to prevent unauthorized access. * **Use Strong Authentication for Exposed Services**: If you’re exposing a web service or application, ensure it has its own strong authentication mechanism. * **Monitor Tunnel Usage**: Regularly review logs and monitor tunnel usage for any unexpected or unauthorized access. * **Limit Exposure Time**: Only keep tunnels open for as long as necessary. The longer a tunnel is open, the higher the potential security risk. [PreviousInstall Dependencieschevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/install-dependencies) [NextEnvironmental Variableschevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/environmental-variables) Last updated 1 year ago * [Download Ngrok](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/ngrok-config#download-ngrok) * [Setting up the Ngrok Free Custom Domain](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/ngrok-config#setting-up-the-ngrok-free-custom-domain) * [Setting up the Ngrok Config File](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/ngrok-config#setting-up-the-ngrok-config-file) * [Security Best Practices When Using Ngrok](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/ngrok-config#security-best-practices-when-using-ngrok) sun-brightdesktopmoon Copy version: "3" tunnels: flask: proto: http hostname: .ngrok-free.app addr: 127.0.0.1:5000 agent: authtoken: sun-brightdesktopmoon --- # Accounts API | Documentation The Accounts API provides a comprehensive list of operations to manage and handle Trading Accounts efficiently. [PreviousV1chevron-left](https://docs.openalgo.in/api-documentation/v1) [NextPingchevron-right](https://docs.openalgo.in/api-documentation/v1/accounts-api/ping) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Cloudflared with Custom Domain | Documentation This documentation outlines how to set up a **Cloudflare Tunnel (**`**cloudflared**`**)** with **OpenAlgo** to receive TradingView alerts securely on your local machine ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/cloudflared-with-custom-domain#id-1.-overview) 1\. Overview A Cloudflare Tunnel creates a secure, outbound-only connection between your local OpenAlgo server and the Cloudflare network. This allows TradingView (which is on the public web) to send HTTP POST requests (Webhooks) to your local machine (`localhost:5000`) securely. * * * ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/cloudflared-with-custom-domain#id-2.-installation) 2\. Installation To follow the video tutorial, install `cloudflared` on your Windows machine using PowerShell: _Note: After installation, restart your terminal to ensure the command is recognized._ * * * ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/cloudflared-with-custom-domain#id-3.-configuration-in-openalgo) 3\. Configuration in OpenAlgo Before starting the tunnel, you must tell OpenAlgo what its public address will be. 1. Open your OpenAlgo folder in **VS Code**. 2. Open the `.env` file. 3. Locate the `HOST_SERVER` variable and update it with your intended domain: 4. Save the file and start OpenAlgo: `python app.py` (running on port 5000). * * * ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/cloudflared-with-custom-domain#id-4.-setting-up-the-tunnel-two-options) 4\. Setting Up the Tunnel (Two Options) #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/cloudflared-with-custom-domain#option-a-custom-domain-recommended-for-production) Option A: Custom Domain (Recommended for Production) This keeps your Webhook URL permanent. 1. **Login to Cloudflare:** _A browser window will open. Select your domain to authorize._ 2. **Create the Tunnel:** _This generates a JSON credentials file. Note the path provided in the terminal._ 3. **Configure** `**config.yml**`**:** In your OpenAlgo project, locate or create `.cloudflared/config.yml` and fill it: 4. **Route DNS:** 5. **Run the Tunnel:** * * * #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/cloudflared-with-custom-domain#option-b-free-temporary-tunnel-quick-testing) Option B: Free Temporary Tunnel (Quick Testing) If you don't own a domain, you can generate a random public URL. 1. **Run the command:** 2. Cloudflare will generate a URL like `https://random-words-generated.trycloudflare.com`. 3. **Warning:** Every time you restart this tunnel, the URL will change. You will have to update your TradingView Webhook URL and `.env` file accordingly. * * * ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/cloudflared-with-custom-domain#id-5.-integrating-with-tradingview) 5\. Integrating with TradingView Once the tunnel is "Active" in your terminal: 1. **Get Webhook URL:** Your URL will be `https://yourdomain.com/api/v1/placeorder`. 2. **Generate Payload:** * Go to OpenAlgo Local Dashboard -> **Platforms** -> **TradingView**. * Configure your symbol (e.g., `SILVERMARFUT`), action (`BUY`), and quantity. * Click **Generate JSON** and Copy the code. 3. **Create Alert in TradingView:** * Set your Condition (e.g., Price Crossing). * Under **Notifications**, check **Webhook URL** and paste your tunnel URL. * Under **Message**, paste the JSON payload generated by OpenAlgo. * * * ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/cloudflared-with-custom-domain#id-6.-verification-and-performance) 6\. Verification & Performance * **Order Book:** When the alert triggers, check the **Order Book** tab in OpenAlgo to see the executed trade. * **Latency Monitor:** Go to **Logs** -> **Latency Monitor**. * Cloudflare Tunnels typically offer latency between **150ms – 300ms**, which is faster than Ngrok or Pagekite in many regions. * **Security:** Because the tunnel is outbound-only, your local IP address remains hidden from the public internet. * * * ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/cloudflared-with-custom-domain#id-7.-troubleshooting) 7\. Troubleshooting * **404 Error:** Ensure the `service` URL in `config.yml` matches the port OpenAlgo is running on (default is `5000`). * **HTTPS Requirement:** TradingView **requires** an `https` URL. Ensure you use the Cloudflare provided link and not your local IP. * **Tunnel Fails to Start:** Check if another instance of `cloudflared` is running in the background. [PreviousDevtunnelschevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/devtunnels) [NextRaspberry Pichevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/raspberry-pi) Last updated 4 months ago * [1\. Overview](https://docs.openalgo.in/installation-guidelines/getting-started/cloudflared-with-custom-domain#id-1.-overview) * [2\. Installation](https://docs.openalgo.in/installation-guidelines/getting-started/cloudflared-with-custom-domain#id-2.-installation) * [3\. Configuration in OpenAlgo](https://docs.openalgo.in/installation-guidelines/getting-started/cloudflared-with-custom-domain#id-3.-configuration-in-openalgo) * [4\. Setting Up the Tunnel (Two Options)](https://docs.openalgo.in/installation-guidelines/getting-started/cloudflared-with-custom-domain#id-4.-setting-up-the-tunnel-two-options) * [5\. Integrating with TradingView](https://docs.openalgo.in/installation-guidelines/getting-started/cloudflared-with-custom-domain#id-5.-integrating-with-tradingview) * [6\. Verification & Performance](https://docs.openalgo.in/installation-guidelines/getting-started/cloudflared-with-custom-domain#id-6.-verification-and-performance) * [7\. Troubleshooting](https://docs.openalgo.in/installation-guidelines/getting-started/cloudflared-with-custom-domain#id-7.-troubleshooting) sun-brightdesktopmoon Copy # Install via Winget (Windows Package Manager) winget install Cloudflare.cloudflared Copy HOST_SERVER="https://demo.openalgo.in" Copy cloudflared tunnel login Copy cloudflared tunnel create openalgo Copy tunnel: credentials-file: C:\Users\\.cloudflared\.json ingress: - hostname: demo.openalgo.in service: http://127.0.0.1:5000 - service: http_status:404 Copy cloudflared tunnel route dns openalgo demo.openalgo.in Copy cloudflared tunnel --config .\.cloudflared\config.yml run openalgo Copy cloudflared tunnel --url http://127.0.0.1:5000 sun-brightdesktopmoon --- # Environmental Variables | Documentation Rename the `.sample.env` file located in `openalgo` folder to `.env` Update the `.env` with your specific configurations as shown in the provided template. ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/environmental-variables#sample-environmental-file) Sample Environmental File Copy # Broker Configuration BROKER_API_KEY = 'YOUR_BROKER_API_KEY' BROKER_API_SECRET = 'YOUR_BROKER_API_SECRET' REDIRECT_URL = 'http://127.0.0.1:5000//callback' # Change if different # Valid Brokers Configuration VALID_BROKERS = 'fivepaisa,aliceblue,angel,dhan,fyers,icici,kotak,shoonya,upstox,zebu,zerodha' # Security Configuration # IMPORTANT: Generate new random values for both keys during setup! # OpenAlgo Application Key APP_KEY = '3daa0403ce2501ee7432b75bf100048e3cf510d63d2754f952e93d88bf07ea84' # Security Pepper - Used for hashing/encryption of sensitive data # This is used for: # 1. API key hashing # 2. User password hashing # 3. Broker auth token encryption # Generate a new random string during setup using: python -c "import secrets; print(secrets.token_hex(32))" API_KEY_PEPPER = 'a25d94718479b170c16278e321ea6c989358bf499a658fd20c90033cef8ce772' # OpenAlgo Database Configuration DATABASE_URL = 'sqlite:///db/openalgo.db' # OpenAlgo Ngrok Configuration NGROK_ALLOW = 'FALSE' # OpenAlgo Hosted Server (Custom Domain Name) or Ngrok Domain Configuration # Change to your custom domain or Ngrok domain HOST_SERVER = 'http://127.0.0.1:5000' # OpenAlgo Flask App Host and Port Configuration # For 0.0.0.0 (accessible from other devices on the network) # Flask Environment - development or production FLASK_HOST_IP='127.0.0.1' FLASK_PORT='5000' FLASK_DEBUG='False' FLASK_ENV='development' # OpenAlgo Rate Limit Settings LOGIN_RATE_LIMIT_MIN = "5 per minute" LOGIN_RATE_LIMIT_HOUR = "25 per hour" API_RATE_LIMIT="10 per second" # OpenAlgo API Configuration # Required to give 0.5 second to 1 second delay between multi-legged option strategies # Single legged orders are not affected by this setting. SMART_ORDER_DELAY = '0.5' # Session Expiry Time (24-hour format, IST) # All user sessions will automatically expire at this time daily SESSION_EXPIRY_TIME = '03:00' # Note: OpenAlgo version is now managed in utils/version.py ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/environmental-variables#undefined) [PreviousNgrok Configchevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/ngrok-config) [NextStart OpenAlgochevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/start-openalgo) Last updated 1 year ago * [Sample Environmental File](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/environmental-variables#sample-environmental-file) * [](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/environmental-variables#undefined) sun-brightdesktopmoon sun-brightdesktopmoon --- # Contributors | Documentation ### [hashtag](https://docs.openalgo.in/contributors#lets-democratize-algorithmic-trading-together) Let's democratize algorithmic trading, together! We're thrilled that you're interested in contributing to OpenAlgo! This guide will help you get started, whether you're fixing a bug, adding a new broker, improving documentation, or building new features. Below you'll find everything you need to set up OpenAlgo on your computer and start contributing. * * * ### [hashtag](https://docs.openalgo.in/contributors#our-mission) Our Mission OpenAlgo is built **by traders, for traders**. We believe in democratizing algorithmic trading by providing a broker-agnostic, open-source platform that puts control back in the hands of traders. Every contribution, no matter how small, helps us achieve this mission. * * * ### [hashtag](https://docs.openalgo.in/contributors#table-of-contents) Table of Contents 1. Technology Stack 2. Development Setup 3. Local Development 4. Project Structure 5. Development Workflow 6. Contributing Guidelines 7. Testing 8. Adding a New Broker 9. Frontend Development 10. Documentation 11. Best Practices 12. Getting Help * * * ### [hashtag](https://docs.openalgo.in/contributors#technology-stack) Technology Stack OpenAlgo uses a **Python Flask** backend with a **React 19** single-page application frontend. #### [hashtag](https://docs.openalgo.in/contributors#backend-technologies) Backend Technologies * **Python 3.12+** - Core programming language * **uv** - Fast Python package manager (replaces pip/venv) * **Flask 3.1+** - Lightweight web framework * **Flask-RESTX** - RESTful API with auto-generated Swagger documentation * **SQLAlchemy 2.0+** - Database ORM for data persistence * **Flask-SocketIO 5.6+** - Real-time WebSocket connections for live updates * **Flask-Login** - User session management and authentication * **Flask-WTF** - Form validation and CSRF protection * **Ruff** - Fast Python linter and formatter #### [hashtag](https://docs.openalgo.in/contributors#frontend-technologies) Frontend Technologies * **React 19** - Component-based UI library * **TypeScript 5.9+** - Type-safe JavaScript * **Vite 7+** - Fast build tool and dev server * **TailwindCSS 4** - Utility-first CSS framework * **shadcn/ui** (Radix UI) - Accessible component primitives * **TanStack Query 5** - Server state management * **Zustand 5** - Client state management * **React Router 7** - Client-side routing * **Plotly.js / Lightweight Charts** - Data visualization * **Socket.IO Client** - Real-time communication * **Biome.js** - Fast linter and formatter * **Vitest** - Unit testing framework * **Playwright** - End-to-end testing #### [hashtag](https://docs.openalgo.in/contributors#trading-and-data-libraries) Trading & Data Libraries * **pandas 2.3+** - Data manipulation and analysis * **numpy 2.0+** - Numerical computing * **DuckDB** - Historical market data storage * **httpx** - Modern HTTP client with HTTP/2 support * **websockets 15.0+** - WebSocket client and server * **pyzmq** - ZeroMQ for high-performance message queue * **APScheduler** - Background task scheduling * **scipy / py\_vollib / numba** - Options analytics and Greeks #### [hashtag](https://docs.openalgo.in/contributors#security-and-performance) Security & Performance * **argon2-cffi** - Secure password hashing * **cryptography** - Token encryption * **Flask-Limiter** - Rate limiting * **Flask-CORS** - CORS protection > \[!IMPORTANT\] You will need **Python 3.12+**, **Node.js 20/22/24**, and the **uv** package manager. * * * ### [hashtag](https://docs.openalgo.in/contributors#development-setup) Development Setup #### [hashtag](https://docs.openalgo.in/contributors#prerequisites) Prerequisites Before you begin, make sure you have the following installed: * **Python 3.12+** - [Download Pythonarrow-up-right](https://www.python.org/downloads/) * **Node.js 20, 22, or 24** - [Download Node.jsarrow-up-right](https://nodejs.org/) * **Git** - [Download Gitarrow-up-right](https://git-scm.com/downloads) * **Code Editor** - VS Code recommended with extensions: * Python * Pylance * Biome * Tailwind CSS IntelliSense * **Basic Knowledge** of Flask and React #### [hashtag](https://docs.openalgo.in/contributors#install-dependencies) Install Dependencies > \[!IMPORTANT\] **Always use** `**uv run**` **to run Python commands.** Never use global Python or manually manage virtual environments. The `uv` tool automatically creates and manages a `.venv` for the project. #### [hashtag](https://docs.openalgo.in/contributors#configure-environment) Configure Environment > \[!NOTE\] **Static IP whitelisting:** Many Indian brokers require you to whitelist a static IP address when generating API keys and secrets. If you are developing locally, you may need to whitelist your public IP. For cloud/VPS deployments, use the server's static IP. Check your broker's API documentation for specific requirements. * * * ### [hashtag](https://docs.openalgo.in/contributors#local-development) Local Development #### [hashtag](https://docs.openalgo.in/contributors#run-the-application) Run the Application #### [hashtag](https://docs.openalgo.in/contributors#development-workflow-with-multiple-terminals) Development Workflow with Multiple Terminals For the best development experience when working on the frontend, use two terminals: **Terminal 1 - React Dev Server (hot reload):** **Terminal 2 - Flask Backend:** > **Note:** The React dev server proxies API requests to the Flask backend. For production testing, build the frontend with `npm run build` and access everything through Flask at port 5000. #### [hashtag](https://docs.openalgo.in/contributors#production-mode-linux-only) Production Mode (Linux only) #### [hashtag](https://docs.openalgo.in/contributors#first-time-setup) First Time Setup 1. **Access the application**: Navigate to `http://127.0.0.1:5000` 2. **Setup account**: Go to `http://127.0.0.1:5000/setup` 3. **Create admin user**: Fill in the setup form 4. **Login**: Use your credentials to access the dashboard 5. **Configure broker**: Navigate to Settings and set up your broker #### [hashtag](https://docs.openalgo.in/contributors#access-points) Access Points * **Main app**: http://127.0.0.1:5000 * **React frontend**: http://127.0.0.1:5000/react * **Swagger API docs**: http://127.0.0.1:5000/api/docs * **API Analyzer**: http://127.0.0.1:5000/analyzer * * * ### [hashtag](https://docs.openalgo.in/contributors#project-structure) Project Structure Understanding the codebase structure will help you contribute effectively: #### [hashtag](https://docs.openalgo.in/contributors#key-directories) Key Directories * `**frontend/**`: React 19 SPA with TypeScript, built with Vite and served by Flask via `blueprints/react_app.py` * `**broker/**`: Each subdirectory contains a complete broker integration with `api/`, `database/`, `mapping/`, `streaming/`, and `plugin.json` * `**restx_api/**`: RESTful API endpoints with automatic Swagger documentation at `/api/docs` * `**blueprints/**`: Flask route handlers for UI pages and webhooks * `**services/**`: Business logic separated from route handlers * `**websocket_proxy/**`: Real-time market data streaming via unified WebSocket proxy * `**database/**`: 5 separate databases for isolation (main, logs, latency, sandbox, historify) * * * ### [hashtag](https://docs.openalgo.in/contributors#development-workflow) Development Workflow #### [hashtag](https://docs.openalgo.in/contributors#id-1.-fork-and-clone) 1\. Fork and Clone > **Important: Disable GitHub Actions on Your Fork** > > After forking, go to your fork's **Settings → Actions → General** (`https://github.com/YOUR_USERNAME/openalgo/settings/actions`) and select **"Disable actions"** under Actions permissions. This prevents CI workflows (frontend builds, Docker pushes) from running on your fork unnecessarily — those workflows are only meant to run on the upstream repository. #### [hashtag](https://docs.openalgo.in/contributors#id-2.-frontend-build-assets-auto-built-by-ci) 2\. Frontend Build Assets (Auto-Built by CI) The `/frontend/dist` directory is **gitignored** and not tracked in the repository. CI automatically builds the frontend when changes are merged to main. **How it works:** * PRs are tested with a fresh frontend build (but not committed) * When merged to main, CI automatically: 1. Builds the frontend (`cd frontend && npm run build`) 2. Pushes Docker image to Docker Hub **For Contributors:** * Build locally for development: `cd frontend && npm install && npm run build` * Do NOT commit `frontend/dist/` — it is gitignored * Focus on source code changes — CI handles production builds #### [hashtag](https://docs.openalgo.in/contributors#id-3.-create-a-feature-branch) 3\. Create a Feature Branch #### [hashtag](https://docs.openalgo.in/contributors#id-4.-make-your-changes) 4\. Make Your Changes Follow these guidelines while developing: **Python Code Style** * Follow PEP 8 style guide * Use 4 spaces for indentation * Maximum 100 characters line length (configured in Ruff) * Imports: Standard library → Third-party → Local * Use Google-style docstrings Run the linter: **React/TypeScript Code Style** * Follow Biome.js rules (configured in `frontend/biome.json`) * Use functional components with hooks * Component files use PascalCase: `MyComponent.tsx` * Use TanStack Query for server state, Zustand for client state Run the linter: **Commit Messages** We follow **Conventional Commits** specification: * `feat:` - New features * `fix:` - Bug fixes * `docs:` - Documentation changes * `style:` - Code style changes (formatting, no logic change) * `refactor:` - Code refactoring * `test:` - Adding or updating tests * `chore:` - Maintenance tasks Examples: #### [hashtag](https://docs.openalgo.in/contributors#id-5.-test-your-changes) 5\. Test Your Changes **Testing Checklist** * Application starts without errors (`uv run app.py`) * All existing features still work * New feature works as expected * Python tests pass (`uv run pytest test/ -v`) * Frontend tests pass (`cd frontend && npm test`) * No TypeScript errors (`cd frontend && npm run build`) * No linting errors (Ruff for Python, Biome for frontend) * API endpoints return correct responses * WebSocket connections work (if applicable) #### [hashtag](https://docs.openalgo.in/contributors#id-6.-push-to-your-fork) 6\. Push to Your Fork #### [hashtag](https://docs.openalgo.in/contributors#id-7.-create-a-pull-request) 7\. Create a Pull Request 1. Go to your fork on GitHub 2. Click **"Compare & pull request"** 3. Fill out the PR template: * **Title**: Clear, descriptive title * **Description**: What does this PR do? * **Related Issues**: Link related issues (e.g., "Closes #123") * **Screenshots**: For UI changes, include before/after screenshots * **Testing**: Describe how you tested the changes * **Checklist**: Complete the PR checklist * * * ### [hashtag](https://docs.openalgo.in/contributors#contributing-guidelines) Contributing Guidelines #### [hashtag](https://docs.openalgo.in/contributors#contribution-policy-one-feature-or-one-fix-at-a-time) Contribution Policy: One Feature or One Fix at a Time OpenAlgo follows a strict **incremental contribution** standard. We require all contributions to be submitted as: * **One feature** per pull request, OR * **One fix** per pull request **Why this matters:** OpenAlgo supports **a growing list of brokers**, and every change must be validated across this broad surface area. Large integrations submitted in a single PR require extensive manual testing and verification that is not practical for the maintainers to review all at once. Additionally, many contributions today are developed with AI assistance, which can accelerate development substantially but also increases the need for careful human review, testing, and incremental verification before acceptance into a shared upstream project. **What this means in practice:** * Break large features into small, self-contained pull requests * Each PR should be independently reviewable and testable * Submit them sequentially — wait for one to be reviewed before sending the next * Large monolithic PRs or full-project integrations will not be accepted in their current form * **Exception — New broker integrations** may be submitted as a single PR since they are self-contained within their own `broker/` directory and don't modify core platform code **If you have a large integration or project built on OpenAlgo:** We appreciate and encourage projects built on top of OpenAlgo (it's why we're open-source!). However, we cannot merge large codebases as a single contribution. Instead, extract individual improvements, fixes, or self-contained features and submit them separately. This gives each contribution a much better chance of being reviewed and accepted. * * * #### [hashtag](https://docs.openalgo.in/contributors#what-can-you-contribute) What Can You Contribute? **For First-Time Contributors** Great ways to get started: 1. **Documentation** * Fix typos in README or docs * Improve installation instructions * Add examples and tutorials 2. **Bug Fixes** * Check [issues labeled "good first issue"arrow-up-right](https://github.com/marketcalls/openalgo/labels/good%20first%20issue) * Fix minor bugs and edge cases * Improve error messages 3. **UI Improvements** * Enhance React components * Improve mobile responsiveness * Add loading states and animations * Fix layout issues 4. **Examples** * Add strategy examples in `/strategies` * Create tutorial notebooks * Document common use cases **For Experienced Contributors** More advanced contributions: 1. **New Broker Integration** * Add support for new brokers * Complete implementation guide in next section * Requires understanding of broker APIs 2. **API Endpoints** * Implement new trading features * Enhance existing endpoints * Add new data sources 3. **React Frontend Features** * Build new pages or components * Add data visualizations with Plotly/Lightweight Charts * Improve real-time updates via Socket.IO 4. **Performance Optimization** * Optimize database queries * Improve caching strategies * Reduce API latency 5. **WebSocket Features** * Add new streaming capabilities * Improve real-time performance * Add broker WebSocket adapters 6. **Testing** * Write Vitest unit tests for React components * Write Playwright end-to-end tests * Write pytest tests for backend services * Improve test coverage 7. **Security Enhancements** * Audit security vulnerabilities * Improve authentication * Enhance encryption * * * ### [hashtag](https://docs.openalgo.in/contributors#testing) Testing #### [hashtag](https://docs.openalgo.in/contributors#python-backend-tests) Python Backend Tests #### [hashtag](https://docs.openalgo.in/contributors#react-frontend-tests) React Frontend Tests #### [hashtag](https://docs.openalgo.in/contributors#writing-python-tests) Writing Python Tests #### [hashtag](https://docs.openalgo.in/contributors#writing-react-tests) Writing React Tests #### [hashtag](https://docs.openalgo.in/contributors#writing-e2e-tests) Writing E2E Tests * * * ### [hashtag](https://docs.openalgo.in/contributors#adding-a-new-broker) Adding a New Broker One of the most valuable contributions is adding support for new brokers. Here's a comprehensive guide: #### [hashtag](https://docs.openalgo.in/contributors#id-1.-broker-integration-structure) 1\. Broker Integration Structure Create a new directory under `/broker/your_broker_name/`: #### [hashtag](https://docs.openalgo.in/contributors#id-2.-implement-required-modules) 2\. Implement Required Modules **2.1 Authentication API (**`**api/auth_api.py**`**)** **2.2 Order API (**`**api/order_api.py**`**)** **2.3 Data API (**`**api/data.py**`**)** **2.4 Plugin Configuration (**`**plugin.json**`**)** #### [hashtag](https://docs.openalgo.in/contributors#id-3.-testing-your-broker-integration) 3\. Testing Your Broker Integration 1. Add broker to `VALID_BROKERS` in `.env` 2. Configure broker credentials in `.env` 3. Test authentication flow 4. Test each API endpoint via Swagger UI at `/api/docs` 5. Test WebSocket streaming (if supported) 6. Validate error handling #### [hashtag](https://docs.openalgo.in/contributors#id-4.-reference-implementations) 4\. Reference Implementations Study existing broker implementations: * `/broker/zerodha/` - Most complete implementation * `/broker/dhan/` - Modern API design * `/broker/angel/` - WebSocket streaming * * * ### [hashtag](https://docs.openalgo.in/contributors#frontend-development) Frontend Development #### [hashtag](https://docs.openalgo.in/contributors#react--shadcn-ui-architecture) React + shadcn/ui Architecture The frontend is a React 19 SPA located in `/frontend/`. It is built with Vite and served by Flask in production via `blueprints/react_app.py`. **Development Server** **Component Library** OpenAlgo uses [shadcn/uiarrow-up-right](https://ui.shadcn.com/) built on Radix UI primitives with Tailwind CSS: **Server State with TanStack Query** **Client State with Zustand** **Styling with Tailwind CSS 4** Use Tailwind utility classes directly. Always use responsive and theme-aware patterns: **Linting and Formatting** * * * ### [hashtag](https://docs.openalgo.in/contributors#documentation) Documentation #### [hashtag](https://docs.openalgo.in/contributors#code-documentation) Code Documentation 1. **Python Docstrings** - Use Google-style: 2. **TypeScript** - Use JSDoc where types alone aren't sufficient: 3. **API Documentation** - Use Flask-RESTX decorators: * * * ### [hashtag](https://docs.openalgo.in/contributors#best-practices) Best Practices #### [hashtag](https://docs.openalgo.in/contributors#security) Security 1. **Never commit sensitive data** 2. **Validate all inputs at system boundaries** 3. **Use parameterized queries (SQLAlchemy ORM)** 4. **Follow OWASP guidelines** * Enable CSRF protection (already configured) * Use HTTPS in production * Rate limiting is configured per endpoint * Sanitize user inputs #### [hashtag](https://docs.openalgo.in/contributors#performance) Performance 1. **Optimize database queries** 2. **Use caching** 3. **Minimize API calls — use batch endpoints** #### [hashtag](https://docs.openalgo.in/contributors#code-quality) Code Quality 1. **Write self-documenting code** 2. **Keep functions small and focused** 3. **Return consistent JSON responses from API endpoints** * * * ### [hashtag](https://docs.openalgo.in/contributors#troubleshooting) Troubleshooting #### [hashtag](https://docs.openalgo.in/contributors#common-issues) Common Issues **Frontend Build Errors** **Python Dependency Issues** **WebSocket Connection Issues** **Database Locked Errors** * * * ### [hashtag](https://docs.openalgo.in/contributors#getting-help) Getting Help #### [hashtag](https://docs.openalgo.in/contributors#support-channels) Support Channels * **Discord**: Join our [Discord serverarrow-up-right](https://discord.com/invite/UPh7QPsNhP) for real-time help * **GitHub Discussions**: Ask questions in [GitHub Discussionsarrow-up-right](https://github.com/marketcalls/openalgo/discussions) * **Documentation**: Check [docs.openalgo.inarrow-up-right](https://docs.openalgo.in/) * **GitHub Issues**: Report bugs in [Issuesarrow-up-right](https://github.com/marketcalls/openalgo/issues) #### [hashtag](https://docs.openalgo.in/contributors#before-asking-for-help) Before Asking for Help 1. **Search existing issues** — your question might already be answered 2. **Check documentation** — review docs at docs.openalgo.in 3. **Review error logs** — include error messages when asking for help 4. **Provide context** — share your environment (OS, Python version, Node version, broker) #### [hashtag](https://docs.openalgo.in/contributors#asking-good-questions) Asking Good Questions When asking for help, include: 1. **Clear description** of the problem 2. **Steps to reproduce** the issue 3. **Expected behavior** vs **actual behavior** 4. **Error messages** (full stack trace) 5. **Environment details**: * OS and version * Python version (`python --version`) * Node.js version (`node --version`) * OpenAlgo version * Broker being used * * * ### [hashtag](https://docs.openalgo.in/contributors#code-review-process) Code Review Process After submitting your pull request: 1. **Automated Checks** * CI will build the frontend and run linting * Ensure all checks pass before requesting review 2. **Review Feedback** * Address reviewer comments promptly * Ask questions if feedback is unclear * Make requested changes in new commits 3. **Updates** * Push additional commits to your branch * No need to create a new PR 4. **Approval & Merge** * Once approved, maintainers will merge * CI will automatically build the frontend for production 5. **Be Patient** * Reviews may take a few days * Maintainers are volunteers * Ping politely if no response after a week * * * ### [hashtag](https://docs.openalgo.in/contributors#recognition-and-community) Recognition & Community We value all contributions! Contributors will be: * **Listed in contributors section** on GitHub * **Mentioned in release notes** for significant contributions * **Part of the OpenAlgo community** on Discord #### [hashtag](https://docs.openalgo.in/contributors#community-guidelines) Community Guidelines 1. **Be Respectful** - Treat everyone with respect 2. **Be Constructive** - Provide helpful feedback 3. **Be Patient** - Remember everyone is learning 4. **Be Inclusive** - Welcome contributors of all skill levels 5. **Be Professional** - Keep discussions focused on code * * * ### [hashtag](https://docs.openalgo.in/contributors#quick-reference-links) Quick Reference Links * **Repository**: [github.com/marketcalls/openalgoarrow-up-right](https://github.com/marketcalls/openalgo) * **Issue Tracker**: [github.com/marketcalls/openalgo/issuesarrow-up-right](https://github.com/marketcalls/openalgo/issues) * **Documentation**: [docs.openalgo.inarrow-up-right](https://docs.openalgo.in/) * **Discord**: [discord.com/invite/UPh7QPsNhParrow-up-right](https://discord.com/invite/UPh7QPsNhP) * **PyPI Package**: [pypi.org/project/openalgoarrow-up-right](https://pypi.org/project/openalgo) * **YouTube**: [youtube.com/@openalgoHQarrow-up-right](https://youtube.com/@openalgoHQ) * **Twitter/X**: [@openalgoHQarrow-up-right](https://twitter.com/openalgoHQ) * * * ### [hashtag](https://docs.openalgo.in/contributors#license) License OpenAlgo is released under the **AGPL v3.0 License**. See the LICENSE file for details. By contributing to OpenAlgo, you agree that your contributions will be licensed under the AGPL v3.0 License. * * * ### [hashtag](https://docs.openalgo.in/contributors#thank-you) Thank You! Thank you for contributing to OpenAlgo! Your efforts help democratize algorithmic trading and empower traders worldwide. Every line of code, documentation improvement, and bug report makes a difference. **Happy coding, and welcome to the OpenAlgo community!** * * * _Built by traders, for traders — making algo trading accessible to everyone._ [PreviousCompliancechevron-left](https://docs.openalgo.in/compliance) [NextMonetizationchevron-right](https://docs.openalgo.in/monetization) Last updated 26 days ago * [Let's democratize algorithmic trading, together!](https://docs.openalgo.in/contributors#lets-democratize-algorithmic-trading-together) * [Our Mission](https://docs.openalgo.in/contributors#our-mission) * [Table of Contents](https://docs.openalgo.in/contributors#table-of-contents) * [Technology Stack](https://docs.openalgo.in/contributors#technology-stack) * [Development Setup](https://docs.openalgo.in/contributors#development-setup) * [Local Development](https://docs.openalgo.in/contributors#local-development) * [Project Structure](https://docs.openalgo.in/contributors#project-structure) * [Development Workflow](https://docs.openalgo.in/contributors#development-workflow) * [Contributing Guidelines](https://docs.openalgo.in/contributors#contributing-guidelines) * [Testing](https://docs.openalgo.in/contributors#testing) * [Adding a New Broker](https://docs.openalgo.in/contributors#adding-a-new-broker) * [Frontend Development](https://docs.openalgo.in/contributors#frontend-development) * [Documentation](https://docs.openalgo.in/contributors#documentation) * [Best Practices](https://docs.openalgo.in/contributors#best-practices) * [Troubleshooting](https://docs.openalgo.in/contributors#troubleshooting) * [Getting Help](https://docs.openalgo.in/contributors#getting-help) * [Code Review Process](https://docs.openalgo.in/contributors#code-review-process) * [Recognition & Community](https://docs.openalgo.in/contributors#recognition-and-community) * [Quick Reference Links](https://docs.openalgo.in/contributors#quick-reference-links) * [License](https://docs.openalgo.in/contributors#license) * [Thank You!](https://docs.openalgo.in/contributors#thank-you) sun-brightdesktopmoon Copy # Clone the repository git clone https://github.com/marketcalls/openalgo.git cd openalgo # Install uv package manager (if not already installed) pip install uv # Sync Python dependencies (uv handles virtualenv automatically) uv sync # Build React frontend (required before first run) cd frontend npm install npm run build cd .. Copy # Copy the sample environment file cp .sample.env .env # Generate secure random keys for APP_KEY and API_KEY_PEPPER: uv run python -c "import secrets; print(secrets.token_hex(32))" # Edit .env and update: # 1. APP_KEY (paste generated key) # 2. API_KEY_PEPPER (paste another generated key) # 3. VALID_BROKERS (comma-separated list of brokers to enable) # 4. Broker API credentials Copy # Development mode (auto-reloads on backend code changes) uv run app.py # Application will be available at http://127.0.0.1:5000 Copy cd frontend npm run dev # Frontend dev server at http://localhost:5173 with hot module replacement Copy uv run app.py # Backend API at http://127.0.0.1:5000 Copy # Run with Gunicorn uv run gunicorn --worker-class eventlet -w 1 app:app # IMPORTANT: Use -w 1 (one worker) for WebSocket compatibility Copy openalgo/ ├── app.py # Main Flask application entry point ├── pyproject.toml # Python dependencies & tool config (uv/ruff/pytest) ├── frontend/ # React 19 SPA (TypeScript + Vite) │ ├── src/ │ │ ├── components/ # React components (shadcn/ui based) │ │ ├── pages/ # Route-level page components │ │ ├── hooks/ # Custom React hooks │ │ ├── api/ # API client functions │ │ ├── stores/ # Zustand state stores │ │ ├── lib/ # Utility functions │ │ └── App.tsx # Root component with routing │ ├── package.json # Node.js dependencies │ ├── biome.json # Biome linter/formatter config │ ├── tsconfig.json # TypeScript configuration │ ├── vite.config.ts # Vite build configuration │ └── dist/ # Production build output (gitignored) ├── blueprints/ # Flask blueprints for web routes │ ├── auth.py # Authentication routes │ ├── react_app.py # Serves React SPA from frontend/dist/ │ └── ... ├── broker/ # Broker integrations (24+ brokers) │ ├── zerodha/ # Reference implementation │ ├── dhan/ # Modern API design │ ├── angel/ # AngelOne integration │ └── .../ # Each broker follows standardized structure ├── restx_api/ # REST API endpoints (/api/v1/) ├── services/ # Business logic layer ├── database/ # SQLAlchemy models and database utilities ├── utils/ # Shared utilities and helpers ├── websocket_proxy/ # Unified WebSocket server (port 8765) ├── test/ # Python test files ├── strategies/ # Trading strategy examples ├── db/ # SQLite/DuckDB database files └── .env # Environment config (create from .sample.env) Copy # 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 Copy # Update your main branch git checkout main git pull upstream main # Create a new branch for your feature # Branch naming convention: # - feature/feature-name : New features # - bugfix/bug-name : Bug fixes # - docs/doc-name : Documentation # - refactor/refactor-name : Code refactoring git checkout -b feature/your-feature-name Copy # Check Python code uv run ruff check . # Auto-fix issues uv run ruff check --fix . # Format code uv run ruff format . Copy cd frontend # Lint code npm run lint # Format code npm run format # Lint + format in one command npm run check Copy git commit -m "feat: add Groww broker integration" git commit -m "fix: correct margin calculation for options" git commit -m "docs: update WebSocket setup instructions" git commit -m "refactor: optimize order processing pipeline" Copy # Run Python tests uv run pytest test/ -v # Run React tests cd frontend npm test # Run end-to-end tests npm run e2e # Manual testing: # 1. Web UI: http://127.0.0.1:5000 # 2. React UI: http://127.0.0.1:5000/react # 3. API Docs: http://127.0.0.1:5000/api/docs # 4. API Analyzer: http://127.0.0.1:5000/analyzer Copy # Add your changes git add . # Commit with conventional commit message git commit -m "feat: add your feature description" # Push to your fork git push origin feature/your-feature-name Copy # Run all tests uv run pytest test/ -v # Run specific test file uv run pytest test/test_broker.py -v # Run single test function uv run pytest test/test_broker.py::test_function_name -v # Run tests with coverage uv run pytest test/ --cov Copy cd frontend # Run unit tests (watch mode) npm test # Run tests once npm run test:run # Run tests with coverage npm run test:coverage # Run accessibility tests npm run test:a11y # Run end-to-end tests (Playwright) npm run e2e # Run e2e tests with UI npm run e2e:ui Copy # test/test_feature.py import pytest def test_feature(): """Test your feature here.""" result = some_function() assert result == expected_value Copy // frontend/src/components/__tests__/MyComponent.test.tsx import { render, screen } from '@testing-library/react'; import { describe, it, expect } from 'vitest'; import { MyComponent } from '../MyComponent'; describe('MyComponent', () => { it('renders correctly', () => { render(); expect(screen.getByText('Expected Text')).toBeInTheDocument(); }); }); Copy // frontend/e2e/my-feature.spec.ts import { test, expect } from '@playwright/test'; test('feature works end to end', async ({ page }) => { await page.goto('/react'); await expect(page.getByText('Dashboard')).toBeVisible(); }); Copy broker/your_broker_name/ ├── api/ │ ├── auth_api.py # Authentication and session management │ ├── order_api.py # Order placement, modification, cancellation │ ├── data.py # Market data, quotes, historical data │ └── funds.py # Account balance and margin ├── database/ │ └── master_contract_db.py # Symbol master contract management ├── mapping/ │ ├── order_data.py # Transform OpenAlgo format to broker format │ └── transform_data.py # General data transformations ├── streaming/ │ └── broker_adapter.py # WebSocket adapter for live data └── plugin.json # Broker configuration metadata Copy """Authentication module for BrokerName.""" def authenticate_broker(data): """Authenticate user with broker. Args: data (dict): Authentication credentials Returns: dict: Authentication response with status and token """ pass def get_auth_token(): """Retrieve stored authentication token. Returns: str: Active auth token or None """ pass Copy """Order management module for BrokerName.""" def place_order_api(data): """Place a new order with the broker.""" pass def modify_order_api(data): """Modify an existing order.""" pass def cancel_order_api(order_id): """Cancel an order.""" pass def get_order_book(): """Get all orders for the day.""" pass def get_trade_book(): """Get all executed trades.""" pass def get_positions(): """Get current open positions.""" pass def get_holdings(): """Get demat holdings.""" pass Copy """Market data module for BrokerName.""" def get_quotes(symbols): """Get real-time quotes for symbols.""" pass def get_market_depth(symbol): """Get market depth/order book.""" pass def get_historical_data(symbol, interval, start_date, end_date): """Get historical OHLC data.""" pass Copy { "broker_name": "brokername", "display_name": "Broker Name", "version": "1.0.0", "auth_type": "oauth2", "api_base_url": "https://api.broker.com", "features": { "place_order": true, "modify_order": true, "cancel_order": true, "websocket": true, "market_depth": true, "historical_data": true } } Copy cd frontend # Start Vite dev server with hot reload npm run dev # Available at http://localhost:5173 # Build for production npm run build # Output goes to frontend/dist/ Copy import { Button } from '@/components/ui/button'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; function PortfolioCard() { return ( Portfolio Value

₹1,25,000

); } Copy import { useQuery } from '@tanstack/react-query'; function Positions() { const { data, isLoading, error } = useQuery({ queryKey: ['positions'], queryFn: () => api.getPositions(), }); if (isLoading) return
Loading...
; // render positions... } Copy import { create } from 'zustand'; interface AppState { selectedBroker: string; setSelectedBroker: (broker: string) => void; } const useAppStore = create((set) => ({ selectedBroker: '', setSelectedBroker: (broker) => set({ selectedBroker: broker }), })); Copy {/* Responsive grid */}
Column 1
Column 2
Column 3
{/* Use CSS variables for theme colors — adapts to light/dark mode */}
Automatically adapts to theme
Copy cd frontend # Lint npm run lint # Format npm run format # Both (with auto-fix) npm run check Copy def place_order(symbol, quantity, price, order_type): """Place a trading order. Args: symbol (str): Trading symbol in OpenAlgo format quantity (int): Number of shares/contracts price (float): Order price (0 for market orders) order_type (str): Order type ('MARKET', 'LIMIT', 'SL') Returns: dict: Order response with order_id and status Raises: ValueError: If invalid order_type provided """ pass Copy /** * Fetches positions for the current user. * Requires active broker authentication. */ async function getPositions(): Promise { // ... } Copy @api.route('/placeorder') class PlaceOrder(Resource): @api.doc(description='Place a new order') @api.expect(order_model) @api.marshal_with(order_response_model) def post(self): """Place a trading order.""" pass Copy # Bad - Never do this! API_KEY = 'abc123xyz' # Good - Use environment variables import os API_KEY = os.getenv('BROKER_API_KEY') Copy def place_order(data): if data.get('quantity', 0) <= 0: raise ValueError('Quantity must be positive') valid_types = ['MARKET', 'LIMIT', 'SL', 'SLM'] if data.get('order_type') not in valid_types: raise ValueError('Invalid order type') Copy # Bad - SQL injection vulnerability! query = f"SELECT * FROM orders WHERE user_id = {user_id}" # Good - SQLAlchemy ORM orders = Order.query.filter_by(user_id=user_id).all() Copy # Bad - N+1 query problem for user in users: orders = Order.query.filter_by(user_id=user.id).all() # Good - Use eager loading from sqlalchemy.orm import joinedload users = User.query.options(joinedload(User.orders)).all() Copy from cachetools import TTLCache symbol_cache = TTLCache(maxsize=1000, ttl=300) def get_symbol_info(symbol): if symbol in symbol_cache: return symbol_cache[symbol] info = fetch_symbol_from_db(symbol) symbol_cache[symbol] = info return info Copy # Bad - Multiple API calls for symbol in symbols: quote = broker.get_quote(symbol) # Good - Batch API call quotes = broker.get_quotes_batch(symbols) Copy # Bad def calc(s, q, p): return s * q * p * 0.1 # Good def calculate_order_value(symbol_price, quantity, price, multiplier): return symbol_price * quantity * price * multiplier Copy return { 'status': 'success' | 'error', 'message': 'Human-readable message', 'data': {...} # Optional payload } Copy # Ensure correct Node.js version (20, 22, or 24) node --version # Clean install cd frontend rm -rf node_modules npm install npm run build # Check for TypeScript errors npx tsc --noEmit Copy # Sync dependencies with uv uv sync # If issues persist, recreate the environment rm -rf .venv uv sync Copy # Check WebSocket configuration in .env: WEBSOCKET_HOST='127.0.0.1' WEBSOCKET_PORT='8765' # Ensure only one worker with Gunicorn: uv run gunicorn --worker-class eventlet -w 1 app:app # Check firewall settings for port 8765 Copy # SQLite doesn't handle high concurrency well # Close all connections and restart the app uv run app.py sun-brightdesktopmoon --- # Ubuntu Server Installation | Documentation ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#undefined) ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#prerequisites) Prerequisites #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#system-requirements) System Requirements * Ubuntu Server (22.04 LTS or later recommended) * Minimum 0.5GB RAM * Clean installation recommended #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#domain-and-dns-setup-required) Domain and DNS Setup (Required) 1. **Cloudflare Account Setup** * Create a Cloudflare account if you don't have one * Add your domain to Cloudflare * Update your domain's nameservers to Cloudflare's nameservers 2. **DNS Configuration** * Add an A record pointing to your server's IP address * Add a CNAME record for the domain (optional). Not required for sub.yourdomain.com 3. **SSL/TLS Configuration in Cloudflare** * Go to SSL/TLS section * Set encryption mode to "Full (strict)" #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#broker-setup-required) Broker Setup (Required) * Obtain your broker's API credentials as per the openalgo documentation: * API Key * API Secret * Prepare the Redirection URL as per your domain name and broker name ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#login-to-the-ubuntu-server) Login to the Ubuntu Server ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#installation-steps) Installation Steps #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#id-1.-download-installation-script) 1\. Download Installation Script #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#id-2.-run-installation-script) 2\. Run Installation Script The script will interactively prompt you for: * Your domain name (supports both root domains and subdomains) * Broker selection * Broker API credentials The installation process will: * Install required packages * Configure Nginx with SSL * Set up the OpenAlgo application * Create systemd service with unique name based on domain and broker * Generate installation logs in the logs directory **Multi-Domain Deployment** The installation script supports deploying multiple instances on the same server: * Each deployment gets a unique service name (e.g., openalgo-yourdomain-broker) * Separate configuration files and directories for each deployment * Individual log files for each installation in the logs directory * Independent SSL certificates for each domain * Isolated Python virtual environments Example of running multiple deployments: Each deployment will: * Have its own systemd service * Use separate configuration files * Store logs in unique timestamped files * Run independently of other deployments #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#id-3.-verify-installation) 3\. Verify Installation After installation completes, verify each deployment: 1. **Check Service Status** 2. **Verify Nginx Configuration** 3. **Access Web Interfaces** Test each deployment in your web browser: 4. **Check Installation Logs** ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#troubleshooting) Troubleshooting #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#common-issues) Common Issues 1. **SSL Certificate Issues** 2. **Application Not Starting** Example scenario: Managing multiple broker deployments 3. **Nginx Issues** 4. **Installation Logs** Example: Checking installation logs for multiple deployments #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#managing-multiple-deployments) Managing Multiple Deployments 1. **Service Management Examples** 2. **Log Management Examples** 3. **Nginx Configuration Examples** 4. **Installation Directory Examples** ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#security-notes) Security Notes 1. **Firewall** * The installation configures UFW to allow only HTTP, HTTPS, and SSH * Additional ports can be opened if needed: 2. **SSL/TLS** * Certificates are automatically renewed by Certbot * The installation configures modern SSL parameters * Regular updates are recommended: ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#post-installation) Post-Installation 1. Configure your broker settings in the web interface 2. Set up monitoring and alerts if needed 3. Regularly check logs for any issues 4. Keep the system updated with security patches ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#support) Support For issues and support: * Check the [GitHub repositoryarrow-up-right](https://github.com/marketcalls/openalgo) * Review the logs using commands provided above * Contact support with relevant log information Remember to: * Regularly backup your configuration * Monitor system resources * Keep the system updated * Review security best practices [PreviousUbuntu (No Custom Domain)chevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-no-custom-domain) [NextDocker + Custom Domainchevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/docker-+-custom-domain) Last updated 9 months ago * [](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#undefined) * [Prerequisites](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#prerequisites) * [Login to the Ubuntu Server](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#login-to-the-ubuntu-server) * [Installation Steps](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#installation-steps) * [Troubleshooting](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#troubleshooting) * [Security Notes](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#security-notes) * [Post-Installation](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#post-installation) * [Support](https://docs.openalgo.in/installation-guidelines/getting-started/ubuntu-server-installation#support) sun-brightdesktopmoon Copy Type: A Name: yourdomain.com Content: YOUR_SERVER_IP Proxy status: Proxied Copy Type: CNAME Name: www Content: yourdomain.com Proxy status: Proxied Copy # Example - domain name is yourdomain.com and broker is zerodha https://yourdomain.com/zerodha/callback # Example - domain name is sub.yourdomain.com and broker is angel https://sub.yourdomain.com/angel/callback Copy # Connect to your Ubuntu server via SSH # example ssh [email protected] ssh user@your_server_ip Copy # 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 # Make the script executable chmod +x install.sh Copy # Execute the installation script sudo ./install.sh Copy # First deployment sudo ./install.sh # Enter domain: trading1.yourdomain.com # Enter broker: fyers # Second deployment sudo ./install.sh # Enter domain: trading2.yourdomain.com # Enter broker: zerodha Copy # Example for Fyers deployment sudo systemctl status openalgo-fyers-yourdomain-fyers # Example for Zerodha deployment sudo systemctl status openalgo-zerodha-yourdomain-zerodha Copy # Test overall Nginx configuration sudo nginx -t # Check specific site configurations ls -l /etc/nginx/sites-enabled/ cat /etc/nginx/sites-enabled/fyers.yourdomain.com cat /etc/nginx/sites-enabled/zerodha.yourdomain.com Copy https://fyers.yourdomain.com https://zerodha.yourdomain.com Copy # View the installation log for your deployment cat install/logs/install_YYYYMMDD_HHMMSS.log Copy # Check Certbot logs sudo journalctl -u certbot # Example: Manually run certificate installation for trading.yourdomain.com sudo certbot --nginx -d trading.yourdomain.com # Example: Manually run certificate installation for multiple subdomains sudo certbot --nginx -d fyers.yourdomain.com -d zerodha.yourdomain.com Copy # Example 1: Fyers deployment on fyers.yourdomain.com sudo journalctl -u openalgo-fyers-yourdomain-fyers # View logs sudo systemctl restart openalgo-fyers-yourdomain-fyers # Restart service # Example 2: Zerodha deployment on zerodha.yourdomain.com sudo journalctl -u openalgo-zerodha-yourdomain-zerodha # View logs sudo systemctl restart openalgo-zerodha-yourdomain-zerodha # Restart service Copy # Check Nginx error logs for all deployments sudo tail -f /var/log/nginx/error.log # Check access logs for specific domains sudo tail -f /var/log/nginx/fyers.yourdomain.com.access.log sudo tail -f /var/log/nginx/zerodha.yourdomain.com.access.log Copy # 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 Copy # List all OpenAlgo services systemctl list-units "openalgo-*" # Example outputs: # openalgo-fyers-yourdomain-fyers.service loaded active running # openalgo-zerodha-yourdomain-zerodha.service loaded active running # Restart specific deployment sudo systemctl restart openalgo-fyers-yourdomain-fyers # Check status of specific deployment sudo systemctl status openalgo-zerodha-yourdomain-zerodha Copy # View real-time logs for Fyers deployment sudo journalctl -f -u openalgo-fyers-yourdomain-fyers # View last 100 lines of Zerodha deployment logs sudo journalctl -n 100 -u openalgo-zerodha-yourdomain-zerodha # View logs since last hour for specific deployment sudo journalctl --since "1 hour ago" -u openalgo-fyers-yourdomain-fyers Copy # View Nginx configs for different deployments sudo nano /etc/nginx/sites-available/fyers.yourdomain.com sudo nano /etc/nginx/sites-available/zerodha.yourdomain.com # Test Nginx configuration sudo nginx -t # Reload Nginx after config changes sudo systemctl reload nginx Copy # List deployment directories ls -l /var/python/openalgo-flask/ # Example structure: # /var/python/openalgo-flask/fyers-yourdomain-fyers/ # /var/python/openalgo-flask/zerodha-yourdomain-zerodha/ # Check specific deployment files ls -l /var/python/openalgo-flask/fyers-yourdomain-fyers/ Copy sudo ufw allow Copy sudo apt update && sudo apt upgrade -y sun-brightdesktopmoon --- # Tradingview | Documentation TradingView is a popular charting and analysis platform used by traders for market analysis, and it also offers features that support automated trading through the use of webhooks. Automated trading works. #### [hashtag](https://docs.openalgo.in/trading-platform/tradingview#what-is-a-webhook) What is a Webhook? A webhook is a method for an app to provide other applications with real-time information. A webhook delivers data to other applications as it happens, meaning you get data immediately. In the context of TradingView, webhooks are used to send signals or alerts to external systems (like a brokerage or a trading bot) whenever certain predefined conditions are met. #### [hashtag](https://docs.openalgo.in/trading-platform/tradingview#setting-up-automated-trading-using-tradingview-webhooks) Setting up Automated Trading using TradingView Webhooks 1. **Define Trading Strategy**: First, you create a trading strategy in TradingView using its Pine Script programming language. This strategy could be based on technical analysis indicators, patterns, or other criteria. 2. **Configure Alerts**: Once your strategy is defined, you set up alerts in TradingView that trigger when specific conditions of your strategy are met. These conditions could be anything that your strategy considers a signal, such as the crossing of moving averages or reaching a certain RSI level. 3. **Set Up Webhook URL**: In the alert settings, you specify a webhook URL to which TradingView will send POST requests when the alert conditions are triggered. This URL is typically provided by the external service or trading bot that will execute the trades on your behalf. It's essential to ensure that this service can accept and process TradingView's webhook notifications. **OpenAlgo Configuration** > Ensure that if you are a windows user ngrok host url is setup and configured in the .env file. If you are linux user ensure that host name (domain name/ip address) is configured in the .env file Login to the OpenAlgo Application and go to the tab **Tradingview**. The page comes with **Tradingview JSON Generator.** Enter the valid trading **symbol**, select the **product** type, and press the **Generate JSON** Button ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F46F4Y9BVSzhJsd4DFWQG%252Fimage.png%3Falt%3Dmedia%26token%3D0d66f4e3-fec0-4069-936d-d31aaab5f5f2&width=768&dpr=3&quality=100&sign=e7095c47&sv=2) Copy the Webhook URL and the Alert Message for a Tradingview Strategy and configure the same in your tradingview strategy ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FfLeZ0Lzi5riIJTO2bG9d%252Fimage.png%3Falt%3Dmedia%26token%3D7b33b0e7-29ee-4143-a9f4-27fa1a3dd056&width=768&dpr=3&quality=100&sign=693d379c&sv=2) Enter the Webhook URL ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FtXgQtKTTMHu8Yjqs8t6u%252Fimage.png%3Falt%3Dmedia%26token%3D1d5eed9b-5b6c-484b-9266-fd1b2d0ec9a5&width=768&dpr=3&quality=100&sign=c8887a33&sv=2) [PreviousTelegram EOD Alertchevron-left](https://docs.openalgo.in/trading-platform/amibroker/telegram-eod-alert) [NextFutures to Options Modulechevron-right](https://docs.openalgo.in/trading-platform/tradingview/futures-to-options-module) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Skills | Documentation Skills are reusable capabilities for AI agents. Install them with a single command to enhance your agents with access to procedural knowledge. Skills are designed to work with a wide range of AI agent frameworks and tools, helping make agents more capable and consistent. Each skill encapsulates structured instructions and sometimes executable logic. That means instead of telling an agent how to do something from scratch with prompts, you can install a skill that encodes that knowledge for reuse [PreviousSymbol Formatchevron-left](https://docs.openalgo.in/symbol-format) [NextIndicatorschevron-right](https://docs.openalgo.in/skills/indicators) Last updated 1 month ago sun-brightdesktopmoon sun-brightdesktopmoon --- # API Collections | Documentation The OpenAlgo API Collections are a comprehensive set of tools designed to streamline your journey into algorithmic trading. Hosted on [GitHubarrow-up-right](https://github.com/marketcalls/openalgo/tree/main/collections) , these collections offer an intuitive and ready-to-use interface to interact with OpenAlgo’s powerful capabilities, making it easier for developers, traders, and enthusiasts to integrate and automate trading strategies. [Postman Collectionsarrow-up-right](https://github.com/marketcalls/openalgo/blob/main/collections/openalgo_postman.json) [Bruno Collectionsarrow-up-right](https://github.com/marketcalls/openalgo/blob/main/collections/openalgo_bruno.json) [PreviousRate Limitingchevron-left](https://docs.openalgo.in/api-documentation/v1/rate-limiting) [NextPlaygroundchevron-right](https://docs.openalgo.in/playground) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Devtunnels | Documentation **What Are Dev Tunnels?** Dev Tunnels is a feature built into [Visual Studio Code (VS Code)arrow-up-right](https://code.visualstudio.com/) . It enables developers to securely expose local web services to the public internet without wrestling with complex networking or cloud infrastructure. Although Dev Tunnels are perfect for ad-hoc testing and development, remember that they are not designed for production workloads. #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/devtunnels#key-benefits-of-dev-tunnels) Key Benefits of Dev Tunnels **Flexibility:** Ideal for testing webhooks, APIs, and various integrations—especially for services like TradingView. **Security:** Dev Tunnels establish encrypted, secure connections between your local environment and the public internet. **Simplicity:** Skip the hassle of configuring cloud servers or proxies. With just a few clicks, you have a publicly accessible URL. ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/devtunnels#prerequisites) Prerequisites Before diving into the setup, ensure you have the following: * **Visual Studio Code (VS Code):** Installed on your machine. * **OpenAlgo:** Running locally (for example, on port 5000). * **TradingView Account:** Set up for alert creation. * **GitHub or Microsoft Account:** For authenticating with Dev Tunnels. ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/devtunnels#step-by-step-setup-guide) Step-by-Step Setup Guide #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/devtunnels#id-1.-start-and-verify-openalgo) 1\. Start and Verify OpenAlgo Begin by launching your OpenAlgo application locally from your VS Code. Open your browser and navigate to the OpenAlgo dashboard (e.g., [http://127.0.0.1:5000/dashboardarrow-up-right](http://127.0.0.1:5000/dashboard) ) to verify that the service is up and running. #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/devtunnels#id-2.-create-a-dev-tunnel-in-vs-code) 2\. Create a Dev Tunnel in VS Code * **Open VS Code** where your OpenAlgo project is running. * Navigate to the **Ports** tab located at the bottom of the VS Code interface. * Click on **“Forward a Port”** to start the process. #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/devtunnels#id-3.-configure-the-forwarded-port) 3\. Configure the Forwarded Port * Enter the port number on which OpenAlgo is running (e.g., **5000**), then press **Enter**. * This action forwards the specified port to a public URL. #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/devtunnels#id-4.-set-port-visibility-to-public) 4\. Set Port Visibility to Public * In the **Ports** tab, right-click on the forwarded address. * Select **“Port Visibility”** and then **“Public.”** * VS Code will warn you that this action will expose your service to the internet—confirm to proceed. * If prompted, sign up or log in using your **GitHub or Microsoft account** to create an encrypted URL. * Once completed, verify your new public URL. #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/devtunnels#id-5.-obtain-your-custom-webhook-url) 5\. Obtain Your Custom Webhook URL * Refer to the **OpenAlgo documentation** and navigate to **“API Documentation” → “V1” → “Orders API” → “Placeorder”.** * Copy the custom domain information provided. For instance: `POST https://your-custom-domain/API/v1/placeorder` * Append your unique Dev Tunnel URL to this endpoint. _Example:_ `https://h03ml9j.5000.inc1.devtunnels.ms/api/v1/placeorder` #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/devtunnels#id-6.-create-an-alert-in-tradingview) 6\. Create an Alert in TradingView * Open your desired chart on **TradingView** and configure the conditions for your alert. * Click the **“Alert”** icon to create a new alert. * In the alert settings, navigate to the **“Notifications”** tab. * Enable the **“Webhook URL”** option and paste your custom OpenAlgo webhook URL from the previous step. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FXjcQCBIo8NXMhA4jcGZw%252Fimage.png%3Falt%3Dmedia%26token%3D96ebbb5c-7be9-4878-836a-3bd42d833ec0&width=768&dpr=3&quality=100&sign=59124693&sv=2) #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/devtunnels#id-7.-configure-the-tradingview-alert-message-json-payload) 7\. Configure the TradingView Alert Message (JSON Payload) The JSON payload sent by TradingView is pivotal—it instructs OpenAlgo on how to execute orders. * Return to the [**OpenAlgo documentation**arrow-up-right](https://docs.openalgo.in/api-documentation/v1/orders-api/placeorder) and copy the JSON payload structure. * Ensure your TradingView alert message matches the required format so that OpenAlgo can correctly interpret and act on the alert. #### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/devtunnels#id-8.-trigger-an-alert-and-verify) 8\. Trigger an Alert and Verify * Activate your TradingView alert settings and position the alert trigger line near the current trading range. * Once the alert is live, monitor OpenAlgo’s **Orderbook** and **live mode** to confirm that orders are being executed as expected. * When the order is successfully placed and completed, the alert will cease, marking a successful integration. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2Fi0.wp.com%2Fwww.marketcalls.in%2Fwp-content%2Fuploads%2F2025%2F02%2Fimage-8.png%3Fresize%3D854%252C637%26ssl%3D1&width=768&dpr=3&quality=100&sign=5592cfd&sv=2) * * * ### [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/devtunnels#conclusion) Conclusion By leveraging Dev Tunnels, you can effortlessly and securely connect TradingView alerts to your local OpenAlgo instance. This setup is ideal for testing new trading strategies, exploring API integrations, and streamlining your algorithmic trading workflow. Remember, while Dev Tunnels are fantastic for development and testing, a more robust solution (such as cloud servers) is recommended for production environments. Embrace this streamlined approach and elevate your algo trading game today! [PreviousDocker Developmentchevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/docker-development) [NextCloudflared with Custom Domainchevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/cloudflared-with-custom-domain) Last updated 4 months ago * [Prerequisites](https://docs.openalgo.in/installation-guidelines/getting-started/devtunnels#prerequisites) * [Step-by-Step Setup Guide](https://docs.openalgo.in/installation-guidelines/getting-started/devtunnels#step-by-step-setup-guide) * [Conclusion](https://docs.openalgo.in/installation-guidelines/getting-started/devtunnels#conclusion) sun-brightdesktopmoon sun-brightdesktopmoon --- # Order Constants | Documentation [hashtag](https://docs.openalgo.in/api-documentation/v1/order-constants#order-constants) Order Constants ------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.openalgo.in/api-documentation/v1/order-constants#exchange) Exchange * NSE: NSE Equity * NFO: NSE Futures & Options * CDS: NSE Currency * BSE: BSE Equity * BFO: BSE Futures & Options * BCD: BSE Currency * MCX: MCX Commodity * NCDEX: NCDEX Commodity * NSE\_INDEX : NSE Indices * BSE\_INDEX : NSE Indices ### [hashtag](https://docs.openalgo.in/api-documentation/v1/order-constants#product-type) Product Type * CNC: Cash & Carry for equity * NRML: Normal for futures and options * MIS: Intraday Square off ### [hashtag](https://docs.openalgo.in/api-documentation/v1/order-constants#price-type) Price Type * MARKET: Market Order * LIMIT: Limit Order * SL: Stop Loss Limit Order * SL-M: Stop Loss Market Order ### [hashtag](https://docs.openalgo.in/api-documentation/v1/order-constants#action) Action * BUY: Buy * SELL: Sell [PreviousWebsocketschevron-left](https://docs.openalgo.in/api-documentation/v1/websockets) [NextHTTP Status Codeschevron-right](https://docs.openalgo.in/api-documentation/v1/http-status-codes) Last updated 5 months ago * [Order Constants](https://docs.openalgo.in/api-documentation/v1/order-constants#order-constants) * [Exchange](https://docs.openalgo.in/api-documentation/v1/order-constants#exchange) * [Product Type](https://docs.openalgo.in/api-documentation/v1/order-constants#product-type) * [Price Type](https://docs.openalgo.in/api-documentation/v1/order-constants#price-type) * [Action](https://docs.openalgo.in/api-documentation/v1/order-constants#action) sun-brightdesktopmoon sun-brightdesktopmoon --- # Amazon Elastic Beanstalk | Documentation [hashtag](https://docs.openalgo.in/installation-guidelines/getting-started/amazon-elastic-beanstalk#hosting-openalgo-in-the-cloud-using-amazon-aws-elastic-beanstalk) Hosting OpenAlgo in the Cloud using Amazon AWS Elastic Beanstalk ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [OpenAlgoarrow-up-right](https://openalgo.in/) is an open-source algo trading platform, offering a wide range of features for both beginners and experienced traders. This tutorial guides you through the process of hosting OpenAlgo in the cloud using Amazon AWS Elastic Beanstalk. **Prerequisites:** * An Amazon AWS account * VS Code (or any code editor with Git installed) * A hosting account with DNS management and custom domain(Cloudflare is recommended) **Steps by Step Instruction to host OpenAlgo in Amazon Cloud with custom domain** **Clone the OpenAlgo Repository:** * Go to the [OpenAlgo GitHub repositoryarrow-up-right](https://github.com/marketcalls/openalgo) . * Copy the repository link. * Open your VS Code and navigate to your project folder. * Open a new terminal in VS Code and type **git clone** [**https://github.com/marketcalls/openalgo**arrow-up-right](https://github.com/marketcalls/openalgo) and press enter. * This will download the OpenAlgo application locally in your VS Code. **Configure the .env File** * Open the sample.env file in the OpenAlgo project. * Right-click and rename it to .env. * Update the REDIRECT\_URL to your custom domain. * For example, if your custom domain for angel trading account is opendash.app, update it to https://opendash.app/angel/callback. * If you’re not using HTTPS, use http://openalgo.app/angel/callback. * Make sure to update the HOST\_SERVER to your custom domain as well as shown in the video. * You might also want to update the BROKER\_API\_KEY and BROKER\_API\_SECRET according to your broker credentials. * Save the changes. **Create the Elastic Beanstalk Application** * Go to the [AWS Management Consolearrow-up-right](https://aws.amazon.com/) and sign in. * Select the desired region (e.g., Asia Pacific (Mumbai) ap-south-1). * Search for “Elastic Beanstalk”. * Click on “Create application”. * Provide an application name (e.g., openalgo) and an environment name (e.g., openalgo-env). * Ensure the domain name is available (e.g., openalgo.ap-south-1.elasticbeanstalk.com). * Provide a description for your environment (optional). * Select “Python” as the platform and choose the “Python 3.11” platform branch. * Select “4.1.0 (Recommended)” as the platform version. * For “Application code”, choose “Upload your code”. * Give a version label (e.g., 1.0.0.1). * Choose “Local file” for “Source code origin”. * Select the zipped OpenAlgo project file you created earlier. * Choose “Single instance (free tier eligible)” as the configuration preset (or choose “Custom configuration” for more options). * Click on “Next” to proceed. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FNdhF417PVzLfFLNrWWiA%252Fimage.png%3Falt%3Dmedia%26token%3Dfd4b2078-f193-41e3-a112-9042502be4a7&width=768&dpr=3&quality=100&sign=50e68e93&sv=2) **Configure Service Access:** * Select the existing service role you created earlier. * If you don’t have one, click on “Create and use new service role”. * Select your EC2 key pair (e.g., test). * If you don’t have an EC2 key pair, click on “Choose an EC2 key pair” and create a new one. * Select the existing EC2 instance profile (e.g., “aws-elasticbeanstalk-ec2-role-flaskenv”). * If you don’t have one, click on “View permission details” and create a new instance profile. * Click on “Next”. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FSGNr4vPZmStLqQuWBlO0%252Fimage.png%3Falt%3Dmedia%26token%3D7f28af87-bb71-4ccf-a970-d7ab33d2d7e2&width=768&dpr=3&quality=100&sign=bdb1470f&sv=2) **Configure VPC Settings** * Select the default VPC. You can create a new VPC, if needed. * This is the virtual network where your Elastic Beanstalk environment will be deployed. **Activate Public IP Address and Instance Subnet:** * Ensure the Public IP address is enabled for your instance. This allows your application to be accessible from the internet. * Choose an instance subnet from your VPC. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252Fare2GJssCn5u3SvrAf4h%252Fimage.png%3Falt%3Dmedia%26token%3D83b72e54-43a7-4d1c-90d4-5befbf9b4cfd&width=768&dpr=3&quality=100&sign=932babf7&sv=2) **Configure Security Group:** * By default, select the default security group. * This will allow your application to connect to the internet. * If you want to restrict access, you can create a new security group and add rules to control incoming and outgoing traffic. * Click on “Next”. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FDADJzwvj3HN3v7DgG6B0%252Fimage.png%3Falt%3Dmedia%26token%3D8cb33e20-153b-4661-81ef-33d3da132a27&width=768&dpr=3&quality=100&sign=97056f9f&sv=2) **Configure Instance Type, Load Balancer, and CloudWatch Logs:** * Choose an instance type (e.g., T3 micro, T3 Small). * If you are looking for a free tier option, use T3 micro. * Select “Single instance” if you don’t need a load balancer. * Choose “Enhanced” for health reporting (optional). * Choose the default settings for CloudWatch logs (optional). * Click on “Next”. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F8m6EcTdF2UvAvkRzxTv7%252Fimage.png%3Falt%3Dmedia%26token%3D52078497-716f-4c32-9056-c10cf7e9b688&width=768&dpr=3&quality=100&sign=fed470b&sv=2) **Review and Submit:** * Review all the configuration steps. * Make sure all the settings are correct. * Click on “Submit”. * This will initiate the automated provisioning of the servers in the backend. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F1797lx2wk4HGOb7CT6fv%252Fimage.png%3Falt%3Dmedia%26token%3Da294e169-faca-4274-bf87-c9fed3ec052d&width=768&dpr=3&quality=100&sign=9dbb687b&sv=2) After deploying your OpenAlgo application on Elastic Beanstalk, you need to configure your custom domain to point to the Elastic Beanstalk environment. This involves creating a CNAME record in your DNS settings. Here’s how to do it: **Access Your DNS Provider:** * Log in to your DNS provider (e.g., Cloudflare, GoDaddy, Namecheap, etc.) * Find your domain’s DNS management section. **Create a CNAME Record:** * Click on “Add record” or similar to create a new record. * **Name:** Enter the subdomain you want to use (e.g., trade). This will be the part of your custom domain that will point to your Elastic Beanstalk application (e.g., trade.openalgo.app). * **Type:** Select “CNAME”. * **Value:** Copy the Elastic Beanstalk domain generated by AWS. It will look something like this: openalgo.ap-south-1.elasticbeanstalk.com. **Save and Verify:** * Save the CNAME record you just created. * Wait for the DNS propagation to complete, which may take some time (usually 24-48 hours). * Test your custom domain by entering it into your web browser. You should be redirected to your OpenAlgo application on Elastic Beanstalk. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2Fi0.wp.com%2Fwww.marketcalls.in%2Fwp-content%2Fuploads%2F2024%2F06%2Fimage-17-1024x466.png%3Fresize%3D1024%252C466%26ssl%3D1&width=768&dpr=3&quality=100&sign=aa4f379c&sv=2) **Example:** * Let’s say your custom domain is openalgo.app. * You want to use the subdomain trade to access your OpenAlgo application. * In your DNS settings, create a CNAME record with the following: * **Name:** trade * **Type:** CNAME * **Value:** openalgo.ap-south-1.elasticbeanstalk.com (replace with your Elastic Beanstalk domain) Once the DNS propagation completes, you’ll be able to access your OpenAlgo application at trade.openalgo.app. **SSL Configuration in Cloudflare** If you are using Cloudflare for DNS Management ensure to enable the flexible mode to access the openalgo domain with https SSL certificate. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2Fi0.wp.com%2Fwww.marketcalls.in%2Fwp-content%2Fuploads%2F2024%2F06%2Fimage-18-1024x524.png%3Fresize%3D1024%252C524%26ssl%3D1&width=768&dpr=3&quality=100&sign=71b2d10f&sv=2) By following these steps, you can successfully deploy OpenAlgo in the cloud using Amazon AWS Elastic Beanstalk. You can then start configuring your trading strategies and begin your algorithmic trading journey. [PreviousAccessing OpenAlgochevron-left](https://docs.openalgo.in/installation-guidelines/getting-started/mac-os-installation/accessing-openalgo) [NextHouseOfFosschevron-right](https://docs.openalgo.in/installation-guidelines/getting-started/houseoffoss) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Utilities API | Documentation [Holidayschevron-right](https://docs.openalgo.in/api-documentation/v1/utilities-api/holidays) [Timingschevron-right](https://docs.openalgo.in/api-documentation/v1/utilities-api/timings) [Telegramchevron-right](https://docs.openalgo.in/api-documentation/v1/utilities-api/telegram) [PreviousInstrumentschevron-left](https://docs.openalgo.in/api-documentation/v1/data-api/instruments) [NextHolidayschevron-right](https://docs.openalgo.in/api-documentation/v1/utilities-api/holidays) sun-brightdesktopmoon sun-brightdesktopmoon --- # HTTP Status Codes | Documentation The status codes contain the following Status Code Meaning 200 Request was successful 400 Bad request. The request is invalid or certain other errors 401 Authorization error. User could not be authenticated 403 Permission error. User does not have the necessary permissions 429 Rate limit exceeded. Users have been blocked for exceeding the rate limit. 500 Internal server error. [PreviousOrder Constantschevron-left](https://docs.openalgo.in/api-documentation/v1/order-constants) [NextRate Limitingchevron-right](https://docs.openalgo.in/api-documentation/v1/rate-limiting) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Metatrader 5 | Documentation [Download & Install Librarychevron-right](https://docs.openalgo.in/trading-platform/metatrader-5/download-and-install-library) [OpenAlgo MQL5 Functionschevron-right](https://docs.openalgo.in/trading-platform/metatrader-5/openalgo-mql5-functions) [Include the Header Filechevron-right](https://docs.openalgo.in/trading-platform/metatrader-5/include-the-header-file) [Sample Expert Advisorchevron-right](https://docs.openalgo.in/trading-platform/metatrader-5/sample-expert-advisor) [PreviousJavachevron-left](https://docs.openalgo.in/trading-platform/java) [NextDownload & Install Librarychevron-right](https://docs.openalgo.in/trading-platform/metatrader-5/download-and-install-library) sun-brightdesktopmoon sun-brightdesktopmoon --- # Data API | Documentation [Quoteschevron-right](https://docs.openalgo.in/api-documentation/v1/data-api/quotes) [MultiQuoteschevron-right](https://docs.openalgo.in/api-documentation/v1/data-api/multiquotes) [Depthchevron-right](https://docs.openalgo.in/api-documentation/v1/data-api/depth) [Historychevron-right](https://docs.openalgo.in/api-documentation/v1/data-api/history) [Intervalschevron-right](https://docs.openalgo.in/api-documentation/v1/data-api/intervals) [Symbolchevron-right](https://docs.openalgo.in/api-documentation/v1/data-api/symbol) [Searchchevron-right](https://docs.openalgo.in/api-documentation/v1/data-api/search) [SyntheticFuturechevron-right](https://docs.openalgo.in/api-documentation/v1/data-api/syntheticfuture) [Expirychevron-right](https://docs.openalgo.in/api-documentation/v1/data-api/expiry) [OptionSymbolchevron-right](https://docs.openalgo.in/api-documentation/v1/data-api/optionsymbol) [Option Chainchevron-right](https://docs.openalgo.in/api-documentation/v1/data-api/option-chain) [OptionGreekschevron-right](https://docs.openalgo.in/api-documentation/v1/data-api/optiongreeks) [MultiOptionGreekschevron-right](https://docs.openalgo.in/api-documentation/v1/data-api/multioptiongreeks) [Tickerchevron-right](https://docs.openalgo.in/api-documentation/v1/data-api/ticker) [Instrumentschevron-right](https://docs.openalgo.in/api-documentation/v1/data-api/instruments) [PreviousOpenPositionchevron-left](https://docs.openalgo.in/api-documentation/v1/orders-api/openposition) [NextQuoteschevron-right](https://docs.openalgo.in/api-documentation/v1/data-api/quotes) sun-brightdesktopmoon sun-brightdesktopmoon --- # Ping | Documentation ### [hashtag](https://docs.openalgo.in/api-documentation/v1/accounts-api/ping#endpoint-url) Endpoint URL This API Function checks connectivity and validates the API key authentication with the OpenAlgo platform Copy Local Host : POST http://127.0.0.1:5000/api/v1/ping Ngrok Domain : POST https://.ngrok-free.app/api/v1/ping Custom Domain: POST https:///api/v1/ping ### [hashtag](https://docs.openalgo.in/api-documentation/v1/accounts-api/ping#sample-api-request) Sample API Request Copy { "apikey": "" } ### [hashtag](https://docs.openalgo.in/api-documentation/v1/accounts-api/ping#sample-api-response) Sample API Response Copy { "data": { "broker": "upstox", "message": "pong" }, "status": "success" } ### [hashtag](https://docs.openalgo.in/api-documentation/v1/accounts-api/ping#request-body) Request Body Parameters Description Mandatory/Optional Default Value apikey App API key Mandatory \- ### [hashtag](https://docs.openalgo.in/api-documentation/v1/accounts-api/ping#response-fields) Response Fields Field Type Description status string Status of the request (success/error) message string Response message ("pong" on successful connection) broker string Name of the connected broker ### [hashtag](https://docs.openalgo.in/api-documentation/v1/accounts-api/ping#error-response) Error Response Notes 1. Use this endpoint to verify API connectivity before making other API calls 2. Validates that the API key is correctly configured and active 3. Returns the broker name associated with the validated API key 4. Rate limited to 10 requests per second (configurable via API\_RATE\_LIMIT) 5. Useful for health checks and monitoring API availability [PreviousAccounts APIchevron-left](https://docs.openalgo.in/api-documentation/v1/accounts-api) [NextFundschevron-right](https://docs.openalgo.in/api-documentation/v1/accounts-api/funds) Last updated 8 months ago * [Endpoint URL](https://docs.openalgo.in/api-documentation/v1/accounts-api/ping#endpoint-url) * [Sample API Request](https://docs.openalgo.in/api-documentation/v1/accounts-api/ping#sample-api-request) * [Sample API Response](https://docs.openalgo.in/api-documentation/v1/accounts-api/ping#sample-api-response) * [Request Body](https://docs.openalgo.in/api-documentation/v1/accounts-api/ping#request-body) * [Response Fields](https://docs.openalgo.in/api-documentation/v1/accounts-api/ping#response-fields) * [Error Response](https://docs.openalgo.in/api-documentation/v1/accounts-api/ping#error-response) sun-brightdesktopmoon Copy { "status": "error", "message": "Invalid openalgo apikey" } sun-brightdesktopmoon --- # Analyzer Toggle | Documentation [hashtag](https://docs.openalgo.in/api-documentation/v1/accounts-api/analyzer-toggle#endpoint-url) Endpoint URL -------------------------------------------------------------------------------------------------------------------- This API Function fetches the stock holdings details from the broker Copy Local Host : POST http://127.0.0.1:5000/api/v1/analyzer/toggle Ngrok Domain : POST https://.ngrok-free.app/api/v1/analyzer/toggle Custom Domain: POST https:///api/v1/analyzer/toggle [hashtag](https://docs.openalgo.in/api-documentation/v1/accounts-api/analyzer-toggle#sample-api-request) Sample API Request -------------------------------------------------------------------------------------------------------------------------------- Copy { "apikey": "", "mode": true } [hashtag](https://docs.openalgo.in/api-documentation/v1/accounts-api/analyzer-toggle#sample-api-response) Sample API Response ---------------------------------------------------------------------------------------------------------------------------------- Copy { "data": { "analyze_mode": false, "message": "Analyzer mode switched to live", "mode": "live", "total_logs": 2 }, "status": "success" } ### [hashtag](https://docs.openalgo.in/api-documentation/v1/accounts-api/analyzer-toggle#request-body) Request Body Parameter Type Required Description apikey string Yes Your OpenAlgo API key mode boolean Yes Target mode (true = analyze, false = live) ### [hashtag](https://docs.openalgo.in/api-documentation/v1/accounts-api/analyzer-toggle#response-fields) Response Fields Field Type Description status string Status of the API call (success/error) data object Container for response data mode string Current mode in human-readable format ("analyze" or "live") analyze\_mode boolean Current analyzer mode flag (true = analyze, false = live) total\_logs integer Total number of analyzer logs stored message string Confirmation message about the mode change ### [hashtag](https://docs.openalgo.in/api-documentation/v1/accounts-api/analyzer-toggle#notes) Notes * **Live Mode (**`**mode: false**`**)**: All API calls execute actual broker operations and real trades * **Analyze Mode (**`**mode: true**`**)**: All API calls return simulated responses without executing real trades * The mode change is applied immediately and affects all subsequent API calls * Use this endpoint to switch between testing (analyze) and production (live) environments * The `total_logs` field shows the cumulative count of all analyzer mode operations * Rate limited to 10 requests per second per API key * **Important**: Always verify the current mode before executing trading operations to avoid unintended live trades [PreviousAnalyzer Statuschevron-left](https://docs.openalgo.in/api-documentation/v1/accounts-api/analyzer-status) [NextOrders APIchevron-right](https://docs.openalgo.in/api-documentation/v1/orders-api) Last updated 9 months ago * [Endpoint URL](https://docs.openalgo.in/api-documentation/v1/accounts-api/analyzer-toggle#endpoint-url) * [Sample API Request](https://docs.openalgo.in/api-documentation/v1/accounts-api/analyzer-toggle#sample-api-request) * [Sample API Response](https://docs.openalgo.in/api-documentation/v1/accounts-api/analyzer-toggle#sample-api-response) * [Request Body](https://docs.openalgo.in/api-documentation/v1/accounts-api/analyzer-toggle#request-body) * [Response Fields](https://docs.openalgo.in/api-documentation/v1/accounts-api/analyzer-toggle#response-fields) * [Notes](https://docs.openalgo.in/api-documentation/v1/accounts-api/analyzer-toggle#notes) sun-brightdesktopmoon sun-brightdesktopmoon --- # Symbol Format | Documentation #### [hashtag](https://docs.openalgo.in/symbol-format#openalgo-symbol-format-standardization) OpenAlgo Symbol Format Standardization OpenAlgo standardizes financial instrument identification via a common symbol format across all exchanges and brokers, enhancing compatibility and simplifying automated trading. This uniform symbology eliminates the need for traders to adapt to varied broker-specific formats, streamlining algorithm development and execution. The format integrates key identifiers such as the base symbol, expiration date, and option type, ensuring consistent and error-free communication within trading systems. With OpenAlgo, developers can efficiently extend platform capabilities while traders focus on strategy, not syntax. ### [hashtag](https://docs.openalgo.in/symbol-format#equity-symbol-format) Equity Symbol Format In the context of OpenAlgo, equity symbols are constructed based on the base symbol of the stock. **Examples:** 1. **NSE Equity for Infosys:** Given the base symbol `INFY`, the OpenAlgo symbol for Infosys on the National Stock Exchange (NSE) would be `INFY`. 2. **BSE Equity for Tata Motors:** With the base symbol `TATAMOTORS`, the symbol on the Bombay Stock Exchange (BSE) would be `TATAMOTORS`. 3. **NSE Equity for State Bank of India:** If the base symbol is `SBIN`, the OpenAlgo symbol on NSE would be `SBIN`. ### [hashtag](https://docs.openalgo.in/symbol-format#future-symbol-format) Future Symbol Format For futures, the OpenAlgo symbology specifies that the symbol should consist of the base symbol followed by the expiration date and "FUT" to denote that it is a futures contract. **Format:** `[Base Symbol][Expiration Date]FUT` Below are the extended examples for various futures contracts: **NSE Futures:** * **Example:** For Bank Nifty futures expiring in April 2024, the symbol would be `BANKNIFTY24APR24FUT`. **BSE Futures:** * **Example:** For SENSEX futures expiring in April 2024, the symbol would be `SENSEX24APR24FUT`. **Currency Futures:** * **Example:** For USDINR currency futures expiring in May 2024, the symbol would be `USDINR10MAY24FUT`. **MCX Futures:** * **Example:** For crude oil futures on MCX expiring in May 2024, the symbol would be `CRUDEOILM20MAY24FUT`. **IRC Futures:** * **Example:** For government bond futures, specifically the 7.26% 2033 bond expiring in April 2024, the symbol in OpenAlgo would be `726GS203325APR24FUT`. ### [hashtag](https://docs.openalgo.in/symbol-format#options-symbol-format) Options Symbol Format Options symbols in OpenAlgo are structured to include the base symbol, the expiration date, the strike price, and whether it's a Call or Put option. **Format:** `[Base Symbol][Expiration Date][Strike Price][Option Type]` **Examples:** **NSE Index Options:** * **Example:** For a Nifty call option with a strike price of 20,800, expiring on 28th March 2024, the symbol would be `NIFTY28MAR2420800CE`. **NSE Stock Options:** * **Example:** For a Vedanta Limited (VEDL) call option with a strike price of 292.50, expiring on 25th April 2024, the symbol would be `VEDL25APR24292.5CE`. **Currency Options:** * **Example:** For a US Dollar to Indian Rupee (USDINR) call option with a strike price of 82, expiring on 19th April 2024, the symbol would be `USDINR19APR2482CE`. **MCX Options:** * **Example:** For a Crude Oil call option with a strike price of 6,750, expiring on 17th April 2024, the symbol would be `CRUDEOIL17APR246750CE`. **IRC Options:** * **Example:** For an Goverent bond (726GS2032) put option with a strike price of 97, expiring on 25th April 2024, the symbol would be `726GS203225APR2497PE`. ### [hashtag](https://docs.openalgo.in/symbol-format#common-nse-index-symbols-exchange-code-nse_index) Common NSE Index Symbols (Exchange Code : NSE\_INDEX) NIFTY NIFTYNXT50 FINNIFTY BANKNIFTY MIDCPNIFTY INDIAVIX HANGSENGBEESNAV NIFTY100 NIFTY200 NIFTY500 NIFTYALPHA50 NIFTYAUTO NIFTYCOMMODITIES NIFTYCONSUMPTION NIFTYCPSE NIFTYDIVOPPS50 NIFTYENERGY NIFTYFMCG NIFTYGROWSECT15 NIFTYGS10YR NIFTYGS10YRCLN NIFTYGS1115YR NIFTYGS15YRPLUS NIFTYGS48YR NIFTYGS813YR NIFTYGSCOMPSITE NIFTYINFRA NIFTYIT NIFTYMEDIA NIFTYMETAL NIFTYMIDLIQ15 NIFTYMIDCAP100 NIFTYMIDCAP150 NIFTYMIDCAP50 NIFTYMIDSML400 NIFTYMNC NIFTYPHARMA NIFTYPSE NIFTYPSUBANK NIFTYPVTBANK NIFTYREALTY NIFTYSERVSECTOR NIFTYSMLCAP100 NIFTYSMLCAP250 NIFTYSMLCAP50 NIFTY100EQLWGT NIFTY100LIQ15 NIFTY100LOWVOL30 NIFTY100QUALTY30 NIFTY200QUALTY30 NIFTY50DIVPOINT NIFTY50EQLWGT NIFTY50PR1XINV NIFTY50PR2XLEV NIFTY50TR1XINV NIFTY50TR2XLEV NIFTY50VALUE20 ### [hashtag](https://docs.openalgo.in/symbol-format#common-bse-index-symbols-exchange-code-bse_index) Common BSE Index Symbols (Exchange Code : BSE\_INDEX) SENSEX BANKEX SENSEX50 BSE100 BSE150MIDCAPINDEX BSE200 BSE250LARGEMIDCAPINDEX BSE400MIDSMALLCAPINDEX BSE500 BSEAUTO BSECAPITALGOODS BSECARBONEX BSECONSUMERDURABLES BSECPSE BSEDOLLEX100 BSEDOLLEX200 BSEDOLLEX30 BSEENERGY BSEFASTMOVINGCONSUMERGOODS BSEFINANCIALSERVICES BSEGREENEX BSEHEALTHCARE BSEINDIAINFRASTRUCTUREINDEX BSEINDUSTRIALS BSEINFORMATIONTECHNOLOGY BSEIPO BSELARGECAP BSEMETAL BSEMIDCAP BSEMIDCAPSELECTINDEX BSEOIL&GAS BSEPOWER BSEPSU BSEREALTY BSESENSEXNEXT50 BSESMALLCAP BSESMALLCAPSELECTINDEX BSESMEIPO BSETECK BSETELECOM ### [hashtag](https://docs.openalgo.in/symbol-format#exchange-codes) Exchange Codes The supported exchange symbol formats in OpenAlgo allow for an identification system that denotes where the instrument is traded, along with specific details that vary by instrument type: * **NSE:** `NSE` for National Stock Exchange equities. * **BSE:** `BSE` for Bombay Stock Exchange equities. * **NFO:** `NFO` for NSE Futures and Options. * **BFO:** `BFO` for BSE Futures and Options. * **BCD:** `BCD` for BSE Currency Derivatives. * **CDS:** `CDS` for NSE Currency Derivatives. * **MCX:** `MCX` for commodities traded on the Multi Commodity Exchange. * **NSE\_INDEX:** `NSE_INDEX` for indices on the National Stock Exchange. * **BSE\_INDEX:** `BSE_INDEX` for indices on the Bombay Stock Exchange. ### [hashtag](https://docs.openalgo.in/symbol-format#database-schema-common-symbols) Database Schema (Common Symbols) For developers, understanding the database schema is essential for managing data effectively within OpenAlgo: 1. **id:** A unique identifier for each record in the database. 2. **symbol:** The standard trading symbol of the instrument as per OpenAlgo's symbology. 3. **brsymbol:** The broker-specific symbol for the instrument, if applicable. 4. **name:** The common name of the instrument (e.g., the company name for equities). 5. **exchange:** The standard exchange identifier code (e.g NSE, BSE, MCX CDS etc) where the instrument is traded as per OpenAlgo's symbology. 6. **brexchange:** The specific broker exchange identifier, if different from the standard exchange code. 7. **token:** A unique token or code assigned to the instrument, possibly for internal tracking or broker-specific identification. 8. **expiry:** The expiration date for derivatives contracts, formatted as per broker/exchange standards. 9. **strike:** The strike price for options contracts. 10. **lotsize:** The standardized lot size for the instrument, particularly relevant for derivatives trading. 11. **instrumenttype:** The type of instrument (e.g., equity, future, option). 12. **tick\_size:** The minimum price movement of the instrument on the exchange. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FvUWO49dLv5Pklo6qPtIV%252Fimage.png%3Falt%3Dmedia%26token%3D7cea9426-f5b9-4c29-b29f-a2e4b9ea7030&width=768&dpr=3&quality=100&sign=9413d7ce&sv=2) This schema captures both the standardized OpenAlgo symbology and the potentially divergent broker-specific information, enabling algorithms and traders to operate across multiple platforms without confusion. It allows for the storage of instrument metadata necessary for trading activities and ensures that all financial instruments are identifiable and their market details readily accessible. [PreviousPlaygroundchevron-left](https://docs.openalgo.in/playground) [NextSkillschevron-right](https://docs.openalgo.in/skills) Last updated 2 months ago * [Equity Symbol Format](https://docs.openalgo.in/symbol-format#equity-symbol-format) * [Future Symbol Format](https://docs.openalgo.in/symbol-format#future-symbol-format) * [Options Symbol Format](https://docs.openalgo.in/symbol-format#options-symbol-format) * [Common NSE Index Symbols (Exchange Code : NSE\_INDEX)](https://docs.openalgo.in/symbol-format#common-nse-index-symbols-exchange-code-nse_index) * [Common BSE Index Symbols (Exchange Code : BSE\_INDEX)](https://docs.openalgo.in/symbol-format#common-bse-index-symbols-exchange-code-bse_index) * [Exchange Codes](https://docs.openalgo.in/symbol-format#exchange-codes) * [Database Schema (Common Symbols)](https://docs.openalgo.in/symbol-format#database-schema-common-symbols) sun-brightdesktopmoon sun-brightdesktopmoon --- # Orders API | Documentation The Orders API provides a comprehensive list of operations to manage and handle orders efficiently. [PreviousAnalyzer Togglechevron-left](https://docs.openalgo.in/api-documentation/v1/accounts-api/analyzer-toggle) [NextPlaceorderchevron-right](https://docs.openalgo.in/api-documentation/v1/orders-api/placeorder) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Amibroker | Documentation AmiBroker is a popular software among traders for its advanced technical analysis and algorithmic trading capabilities. It suits algorithmic trading well due to several key features: 1. **Advanced Charting and Analysis Tools**: AmiBroker offers a wide range of charting options and technical indicators, allowing traders to conduct thorough market analysis and develop strategies based on historical and real-time data. 2. **AFL (AmiBroker Formula Language)**: One of the core strengths of AmiBroker is its powerful and efficient programming language, AFL. It enables traders to write custom trading rules, indicators, and algorithms. AFL is designed to be easy to learn and fast to execute, making it ideal for developing complex trading strategies without requiring extensive programming knowledge. 3. **Backtesting Capability**: AmiBroker provides robust backtesting tools that allow traders to test their trading strategies on historical data before applying them in live markets. This feature is crucial for algorithmic trading, as it helps identify and refine effective strategies while minimizing risk. 4. **Optimization**: Along with backtesting, AmiBroker offers optimization features that enable traders to fine-tune their strategies by testing various parameters. This process helps in identifying the most effective settings for maximum profitability or efficiency. 5. **Automation and Execution**: AmiBroker can be integrated with trading platforms for automated trading. It can send orders directly to the market based on the rules defined in the AFL scripts, enabling fully automated, hands-off trading. 6. **Scalability and Speed**: The software is designed for efficiency, able to handle large volumes of data and execute trading strategies with minimal delay. This is crucial for high-frequency trading strategies that rely on speed and efficiency. [PreviousTool Referenceschevron-left](https://docs.openalgo.in/mcp/tool-references) [NextAmibroker Pluginchevron-right](https://docs.openalgo.in/trading-platform/amibroker/amibroker-plugin) Last updated 2 years ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Download & Install Library | Documentation **Download the MQL5 Libray and Unzip it** file-archive 6KB [OpenAlgo.zip](https://17901342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FmBwEhITzgv0O0fEGIIRN%2Fuploads%2FGaAX10Y9VcAQayg10UA8%2FOpenAlgo.zip?alt=media&token=c43859e9-84d9-42e0-b743-f2c3f3c846dd) archive downloadDownload[arrow-up-right-from-squareOpen](https://17901342-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FmBwEhITzgv0O0fEGIIRN%2Fuploads%2FGaAX10Y9VcAQayg10UA8%2FOpenAlgo.zip?alt=media&token=c43859e9-84d9-42e0-b743-f2c3f3c846dd) **Open MQL5 -> File -> Open DataFolder as shown below** ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252F13F4dTUvFFdRURXjPU52%252Fimage.png%3Falt%3Dmedia%26token%3D58a9a5e5-0822-404e-a22e-1f5ee29318f0&width=768&dpr=3&quality=100&sign=672b804b&sv=2) **Navigate to \\MQL5\\Include folder and paste the Unzipped OpenAlgo Folder here as shown below** ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FjiBNoWZ5OG5loXNLChYy%252Fimage.png%3Falt%3Dmedia%26token%3D1a597866-ee55-4e54-9294-2a160ec68278&width=768&dpr=3&quality=100&sign=64adfdd7&sv=2) Now the Installation Process is completed if you open MetaEditor you should see the Folders with Library Files as shown below ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FdyMciTowRcEn5Bq4P5Lm%252Fimage.png%3Falt%3Dmedia%26token%3Ddaff985e-3b4f-49ea-8641-0fc4120c348b&width=768&dpr=3&quality=100&sign=84098285&sv=2) [PreviousMetatrader 5chevron-left](https://docs.openalgo.in/trading-platform/metatrader-5) [NextOpenAlgo MQL5 Functionschevron-right](https://docs.openalgo.in/trading-platform/metatrader-5/openalgo-mql5-functions) Last updated 2 years ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Playground | Documentation [hashtag](https://docs.openalgo.in/playground#api-playground-documentation) API Playground Documentation ------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.openalgo.in/playground#overview) Overview The API Playground is a web-based interface for testing OpenAlgo REST API endpoints. It provides an intuitive UI to explore, test, and debug all available API endpoints without needing external tools like Postman. ![](https://docs.openalgo.in/~gitbook/image?url=https%3A%2F%2F17901342-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FmBwEhITzgv0O0fEGIIRN%252Fuploads%252FC1ieJg18id967e2h9ct4%252Fimage.png%3Falt%3Dmedia%26token%3Da4f69398-5688-4ddc-b8f4-e39994e0316b&width=768&dpr=3&quality=100&sign=6338f510&sv=2) ### [hashtag](https://docs.openalgo.in/playground#features) Features * **Three-Panel Layout**: Sidebar, request editor, and response viewer side-by-side * **Comprehensive Endpoint Library**: Pre-configured with all OpenAlgo API endpoints loaded from Bruno collection * **Organized Categories**: Endpoints grouped by functionality (Account, Orders, Data, Utilities) * **Live Testing**: Send requests and view responses in real-time * **Auto-Populated API Key**: Your API key is automatically injected into request bodies * **Line Numbers**: Both request body and response display line numbers for easy reference * **Prettify JSON**: Format and beautify JSON request bodies with one click * **Response Metrics**: View status code, response time, and response size * **Copy Options**: Copy response or generate cURL command * **Search Functionality**: Quickly find endpoints by name ### [hashtag](https://docs.openalgo.in/playground#access) Access Navigate to: `http://your-host:port/playground` **Note**: You must be logged in to access the Playground. ### [hashtag](https://docs.openalgo.in/playground#usage) Usage #### [hashtag](https://docs.openalgo.in/playground#id-1.-api-key-automatic) 1\. API Key (Automatic) Your API key is automatically managed: * The API key is fetched when you open the Playground * It's automatically injected into all request bodies containing an `apikey` field * No manual copy/paste required #### [hashtag](https://docs.openalgo.in/playground#id-2.-select-an-endpoint) 2\. Select an Endpoint Browse the left sidebar to find the endpoint you want to test: * **Account**: Funds, orderbook, tradebook, positionbook, holdings * **Orders**: Place, modify, cancel orders, basket orders, split orders * **Data**: Quotes, depth, history, search, symbols, expiry dates * **Utilities**: Ping, instruments, margin calculator Click on any endpoint to load its configuration in the request panel. #### [hashtag](https://docs.openalgo.in/playground#id-3.-customize-the-request) 3\. Customize the Request The middle panel contains two tabs: **Body Tab** * Edit the JSON request body with line numbers * API key is automatically populated * Click **Prettify** to format JSON * Modify parameters as needed **Headers Tab** * Shows request headers * Content-Type: application/json (default) #### [hashtag](https://docs.openalgo.in/playground#id-4.-send-the-request) 4\. Send the Request 1. Review the URL and method in the URL bar 2. Click the **Send** button (or use the arrow icon) 3. View the response in the right panel #### [hashtag](https://docs.openalgo.in/playground#id-5.-analyze-the-response) 5\. Analyze the Response The right panel shows: * **Status Code**: Color-coded (green for 2xx, red for errors) * **Response Time**: Request duration in milliseconds * **Response Size**: Size of the response in bytes/KB * **Response Body**: Formatted JSON with line numbers * **Copy Response**: Copy the JSON response * **Copy cURL**: Generate and copy cURL command ### [hashtag](https://docs.openalgo.in/playground#endpoint-categories) Endpoint Categories #### [hashtag](https://docs.openalgo.in/playground#account-endpoints) Account Endpoints * **Analyzer Status**: Check if analyzer mode is enabled * **Analyzer Toggle**: Enable/disable analyzer mode * **Funds**: Get account balance and margin details * **Orderbook**: View all orders * **Tradebook**: View executed trades * **Positionbook**: View open positions * **Holdings**: View long-term holdings #### [hashtag](https://docs.openalgo.in/playground#order-endpoints) Order Endpoints * **Place Order**: Place a single order * **Place Smart Order**: Place order with position sizing * **Basket Order**: Place multiple orders at once * **Split Order**: Split large orders into smaller chunks * **Modify Order**: Modify existing order parameters * **Cancel Order**: Cancel a specific order * **Cancel All Orders**: Cancel all pending orders * **Close Position**: Close all positions for a strategy * **Order Status**: Get status of a specific order * **Open Position**: Check open position for a symbol #### [hashtag](https://docs.openalgo.in/playground#data-endpoints) Data Endpoints * **Quotes**: Get real-time quotes for a symbol * **Depth**: Get market depth (order book) * **History**: Get historical OHLCV data * **Intervals**: Get supported time intervals * **Symbol**: Get symbol details * **Search**: Search for symbols * **Expiry**: Get expiry dates for derivatives * **Option Symbol**: Get option chain symbols * **Option Greeks**: Calculate option Greeks * **Ticker**: Get ticker data (GET request) #### [hashtag](https://docs.openalgo.in/playground#utility-endpoints) Utility Endpoints * **Ping**: Test API connectivity * **Instruments**: Download instrument master files * **Margin Calculator**: Calculate margin requirements ### [hashtag](https://docs.openalgo.in/playground#tips) Tips 1. **Automatic API Key**: Your API key is automatically injected into requests - no manual entry needed 2. **Search Feature**: Use the search box to quickly find endpoints by name 3. **Prettify JSON**: Click the Prettify button to format messy JSON in the request body 4. **Line Numbers**: Use line numbers to reference specific parts of requests/responses 5. **Copy cURL**: Generate cURL commands to replicate requests in terminal 6. **Status Codes**: * 200-299: Success (green) * 400-499: Client errors (red) * 500-599: Server errors (red) ### [hashtag](https://docs.openalgo.in/playground#integration-with-collections) Integration with Collections The API Playground is built using the same endpoint definitions as: * Postman Collection (`collections/postman/openalgo.postman_collection.json`) * Bruno Collection (`collections/openalgo/*.bru`) This ensures consistency across all testing tools. ### [hashtag](https://docs.openalgo.in/playground#troubleshooting) Troubleshooting #### [hashtag](https://docs.openalgo.in/playground#authentication-required-error) "Authentication required" error * Make sure you're logged into OpenAlgo * Navigate to `/playground` while logged in #### [hashtag](https://docs.openalgo.in/playground#api-key-not-being-injected) API key not being injected * Navigate to `/apikey` to generate your API key * Refresh the Playground page after generating a key * Ensure the request body contains an `apikey` field #### [hashtag](https://docs.openalgo.in/playground#invalid-api-key-errors) Invalid API key errors * Navigate to `/apikey` to verify or regenerate your API key * Ensure your API key is active and not expired #### [hashtag](https://docs.openalgo.in/playground#network-errors) Network errors * Check if the OpenAlgo server is running * Verify the URL in the request field is correct * Check browser console for detailed error messages ### [hashtag](https://docs.openalgo.in/playground#security-notes) Security Notes * API keys are automatically fetched from your secure session * API keys are stored encrypted in the database * Never share your API key with others * The API Playground requires authentication (login) to access * API keys are displayed in read-only mode for security ### [hashtag](https://docs.openalgo.in/playground#future-enhancements) Future Enhancements Planned features: * Request history and saved responses * Favorite/starred endpoints * Environment variables support * WebSocket endpoint testing * Response diff comparison [PreviousAPI Collectionschevron-left](https://docs.openalgo.in/api-documentation/v1/api-collections) [NextSymbol Formatchevron-right](https://docs.openalgo.in/symbol-format) Last updated 5 months ago * [API Playground Documentation](https://docs.openalgo.in/playground#api-playground-documentation) * [Overview](https://docs.openalgo.in/playground#overview) * [Features](https://docs.openalgo.in/playground#features) * [Access](https://docs.openalgo.in/playground#access) * [Usage](https://docs.openalgo.in/playground#usage) * [Endpoint Categories](https://docs.openalgo.in/playground#endpoint-categories) * [Tips](https://docs.openalgo.in/playground#tips) * [Integration with Collections](https://docs.openalgo.in/playground#integration-with-collections) * [Troubleshooting](https://docs.openalgo.in/playground#troubleshooting) * [Security Notes](https://docs.openalgo.in/playground#security-notes) * [Future Enhancements](https://docs.openalgo.in/playground#future-enhancements) sun-brightdesktopmoon sun-brightdesktopmoon --- # Ban IP | Documentation ### [hashtag](https://docs.openalgo.in/security/ban-ip#overview) Overview OpenAlgo includes a comprehensive security module designed to protect your trading platform from malicious traffic, bots, and unauthorized access attempts. This is especially crucial when hosting OpenAlgo on public-facing IPs or custom domains. ### [hashtag](https://docs.openalgo.in/security/ban-ip#why-security-matters-for-algo-traders) Why Security Matters for Algo Traders When you host OpenAlgo on a public IP or custom domain, your trading platform becomes accessible to the internet. This exposure can attract: * **Web Scrapers** attempting to harvest your trading data * **Bots** probing for vulnerabilities * **Brute Force Attacks** trying to guess API keys * **Automated Scanners** looking for exposed endpoints * **DDoS Attempts** that could disrupt your trading operations A single security breach could lead to: * Exposed trading strategies * Compromised API credentials * Disrupted trading operations during critical market hours * Unauthorized access to your portfolio data ### [hashtag](https://docs.openalgo.in/security/ban-ip#core-security-features) Core Security Features #### [hashtag](https://docs.openalgo.in/security/ban-ip#id-1.-ip-ban-system) 1\. IP Ban System The IP ban system automatically protects your platform by blocking malicious IPs based on suspicious behavior patterns. **How It Works** * **Automatic Detection**: Monitors all incoming traffic for suspicious patterns * **Threshold-Based Banning**: Automatically bans IPs that exceed predefined thresholds * **Temporary & Permanent Bans**: First-time offenders get temporary bans, repeat offenders get permanently banned * **Localhost Protection**: Your local IP (127.0.0.1) is protected from accidental banning **Ban Types** * **24 Hours**: Default for first offense * **48 Hours**: For API key abuse * **1 Week**: Manual option for serious violations * **Permanent**: After 3 offenses or manual selection #### [hashtag](https://docs.openalgo.in/security/ban-ip#id-2.-404-error-tracking) 2\. 404 Error Tracking Monitors and tracks 404 (Not Found) errors to detect bots and scanners probing for vulnerabilities. **Features** * **Real-time Tracking**: Every 404 error is logged with IP and attempted path * **Auto-Ban Threshold**: 20 404 errors in 24 hours triggers automatic ban * **Path Analysis**: View which paths attackers are attempting to access * **24-Hour Window**: Counter resets daily for legitimate users **Common Attack Patterns Detected** * WordPress vulnerability scans (wp-admin, wp-login.php) * PHPMyAdmin probes * Configuration file searches (.env, .git, config.php) * Admin panel discovery attempts #### [hashtag](https://docs.openalgo.in/security/ban-ip#id-3.-invalid-api-key-monitoring) 3\. Invalid API Key Monitoring Protects against brute force attacks on your API endpoints. **Features** * **Attempt Tracking**: Logs every invalid API key attempt * **Auto-Ban Threshold**: 10 invalid attempts in 24 hours triggers 48-hour ban * **Hashed Storage**: API keys are hashed before tracking for privacy * **Integration**: Works seamlessly with all OpenAlgo API endpoints **Protection Against** * API key brute force attacks * Credential stuffing attempts * Automated API abuse * Unauthorized trading bot access ### [hashtag](https://docs.openalgo.in/security/ban-ip#security-dashboard) Security Dashboard Access the security dashboard at `/security` (available in the profile dropdown menu). #### [hashtag](https://docs.openalgo.in/security/ban-ip#dashboard-components) Dashboard Components **1\. Statistics Overview** * **Total Bans**: Current number of banned IPs * **Permanent Bans**: IPs permanently blocked * **Suspicious IPs**: IPs showing suspicious behavior * **Near Threshold**: IPs close to auto-ban threshold **2\. Manual Ban Controls** * **IP Ban**: Manually ban specific IP addresses * **Host/Domain Ban**: Ban all IPs from a specific host * **Custom Reasons**: Document why an IP was banned * **Duration Options**: Choose ban duration or make permanent **3\. Banned IPs Table** Displays all currently banned IPs with: * IP address * Ban reason * Ban timestamp * Expiry time (or permanent status) * Ban count (repeat offenses) * Created by (system/manual) * Unban action button **4\. Invalid API Key Attempts** Shows IPs attempting invalid API authentication: * IP address * Number of attempts (X/10 threshold) * First and last attempt timestamps * Hashed API keys tried * Quick ban action **5\. 404 Error Tracking** Monitors IPs generating 404 errors: * IP address * Error count (X/20 threshold) * First and last error timestamps * Paths attempted * Ban and clear actions ### [hashtag](https://docs.openalgo.in/security/ban-ip#configuration) Configuration The security module works out-of-the-box with these default thresholds: These thresholds are optimized to: * Allow legitimate users some margin for error * Quickly identify and block malicious actors * Prevent false positives for normal trading operations ### [hashtag](https://docs.openalgo.in/security/ban-ip#usage-guide) Usage Guide #### [hashtag](https://docs.openalgo.in/security/ban-ip#accessing-the-security-dashboard) Accessing the Security Dashboard 1. Log in to OpenAlgo 2. Click on your profile dropdown 3. Select "Security" #### [hashtag](https://docs.openalgo.in/security/ban-ip#manual-ip-banning) Manual IP Banning 1. Enter the IP address in the "Manual IP Ban" section 2. Provide a reason for the ban 3. Select duration (24 hours, 48 hours, 1 week, or permanent) 4. Click "Ban IP" #### [hashtag](https://docs.openalgo.in/security/ban-ip#banning-by-host-domain) Banning by Host/Domain 1. Enter the host or domain name 2. Check "Permanent Ban" if needed 3. Click "Ban Host" 4. All IPs from that host will be banned #### [hashtag](https://docs.openalgo.in/security/ban-ip#unbanning-an-ip) Unbanning an IP 1. Find the IP in the "Banned IPs" table 2. Click the "Unban" button 3. Confirm in the modal dialog #### [hashtag](https://docs.openalgo.in/security/ban-ip#clearing-404-tracker) Clearing 404 Tracker To give an IP a fresh start: 1. Find the IP in the "404 Tracker" table 2. Click "Clear" 3. Confirm the action ### [hashtag](https://docs.openalgo.in/security/ban-ip#best-practices) Best Practices #### [hashtag](https://docs.openalgo.in/security/ban-ip#for-public-hosting) For Public Hosting 1. **Regular Monitoring**: Check the security dashboard weekly 2. **Review Patterns**: Look for attack patterns in attempted paths 3. **Permanent Bans**: Use for confirmed malicious sources 4. **Documentation**: Use clear ban reasons for future reference #### [hashtag](https://docs.openalgo.in/security/ban-ip#for-development) For Development 1. **Localhost Safety**: Your local IP is protected from banning 2. **Testing**: Use external IPs or tools like ngrok for testing 3. **Clear Trackers**: Reset tracking data after testing #### [hashtag](https://docs.openalgo.in/security/ban-ip#for-production) For Production 1. **Enable HTTPS**: Use SSL certificates for encrypted connections 2. **Strong API Keys**: Use complex, randomly generated API keys 3. **Regular Updates**: Keep OpenAlgo updated for latest security patches 4. **Backup Strategy**: Regular backups before applying bans ### [hashtag](https://docs.openalgo.in/security/ban-ip#security-response-workflow) Security Response Workflow When suspicious activity is detected: 1. **Automatic Response** * System tracks the activity * Thresholds are monitored * Auto-ban triggers if exceeded 2. **Manual Review** * Check security dashboard * Review attack patterns * Apply manual bans if needed 3. **Post-Incident** * Document the incident * Review if thresholds need adjustment * Consider permanent bans for serious attacks ### [hashtag](https://docs.openalgo.in/security/ban-ip#database-information) Database Information All security data is stored in the `logs.db` database: * **Table**: `ip_bans` - Stores banned IP information * **Table**: `error_404_tracker` - Tracks 404 errors * **Table**: `invalid_api_key_tracker` - Monitors API key attempts * **Table**: `traffic_logs` - General traffic logging No additional configuration or migration is required. The tables are created automatically on first run. ### [hashtag](https://docs.openalgo.in/security/ban-ip#troubleshooting) Troubleshooting #### [hashtag](https://docs.openalgo.in/security/ban-ip#ip-not-getting-banned) IP Not Getting Banned * Check if it's localhost (protected from banning) * Verify thresholds haven't been modified * Ensure security middleware is active #### [hashtag](https://docs.openalgo.in/security/ban-ip#cant-access-after-ban) Can't Access After Ban * Access from different IP * Use database tools to remove ban * Contact system administrator #### [hashtag](https://docs.openalgo.in/security/ban-ip#false-positives) False Positives * Adjust thresholds if needed * Use manual unban for legitimate users * Consider whitelisting (future feature) ### [hashtag](https://docs.openalgo.in/security/ban-ip#future-enhancements) Future Enhancements Planned security improvements: 1. **IP Whitelist System**: Allow trusted IPs to bypass security checks 2. **Geographic Blocking**: Ban entire countries or regions 3. **Rate Limiting**: Per-endpoint request limits 4. **Two-Factor Authentication**: Additional login security 5. **Webhook Alerts**: Notify on security events via Discord/Telegram ### [hashtag](https://docs.openalgo.in/security/ban-ip#support) Support For security-related issues or questions: 1. Check the security dashboard first 2. Review logs in `/logs` endpoint 3. Join our Discord community 4. Report security vulnerabilities privately Remember: Security is not a feature, it's a necessity when your money and trading strategies are at stake. [PreviousArchitecturechevron-left](https://docs.openalgo.in/security/architecture) [NextPracticeschevron-right](https://docs.openalgo.in/security/practices) Last updated 6 months ago * [Overview](https://docs.openalgo.in/security/ban-ip#overview) * [Why Security Matters for Algo Traders](https://docs.openalgo.in/security/ban-ip#why-security-matters-for-algo-traders) * [Core Security Features](https://docs.openalgo.in/security/ban-ip#core-security-features) * [Security Dashboard](https://docs.openalgo.in/security/ban-ip#security-dashboard) * [Configuration](https://docs.openalgo.in/security/ban-ip#configuration) * [Usage Guide](https://docs.openalgo.in/security/ban-ip#usage-guide) * [Best Practices](https://docs.openalgo.in/security/ban-ip#best-practices) * [Security Response Workflow](https://docs.openalgo.in/security/ban-ip#security-response-workflow) * [Database Information](https://docs.openalgo.in/security/ban-ip#database-information) * [Troubleshooting](https://docs.openalgo.in/security/ban-ip#troubleshooting) * [Future Enhancements](https://docs.openalgo.in/security/ban-ip#future-enhancements) * [Support](https://docs.openalgo.in/security/ban-ip#support) sun-brightdesktopmoon Copy # 404 Error Threshold MAX_404_ERRORS_PER_DAY = 20 # Auto-ban after 20 404s # Invalid API Key Threshold MAX_INVALID_API_ATTEMPTS = 10 # Auto-ban after 10 attempts # Repeat Offender Threshold PERMANENT_BAN_AFTER = 3 # Permanent ban after 3 offenses sun-brightdesktopmoon --- # Architecture | Documentation ### [hashtag](https://docs.openalgo.in/security/architecture#openalgo-security-architecture) OpenAlgo Security Architecture OpenAlgo implements multiple layers of security to protect your trading operations, data, and infrastructure. * * * 1. **Authentication & Session Management** * Encrypted Password Storage: User passwords are hashed using Argon2 (industry-standard, resistant to GPU attacks) * Session Expiry: Automatic daily session expiration at configurable time (default 3:30 AM IST) * Secure Session Cookies: HTTPOnly, SameSite, and Secure flags enabled for HTTPS deployments * Token Revocation: Automatic token revocation on session expiry or logout * * * 1. **API Security** * API Key Authentication: Unique API keys for each user with Argon2 hashing + pepper * Encrypted Token Storage: All broker tokens encrypted using Fernet symmetric encryption * API Rate Limiting: Configurable rate limits on all API endpoints (default 10-60 requests/minute) * Invalid API Key Tracking: Auto-bans IPs after 10 invalid API key attempts * * * 1. **Network Security** * IP Ban System: Automatic and manual IP blocking for malicious traffic * 404 Attack Detection: Auto-bans after 20 suspicious 404 errors per day * CSRF Protection: Built-in CSRF tokens on all forms and state-changing operations * CORS Configuration: Restrictive cross-origin policies with configurable allowed origins * Content Security Policy (CSP): Prevents XSS attacks through strict CSP headers * * * 1. **Data Protection** * Database Encryption: Sensitive data (API keys, broker tokens, SMTP passwords) encrypted at rest * No Credential Logging: API keys and passwords never logged in plaintext * Secure Configuration: Environment variables for sensitive configuration * Pepper-based Hashing: Additional pepper secret for password and API key hashing * * * 1. **Infrastructure Security** * Security Middleware: Request validation and IP checking before processing * Traffic Logging: Complete audit trail of all requests with anonymized sensitive data * Performance Monitoring: Latency tracking to detect DoS attempts * Error Handling: Generic error messages to prevent information leakage * File Upload Restrictions: Limited file types and size restrictions * * * 1. **Broker Integration Security** * OAuth 2.0 Support: Secure authorization flow for broker connections * Token Refresh: Automatic token refresh without storing credentials * Broker-specific Encryption: Each broker's tokens encrypted separately * Revocation Support: Ability to immediately revoke broker access * * * 1. **WebSocket Security** * Authentication Required: WebSocket connections require valid session * Message Validation: All WebSocket messages validated before processing * Connection Limits: Maximum concurrent connections per user * Heartbeat Monitoring: Automatic disconnection of idle connections * * * 1. **Operational Security** * Security Dashboard: Real-time monitoring at /security * Audit Logs: Comprehensive logging of all security events * Configurable Thresholds: Adjust security settings without code changes * Multiple Ban Durations: Temporary (24hr, 48hr, 1 week) or permanent bans * Repeat Offender Detection: Escalating penalties for repeat violations * * * 1. **Development Security** * No Hardcoded Secrets: All sensitive data in environment variables or database * Input Validation: All user inputs sanitized and validated * SQL Injection Prevention: Using SQLAlchemy ORM with parameterized queries * XSS Prevention: Template auto-escaping and CSP headers * Dependency Management: Regular updates and security patches * * * 1. **Deployment Security** * HTTPS Support: Automatic secure cookie configuration for HTTPS * Docker Security: Non-root user in container, minimal base images * * * **Security Best Practices for Users** 1. Use Strong API Keys: Generate complex, random API keys 2. Enable HTTPS: Always use SSL certificates in production 3. Regular Updates: Keep OpenAlgo updated for latest security patches 4. Monitor Security Dashboard: Regular checks at /security 5. Backup Before Bans: Export data before applying permanent bans 6. Whitelist Trusted IPs: (Coming soon) Add trusted IPs to whitelist 7. Review Logs: Regularly check /logs for suspicious activity 8. Secure Environment: Protect your .env file and database [Previous52 - Broker Factory Implementationchevron-left](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation) [NextBan IPchevron-right](https://docs.openalgo.in/security/ban-ip) Last updated 4 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Practices | Documentation [hashtag](https://docs.openalgo.in/security/practices#openalgo-security-practices-report) OpenAlgo Security Practices Report --------------------------------------------------------------------------------------------------------------------------------- **Version:** 1.0 **Date:** December 2025 **Overall Security Rating:** 7.5 / 10 * * * ### [hashtag](https://docs.openalgo.in/security/practices#executive-summary) Executive Summary OpenAlgo implements **enterprise-grade security** with a defense-in-depth approach across all layers of the application. This document details all strong security practices currently implemented in the codebase. #### [hashtag](https://docs.openalgo.in/security/practices#key-security-highlights) Key Security Highlights Category Implementation Password Hashing Argon2 with pepper Token Encryption Fernet (AES-128-CBC) Session Protection HTTPOnly, SameSite, Secure cookies API Security Dual-storage (hashed + encrypted) Input Validation Marshmallow schema validation SQL Prevention SQLAlchemy ORM (parameterized queries) XSS Prevention Content Security Policy headers Rate Limiting Flask-Limiter with configurable limits Threat Detection IP banning, 404 tracking, invalid key tracking * * * ### [hashtag](https://docs.openalgo.in/security/practices#id-1.-password-and-credential-security) 1\. Password & Credential Security #### [hashtag](https://docs.openalgo.in/security/practices#argon2-password-hashing) Argon2 Password Hashing OpenAlgo uses Argon2, the winner of the Password Hashing Competition, for all password storage. Practice Implementation Location Argon2 Hashing Memory-hard hashing algorithm `database/user_db.py:74-77` Mandatory Pepper 32+ character pepper required at startup `database/auth_db.py:27-41` Auto-Rehashing Passwords rehashed on verification if needed `database/user_db.py:84-87` #### [hashtag](https://docs.openalgo.in/security/practices#password-strength-requirements) Password Strength Requirements All passwords must meet the following criteria: **Location:** `utils/auth_utils.py:13-48` #### [hashtag](https://docs.openalgo.in/security/practices#credential-masking) Credential Masking Sensitive credentials are masked in UI displays showing only the first 4 characters. **Location:** `utils/auth_utils.py:50-64` * * * ### [hashtag](https://docs.openalgo.in/security/practices#id-2.-api-key-security) 2\. API Key Security #### [hashtag](https://docs.openalgo.in/security/practices#dual-storage-approach) Dual-Storage Approach API keys are stored using a dual approach for maximum security: Storage Method Purpose Location Argon2 Hash Verification without exposing key `database/auth_db.py:334-336` Fernet Encrypted Secure retrieval when needed `database/auth_db.py:339` #### [hashtag](https://docs.openalgo.in/security/practices#intelligent-caching) Intelligent Caching Key Type Cache TTL Rationale Valid Keys 10 hours Reduce database load Invalid Keys 5 minutes Prevent cache poisoning **Location:** `database/auth_db.py:105-106` #### [hashtag](https://docs.openalgo.in/security/practices#security-features) Security Features * **Cache Invalidation:** Automatic invalidation on key regeneration (`database/auth_db.py:354-355`) * **Invalid Key Tracking:** Per-IP tracking of failed attempts (`database/traffic_db.py:349-456`) * **SHA256 Cache Keys:** API keys never stored as cache keys in plaintext (`database/auth_db.py:397`) * * * ### [hashtag](https://docs.openalgo.in/security/practices#id-3.-encryption) 3\. Encryption #### [hashtag](https://docs.openalgo.in/security/practices#fernet-token-encryption) Fernet Token Encryption All sensitive tokens are encrypted using Fernet (symmetric authenticated encryption). Component Implementation Location Algorithm Fernet (AES-128-CBC + HMAC) `database/auth_db.py:43-56` Key Derivation PBKDF2-HMAC-SHA256 `database/auth_db.py:46-50` Iterations 100,000 `database/auth_db.py:50` #### [hashtag](https://docs.openalgo.in/security/practices#encrypted-data) Encrypted Data * Broker authentication tokens * API keys (encrypted copy for retrieval) * SMTP passwords (if email reset enabled) * * * ### [hashtag](https://docs.openalgo.in/security/practices#id-4.-session-security) 4\. Session Security #### [hashtag](https://docs.openalgo.in/security/practices#cookie-configuration) Cookie Configuration Setting Value Location HTTPOnly `True` `app.py:142` SameSite `Lax` `app.py:143` Secure HTTPS-conditional `app.py:144` Name Prefix `__Secure-` (HTTPS) `app.py:150-151` #### [hashtag](https://docs.openalgo.in/security/practices#session-expiry) Session Expiry * **Daily Expiry:** Configurable auto-expiry time (default 3:00 AM IST) * **Validation Decorator:** `check_session_validity()` validates each request * **Token Revocation:** Automatic on session expiry **Location:** `utils/session.py:68-118` * * * ### [hashtag](https://docs.openalgo.in/security/practices#id-5.-csrf-protection) 5\. CSRF Protection #### [hashtag](https://docs.openalgo.in/security/practices#flask-wtf-integration) Flask-WTF Integration Setting Value Location CSRF Enabled `True` `app.py:154-155` Cookie HTTPOnly `True` `app.py:160` Cookie SameSite `Lax` `app.py:161` Cookie Secure HTTPS-conditional `app.py:162` #### [hashtag](https://docs.openalgo.in/security/practices#api-exemption) API Exemption REST API endpoints (`/api/v1/*`) are exempt from CSRF as they use API key authentication instead. **Location:** `app.py:184` * * * ### [hashtag](https://docs.openalgo.in/security/practices#id-6.-rate-limiting) 6\. Rate Limiting #### [hashtag](https://docs.openalgo.in/security/practices#configured-limits) Configured Limits Endpoint Limit Location Login 5/minute, 25/hour `blueprints/auth.py:30-31` Password Reset 15/hour `blueprints/auth.py:84` API Requests 50/second `.sample.env:82` Order Placement 10/second `.sample.env:84` Smart Orders 2/second `.sample.env:86` Webhooks 100/minute `.sample.env:88` WebSocket 100/minute `.sample.env:90` #### [hashtag](https://docs.openalgo.in/security/practices#implementation) Implementation * **Library:** Flask-Limiter with moving-window strategy * **Storage:** Memory-based (configurable) * **Per-IP:** Rate limits applied per client IP **Location:** `limiter.py` * * * ### [hashtag](https://docs.openalgo.in/security/practices#id-7.-input-validation) 7\. Input Validation #### [hashtag](https://docs.openalgo.in/security/practices#marshmallow-schema-validation) Marshmallow Schema Validation All API endpoints use Marshmallow schemas for strict input validation. Schema Validations Location OrderSchema Action (BUY/SELL), quantity (min 1), price (min 0), product, pricetype `restx_api/schemas.py:3-15` ModifyOrderSchema Order fields with validation `restx_api/schemas.py:31-43` CancelOrderSchema orderid required `restx_api/schemas.py:45-48` BasketOrderSchema Nested order validation `restx_api/schemas.py:69-72` SplitOrderSchema Splitsize (positive int) `restx_api/schemas.py:74-86` OptionsOrderSchema Strike, expiry, offset validation `restx_api/schemas.py:88-104` OptionsMultiOrderSchema Array length 1-20 `restx_api/schemas.py:120-132` MarginCalculatorSchema Array length 1-50 `restx_api/schemas.py:152-159` #### [hashtag](https://docs.openalgo.in/security/practices#validation-features) Validation Features * * * ### [hashtag](https://docs.openalgo.in/security/practices#id-8.-sql-injection-prevention) 8\. SQL Injection Prevention #### [hashtag](https://docs.openalgo.in/security/practices#sqlalchemy-orm) SQLAlchemy ORM All database queries use SQLAlchemy ORM with parameterized queries. Practice Implementation ORM Usage 100% of queries via SQLAlchemy Parameterized Queries `filter_by()` for all lookups No String Concatenation Zero raw SQL string building #### [hashtag](https://docs.openalgo.in/security/practices#example-safe-query) Example Safe Query **Locations:** `database/auth_db.py`, `database/user_db.py`, `database/traffic_db.py` * * * ### [hashtag](https://docs.openalgo.in/security/practices#id-9.-xss-prevention-content-security-policy) 9\. XSS Prevention (Content Security Policy) #### [hashtag](https://docs.openalgo.in/security/practices#csp-directives) CSP Directives Directive Value Purpose default-src 'self' Restrict all to same-origin script-src 'self' 'unsafe-inline' cdn.socket.io Scripts from self + Socket.IO style-src 'self' 'unsafe-inline' Styles from self img-src 'self' data: Images from self + data URIs connect-src 'self' wss: ws: WebSocket connections font-src 'self' Fonts from same-origin object-src 'none' No plugins allowed frame-ancestors 'self' Clickjacking protection form-action 'self' Form submission restriction base-uri 'self' Base tag restriction **Location:** `csp.py:139-186` #### [hashtag](https://docs.openalgo.in/security/practices#configuration) Configuration * * * ### [hashtag](https://docs.openalgo.in/security/practices#id-10.-ip-security-and-banning) 10\. IP Security & Banning #### [hashtag](https://docs.openalgo.in/security/practices#ip-ban-system) IP Ban System Feature Implementation Location Temporary Bans Configurable duration (default 24h) `database/traffic_db.py:185` Permanent Bans After repeat offenses `database/traffic_db.py:178-182` Repeat Tracking Ban count incremented per violation `database/traffic_db.py:173-181` Localhost Protection Never ban 127.0.0.1, ::1 `database/traffic_db.py:162-164` #### [hashtag](https://docs.openalgo.in/security/practices#threat-detection) Threat Detection Feature Description Location 404 Tracking Detect bot scanning `database/traffic_db.py:242-347` Invalid API Key Tracking Track brute-force attempts `database/traffic_db.py:349-456` Auto-Escalation Temp ban → Permanent after 3 offenses `database/traffic_db.py:179-182` #### [hashtag](https://docs.openalgo.in/security/practices#proxy-ip-detection) Proxy IP Detection Supports multiple proxy headers in priority order: 1. CF-Connecting-IP (Cloudflare) 2. True-Client-IP (Cloudflare Enterprise) 3. X-Real-IP 4. X-Forwarded-For 5. X-Client-IP 6. request.remote\_addr (fallback) **Location:** `utils/ip_helper.py:1-108` * * * ### [hashtag](https://docs.openalgo.in/security/practices#id-11.-logging-and-audit-trails) 11\. Logging & Audit Trails #### [hashtag](https://docs.openalgo.in/security/practices#traffic-logging) Traffic Logging All HTTP requests are logged (except static files). Field Description IP Address Client IP (proxy-aware) Method HTTP method Path Request path Status Code Response status Duration Request duration (ms) User ID Authenticated user (if available) Error Error message (if any) **Location:** `utils/traffic_logger.py:35-44` #### [hashtag](https://docs.openalgo.in/security/practices#sensitive-data-redaction) Sensitive Data Redaction The following patterns are automatically redacted from logs: **Location:** `utils/logging.py:28-80` #### [hashtag](https://docs.openalgo.in/security/practices#log-retention) Log Retention * **Rotating Files:** Configurable rotation * **Default Retention:** 14 days * **Separate Log Database:** `LOGS_DATABASE_URL` for traffic logs * * * ### [hashtag](https://docs.openalgo.in/security/practices#id-12.-docker-security) 12\. Docker Security #### [hashtag](https://docs.openalgo.in/security/practices#dockerfile-hardening) Dockerfile Hardening Practice Implementation Location Multi-Stage Build Separate builder/production stages `Dockerfile:2-17` Slim Base Image `python:3.12-slim-bullseye` `Dockerfile:17` Non-Root User Runs as `appuser` `Dockerfile:24,46` Cache Cleanup `rm -rf /root/.cache` `Dockerfile:14` #### [hashtag](https://docs.openalgo.in/security/practices#directory-permissions) Directory Permissions Directory Permission Purpose /app/strategies 755 Strategy scripts /app/keys 700 Private keys (owner only) /app/log 755 Application logs #### [hashtag](https://docs.openalgo.in/security/practices#docker-compose-security) Docker Compose Security Practice Implementation Location Named Volumes Persistent data isolation `docker-compose.yaml:31-40` Read-Only .env Config mounted as `:ro` `docker-compose.yaml:20` Restart Policy `unless-stopped` `docker-compose.yaml:27` * * * ### [hashtag](https://docs.openalgo.in/security/practices#id-13.-cors-configuration) 13\. CORS Configuration #### [hashtag](https://docs.openalgo.in/security/practices#default-configuration) Default Configuration Setting Default Location CORS\_ENABLED FALSE `.sample.env:104` CORS\_ALLOWED\_ORIGINS Specific only `.sample.env:109` CORS\_ALLOW\_CREDENTIALS FALSE `.sample.env:124` CORS\_MAX\_AGE 86400 (24h) `.sample.env:128` #### [hashtag](https://docs.openalgo.in/security/practices#security-features-1) Security Features * **Disabled by Default:** Must be explicitly enabled * **No Wildcard Origins:** Specific origins required * **API Routes Only:** Applied only to `/api/*` **Location:** `cors.py`, `app.py:117-119` * * * ### [hashtag](https://docs.openalgo.in/security/practices#id-14.-security-headers) 14\. Security Headers #### [hashtag](https://docs.openalgo.in/security/practices#additional-headers) Additional Headers Header Value Location Referrer-Policy strict-origin-when-cross-origin `csp.py:127` Permissions-Policy Restrictive defaults `csp.py:132` #### [hashtag](https://docs.openalgo.in/security/practices#permissions-policy) Permissions Policy * * * ### [hashtag](https://docs.openalgo.in/security/practices#id-15.-multi-factor-authentication) 15\. Multi-Factor Authentication #### [hashtag](https://docs.openalgo.in/security/practices#totp-support) TOTP Support Feature Implementation Location TOTP Generation pyotp library `database/user_db.py:99-102` QR Code Setup Scannable QR for authenticator apps `blueprints/auth.py:321-334` Password Reset TOTP or Email options `blueprints/auth.py:83-269` #### [hashtag](https://docs.openalgo.in/security/practices#user-enumeration-prevention) User Enumeration Prevention Password reset returns the same response regardless of whether the email exists. **Location:** `blueprints/auth.py:98-106` * * * ### [hashtag](https://docs.openalgo.in/security/practices#id-16.-vulnerability-management) 16\. Vulnerability Management #### [hashtag](https://docs.openalgo.in/security/practices#github-dependabot-integration) GitHub Dependabot Integration Practice Status CVE Monitoring Active via Dependabot alerts Regular Updates Security patches applied regularly Dependency Tracking Automated vulnerability detection #### [hashtag](https://docs.openalgo.in/security/practices#security-response) Security Response * Regular CVE vulnerability fixes from Dependabot alerts * Timely security patches for dependencies * Supply chain security monitoring * * * ### [hashtag](https://docs.openalgo.in/security/practices#id-17.-security-libraries) 17\. Security Libraries #### [hashtag](https://docs.openalgo.in/security/practices#core-security-dependencies) Core Security Dependencies Library Version Purpose argon2-cffi 23.1.0 Password hashing cryptography 44.0.1 Fernet encryption Flask-WTF 1.2.1 CSRF protection Flask-Limiter 3.7.0 Rate limiting Flask-Cors 6.0.0 CORS management pyotp 2.9.0 TOTP authentication Flask-SQLAlchemy 3.1.1 SQL injection prevention bcrypt 4.1.3 Legacy password support * * * ### [hashtag](https://docs.openalgo.in/security/practices#security-architecture-diagram) Security Architecture Diagram * * * ### [hashtag](https://docs.openalgo.in/security/practices#summary) Summary OpenAlgo implements comprehensive security controls across all application layers: Layer Controls **Network** CORS, CSP, Security Headers, Rate Limiting **Authentication** Argon2, TOTP, Session Security **Authorization** CSRF, API Key Verification **Data** Fernet Encryption, Input Validation **Database** SQLAlchemy ORM, Parameterized Queries **Monitoring** Traffic Logging, IP Banning, Audit Trails **Infrastructure** Docker Hardening, Non-Root User **Supply Chain** Dependabot CVE Monitoring * * * _This document is maintained as part of OpenAlgo's security documentation. For security concerns, please report to the maintainers._ [PreviousBan IPchevron-left](https://docs.openalgo.in/security/ban-ip) [Nextreleasechevron-right](https://docs.openalgo.in/change-log/release) Last updated 4 months ago * [OpenAlgo Security Practices Report](https://docs.openalgo.in/security/practices#openalgo-security-practices-report) * [Executive Summary](https://docs.openalgo.in/security/practices#executive-summary) * [1\. Password & Credential Security](https://docs.openalgo.in/security/practices#id-1.-password-and-credential-security) * [2\. API Key Security](https://docs.openalgo.in/security/practices#id-2.-api-key-security) * [3\. Encryption](https://docs.openalgo.in/security/practices#id-3.-encryption) * [4\. Session Security](https://docs.openalgo.in/security/practices#id-4.-session-security) * [5\. CSRF Protection](https://docs.openalgo.in/security/practices#id-5.-csrf-protection) * [6\. Rate Limiting](https://docs.openalgo.in/security/practices#id-6.-rate-limiting) * [7\. Input Validation](https://docs.openalgo.in/security/practices#id-7.-input-validation) * [8\. SQL Injection Prevention](https://docs.openalgo.in/security/practices#id-8.-sql-injection-prevention) * [9\. XSS Prevention (Content Security Policy)](https://docs.openalgo.in/security/practices#id-9.-xss-prevention-content-security-policy) * [10\. IP Security & Banning](https://docs.openalgo.in/security/practices#id-10.-ip-security-and-banning) * [11\. Logging & Audit Trails](https://docs.openalgo.in/security/practices#id-11.-logging-and-audit-trails) * [12\. Docker Security](https://docs.openalgo.in/security/practices#id-12.-docker-security) * [13\. CORS Configuration](https://docs.openalgo.in/security/practices#id-13.-cors-configuration) * [14\. Security Headers](https://docs.openalgo.in/security/practices#id-14.-security-headers) * [15\. Multi-Factor Authentication](https://docs.openalgo.in/security/practices#id-15.-multi-factor-authentication) * [16\. Vulnerability Management](https://docs.openalgo.in/security/practices#id-16.-vulnerability-management) * [17\. Security Libraries](https://docs.openalgo.in/security/practices#id-17.-security-libraries) * [Security Architecture Diagram](https://docs.openalgo.in/security/practices#security-architecture-diagram) * [Summary](https://docs.openalgo.in/security/practices#summary) sun-brightdesktopmoon Copy - Minimum 8 characters - At least 1 uppercase letter (A-Z) - At least 1 lowercase letter (a-z) - At least 1 number (0-9) - At least 1 special character (!@#$%^&*) Copy # Example validations used validate.OneOf(["BUY", "SELL"]) # Enum validation validate.Range(min=1) # Numeric range validate.Length(min=1, max=20) # Array length fields.Nested() # Complex object validation Copy # Safe - parameterized query user = User.query.filter_by(username=username).first() # Never used - unsafe string concatenation # cursor.execute(f"SELECT * FROM users WHERE username='{username}'") Copy CSP_ENABLED = TRUE CSP_REPORT_ONLY = FALSE CSP_REPORT_URI = "" CSP_UPGRADE_INSECURE_REQUESTS = FALSE Copy - api_key, apikey, api-key - password, passwd - token, access_token, refresh_token - secret, client_secret - authorization header - Bearer tokens Copy camera=() microphone=() geolocation=() payment=() usb=() screen-wake-lock=() web-share=() Copy ┌─────────────────────────────────────────┐ │ INTERNET │ └─────────────────┬───────────────────────┘ │ ┌─────────────────▼───────────────────────┐ │ NGINX REVERSE PROXY │ │ - SSL/TLS Termination │ │ - Rate Limiting │ │ - Security Headers │ └─────────────────┬───────────────────────┘ │ ┌───────────────────────────┼───────────────────────────┐ │ │ │ ▼ ▼ ▼ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ IP Ban Check │ │ Rate Limiter │ │ CSRF Check │ │ (Middleware) │ │ (Flask-Limiter)│ │ (Flask-WTF) │ └────────┬────────┘ └────────┬────────┘ └────────┬────────┘ │ │ │ └────────────────────────┼────────────────────────┘ │ ┌─────────────▼───────────────────────┐ │ INPUT VALIDATION │ │ (Marshmallow Schemas) │ └─────────────┬───────────────────────┘ │ ┌───────────────────────┼───────────────────────┐ │ │ │ ▼ ▼ ▼ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ Session Auth │ │ API Key Auth │ │ TOTP Auth │ │ (Cookies) │ │ (Argon2) │ │ (pyotp) │ └────────┬────────┘ └────────┬────────┘ └────────┬────────┘ │ │ │ └──────────────────────┼──────────────────────┘ │ ┌───────────▼─────────────────────────┐ │ APPLICATION │ │ - SQLAlchemy ORM (SQL Prevention) │ │ - Fernet Encryption (Tokens) │ │ - Audit Logging (Traffic) │ └───────────┬─────────────────────────┘ │ ┌───────────▼─────────────────────────┐ │ DATABASE │ │ - Encrypted Tokens │ │ - Hashed Passwords (Argon2) │ │ - Hashed API Keys │ └─────────────────────────────────────┘ sun-brightdesktopmoon --- # 43 - Telegram Bot Configuration | Documentation ### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#overview) Overview OpenAlgo integrates with Telegram to provide real-time trading notifications, account information, and bot commands. Users can configure their Telegram bot to receive order alerts, position updates, and execute queries. ### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#architecture-diagram) Architecture Diagram Copy ┌──────────────────────────────────────────────────────────────────────────────┐ │ Telegram Bot Architecture │ └──────────────────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────────────────┐ │ Telegram Cloud │ │ │ │ ┌─────────────────┐ ┌─────────────────┐ │ │ │ User's │ │ Bot Father │ │ │ │ Telegram App │ │ @BotFather │ │ │ └────────┬────────┘ └────────┬────────┘ │ │ │ │ │ │ │ Messages/Commands │ Create Bot Token │ │ │ │ │ │ └────────────────┬───────────────┘ │ │ │ │ │ Bot API Gateway │ │ │ │ └────────────────────────────┼────────────────────────────────────────────────┘ │ │ Webhook / Long Polling │ ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ │ OpenAlgo Backend │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ Telegram Blueprint │ │ │ │ /telegram/* │ │ │ │ │ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │ │ │ /settings │ │ /webhook │ │ /test │ │ │ │ │ │ Configure │ │ Receive │ │ Send test │ │ │ │ │ │ bot token │ │ updates │ │ message │ │ │ │ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ Telegram Service │ │ │ │ │ │ │ │ ┌──────────────────────────────────────────────────────────────┐ │ │ │ │ │ Command Handler │ │ │ │ │ │ │ │ │ │ │ │ /start - Initialize bot │ │ │ │ │ │ /help - Show commands │ │ │ │ │ │ /funds - Account balance │ │ │ │ │ │ /positions- Open positions │ │ │ │ │ │ /orders - Order book │ │ │ │ │ │ /holdings - Portfolio holdings │ │ │ │ │ │ /trades - Trade book │ │ │ │ │ │ /pnl - P&L summary │ │ │ │ │ │ /quote - Get LTP │ │ │ │ │ │ /status - Connection status │ │ │ │ │ │ /alerts - Toggle alerts │ │ │ │ │ │ /settings - Preferences │ │ │ │ │ │ /logout - Disconnect │ │ │ │ │ └──────────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ Database Layer │ │ │ │ │ │ │ │ telegram_users │ bot_config │ command_log │ notification_queue │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────────────┘ ### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#database-schema) Database Schema #### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#telegram_users-table) telegram\_users Table #### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#bot_config-table) bot\_config Table #### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#notification_queue-table) notification\_queue Table #### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#user_preferences-table) user\_preferences Table ### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#bot-commands) Bot Commands #### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#command-reference) Command Reference Command Description Example /start Initialize bot and link account /start /help Display available commands /help /funds Get account balance and margin /funds /positions View open positions with P&L /positions /orders Get today's order book /orders /holdings View portfolio holdings /holdings /trades Get executed trades /trades /pnl Get P&L summary /pnl /quote SYMBOL Get last traded price /quote SBIN /status Check broker connection /status /alerts on/off Toggle notifications /alerts on /settings View/modify preferences /settings /logout Disconnect bot /logout ### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#configuration-flow) Configuration Flow ### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#service-implementation) Service Implementation #### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#bot-token-security) Bot Token Security #### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#command-handler) Command Handler #### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#notification-service) Notification Service ### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#api-endpoints) API Endpoints #### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#save-configuration) Save Configuration #### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#test-connection) Test Connection **Response:** #### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#webhook-endpoint) Webhook Endpoint ### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#notification-types) Notification Types #### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#order-notifications) Order Notifications #### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#position-alerts) Position Alerts #### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#p-and-l-summary) P&L Summary ### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#error-handling) Error Handling #### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#rate-limiting) Rate Limiting #### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#retry-logic) Retry Logic ### [hashtag](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#key-files-reference) Key Files Reference File Purpose `blueprints/telegram.py` Telegram routes and webhook `services/telegram_bot_service.py` Bot command handlers `services/telegram_alert_service.py` Alert/notification service `database/telegram_db.py` Database models `restx_api/telegram_bot.py` REST API endpoints `frontend/src/pages/TelegramSettings.tsx` Configuration UI [Previous42 - Action Centerchevron-left](https://docs.openalgo.in/developers/design-documentation/42-action-center) [Next44 - Toast Notifications Systemchevron-right](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system) Last updated 1 month ago * [Overview](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#overview) * [Architecture Diagram](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#architecture-diagram) * [Database Schema](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#database-schema) * [Bot Commands](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#bot-commands) * [Configuration Flow](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#configuration-flow) * [Service Implementation](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#service-implementation) * [API Endpoints](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#api-endpoints) * [Notification Types](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#notification-types) * [Error Handling](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#error-handling) * [Key Files Reference](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration#key-files-reference) sun-brightdesktopmoon Copy ┌────────────────────────────────────────────────────────────────┐ │ telegram_users table │ ├──────────────────┬──────────────┬──────────────────────────────┤ │ Column │ Type │ Description │ ├──────────────────┼──────────────┼──────────────────────────────┤ │ id │ INTEGER PK │ Auto-increment │ │ user_id │ VARCHAR(255) │ OpenAlgo user ID │ │ telegram_id │ BIGINT │ Telegram chat ID │ │ username │ VARCHAR(255) │ Telegram username │ │ first_name │ VARCHAR(255) │ User's first name │ │ is_active │ BOOLEAN │ Bot active status │ │ linked_at │ DATETIME │ When linked │ │ last_activity │ DATETIME │ Last command time │ └──────────────────┴──────────────┴──────────────────────────────┘ Copy ┌────────────────────────────────────────────────────────────────┐ │ bot_config table │ ├──────────────────┬──────────────┬──────────────────────────────┤ │ Column │ Type │ Description │ ├──────────────────┼──────────────┼──────────────────────────────┤ │ id │ INTEGER PK │ Auto-increment │ │ user_id │ VARCHAR(255) │ OpenAlgo user ID (unique) │ │ bot_token │ TEXT │ Encrypted bot token │ │ webhook_url │ VARCHAR(500) │ Webhook endpoint │ │ is_enabled │ BOOLEAN │ Bot enabled status │ │ created_at │ DATETIME │ Configuration created │ │ updated_at │ DATETIME │ Last modified │ └──────────────────┴──────────────┴──────────────────────────────┘ Copy ┌────────────────────────────────────────────────────────────────┐ │ notification_queue table │ ├──────────────────┬──────────────┬──────────────────────────────┤ │ Column │ Type │ Description │ ├──────────────────┼──────────────┼──────────────────────────────┤ │ id │ INTEGER PK │ Auto-increment │ │ user_id │ VARCHAR(255) │ Target user │ │ message_type │ VARCHAR(50) │ order/position/alert │ │ message │ TEXT │ Message content │ │ status │ VARCHAR(20) │ pending/sent/failed │ │ created_at │ DATETIME │ Queue time │ │ sent_at │ DATETIME │ Delivery time │ │ retry_count │ INTEGER │ Retry attempts │ └──────────────────┴──────────────┴──────────────────────────────┘ Copy ┌────────────────────────────────────────────────────────────────┐ │ user_preferences table │ ├──────────────────┬──────────────┬──────────────────────────────┤ │ Column │ Type │ Description │ ├──────────────────┼──────────────┼──────────────────────────────┤ │ id │ INTEGER PK │ Auto-increment │ │ user_id │ VARCHAR(255) │ User ID (unique) │ │ order_alerts │ BOOLEAN │ Order notifications │ │ position_alerts │ BOOLEAN │ Position updates │ │ pnl_alerts │ BOOLEAN │ P&L notifications │ │ daily_summary │ BOOLEAN │ End of day summary │ │ alert_threshold │ DECIMAL │ P&L alert threshold │ └──────────────────┴──────────────┴──────────────────────────────┘ Copy ┌────────────────────────────────────────────────────────────────────────────┐ │ Telegram Bot Setup Flow │ │ │ │ 1. Create Bot with BotFather ─────────────────────────────────────────► │ │ │ │ │ ├──► Message @BotFather │ │ ├──► /newbot command │ │ ├──► Set bot name and username │ │ └──► Receive bot token │ │ │ │ │ ▼ │ │ 2. Configure in OpenAlgo ─────────────────────────────────────────────► │ │ │ │ │ ├──► Go to Settings > Telegram │ │ ├──► Enter bot token │ │ ├──► Set webhook URL (optional) │ │ └──► Save configuration │ │ │ │ │ ▼ │ │ 3. Link Telegram Account ─────────────────────────────────────────────► │ │ │ │ │ ├──► Open bot in Telegram │ │ ├──► Send /start command │ │ ├──► Enter verification code │ │ └──► Account linked │ │ │ │ │ ▼ │ │ 4. Configure Notifications ───────────────────────────────────────────► │ │ │ │ │ ├──► /settings in Telegram │ │ ├──► Select notification types │ │ └──► Set thresholds │ │ │ └────────────────────────────────────────────────────────────────────────────┘ Copy from cryptography.fernet import Fernet from utils.env_utils import get_fernet_key def encrypt_bot_token(token): """Encrypt bot token before storage""" key = get_fernet_key() fernet = Fernet(key) return fernet.encrypt(token.encode()).decode() def decrypt_bot_token(encrypted_token): """Decrypt bot token for use""" key = get_fernet_key() fernet = Fernet(key) return fernet.decrypt(encrypted_token.encode()).decode() Copy def handle_telegram_command(update): """Process incoming Telegram command""" chat_id = update['message']['chat']['id'] text = update['message'].get('text', '') # Parse command if text.startswith('/'): command = text.split()[0].lower() args = text.split()[1:] if len(text.split()) > 1 else [] handlers = { '/start': handle_start, '/help': handle_help, '/funds': handle_funds, '/positions': handle_positions, '/orders': handle_orders, '/holdings': handle_holdings, '/trades': handle_trades, '/pnl': handle_pnl, '/quote': handle_quote, '/status': handle_status, '/alerts': handle_alerts, '/settings': handle_settings, '/logout': handle_logout } handler = handlers.get(command, handle_unknown) return handler(chat_id, args) Copy from concurrent.futures import ThreadPoolExecutor executor = ThreadPoolExecutor(max_workers=4) def send_notification_async(user_id, message_type, message): """Send notification in background thread""" executor.submit(_send_notification, user_id, message_type, message) def _send_notification(user_id, message_type, message): """Send Telegram notification""" # Get user's telegram config config = get_bot_config(user_id) telegram_user = get_telegram_user(user_id) if not config or not telegram_user or not config.is_enabled: return # Check user preferences prefs = get_user_preferences(user_id) if message_type == 'order' and not prefs.order_alerts: return # Send via Telegram API bot_token = decrypt_bot_token(config.bot_token) send_telegram_message(bot_token, telegram_user.telegram_id, message) # Log notification log_notification(user_id, message_type, 'sent') Copy POST /telegram/settings Content-Type: application/json { "bot_token": "123456:ABC-DEF...", "webhook_url": "https://example.com/webhook", "is_enabled": true } Copy POST /telegram/test Copy { "status": "success", "message": "Test message sent successfully" } Copy POST /telegram/webhook Content-Type: application/json { "update_id": 123456789, "message": { "chat": {"id": 987654321}, "text": "/funds" } } Copy 📊 Order Executed Symbol: SBIN Action: BUY Quantity: 100 Price: ₹625.50 Status: COMPLETE Order ID: 230125000123 Time: 10:30:15 IST Copy 📈 Position Update Symbol: SBIN Quantity: 100 Entry: ₹625.50 LTP: ₹630.00 P&L: +₹450.00 (+0.72%) Time: 10:45:00 IST Copy 📊 Daily P&L Summary Realized: +₹2,500.00 Unrealized: +₹1,250.00 Total: +₹3,750.00 Trades: 5 Win Rate: 80% Date: 25-Jan-2025 Copy TELEGRAM_RATE_LIMIT = 30 # messages per second def check_rate_limit(user_id): """Ensure rate limit compliance""" key = f"telegram_rate:{user_id}" count = cache.get(key, 0) if count >= TELEGRAM_RATE_LIMIT: return False cache.set(key, count + 1, ttl=1) return True Copy MAX_RETRIES = 3 RETRY_DELAY = [1, 5, 15] # seconds def send_with_retry(bot_token, chat_id, message): """Send message with retry on failure""" for attempt in range(MAX_RETRIES): try: response = send_telegram_message(bot_token, chat_id, message) if response.ok: return True except Exception as e: logger.error(f"Telegram send failed: {e}") if attempt < MAX_RETRIES - 1: time.sleep(RETRY_DELAY[attempt]) return False sun-brightdesktopmoon --- # 44 - Toast Notifications System | Documentation This document describes the toast notification system in OpenAlgo's React frontend, including guidelines for developers adding new features. ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#overview) Overview OpenAlgo uses [Sonnerarrow-up-right](https://sonner.emilkowal.ski/) (v2.0.7) as the underlying toast library, wrapped with a custom utility that provides category-based filtering. This allows users to control which types of notifications they see via the **Profile > Alerts** settings. ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#architecture) Architecture Copy ┌─────────────────────────────────────────────────────────────────────────────┐ │ Toast Notification Flow │ └─────────────────────────────────────────────────────────────────────────────┘ ┌──────────────┐ ┌──────────────────┐ ┌──────────────┐ ┌────────────┐ │ Component │───▶│ showToast │───▶│ alertStore │───▶│ sonner │ │ (Feature) │ │ (utils/toast) │ │ (check) │ │ (UI) │ └──────────────┘ └──────────────────┘ └──────────────┘ └────────────┘ │ │ │ ▼ │ ┌──────────────────┐ │ │ User Preferences │ │ │ (localStorage) │ │ └──────────────────┘ │ ▼ Category Check: - Is master toggle ON? - Is category enabled? ──────────────────── If YES → Show toast If NO → Suppress ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#key-files) Key Files File Purpose `frontend/src/utils/toast.ts` Toast wrapper utility with category filtering `frontend/src/stores/alertStore.ts` Zustand store for user preferences `frontend/src/components/ui/sonner.tsx` Sonner Toaster component `frontend/src/app/providers.tsx` Toaster configuration (position, duration) `frontend/src/pages/Profile.tsx` Alerts settings UI (Profile > Alerts tab) `frontend/src/hooks/useSocket.ts` Socket.IO toast events (real-time) ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#available-categories) Available Categories The following categories are available for toast notifications: Category Description Use Cases `orders` Order-related notifications Order placed, cancelled, modified, rejected `analyzer` Sandbox/analyzer mode operations Mode toggle, paper trading actions `system` System-wide notifications Login, logout, password change, theme `actionCenter` Semi-auto order approval Pending order alerts `historify` Historical data operations Download jobs, schedules, uploads `strategy` TradingView strategy management Strategy CRUD, symbol mapping `positions` Position operations Close position, PnL tracker `chartink` Chartink strategy operations Chartink strategy CRUD `pythonStrategy` Python strategy operations Upload, start, stop, schedule `telegram` Telegram bot operations Bot config, user management `flow` Workflow automation Workflow CRUD, execution `admin` Admin panel operations Market timings, holidays, freeze qty `monitoring` Monitoring dashboards Health, latency, security, traffic `clipboard` Copy to clipboard feedback Any copy operation ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#developer-guidelines) Developer Guidelines #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#id-1.-always-use-the-showtoast-utility) 1\. Always Use the showToast Utility **DO:** **DON'T:** #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#id-2.-always-include-a-category) 2\. Always Include a Category Every toast call should include a category as the second parameter: **Examples:** #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#id-3.-choose-the-right-category) 3\. Choose the Right Category When adding a new feature, determine which category best fits: * **New trading feature** → `orders` or `positions` * **New strategy type** → `strategy`, `chartink`, or `pythonStrategy` * **New admin feature** → `admin` * **New monitoring feature** → `monitoring` * **Copy operations** → `clipboard` * **Authentication/system** → `system` #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#id-4.-when-to-show-toasts) 4\. When to Show Toasts **DO show toasts for:** * Successful operations (create, update, delete) * Failed operations with user-actionable errors * Important state changes * Copy to clipboard confirmation **DON'T show toasts for:** * Loading states (use spinners instead) * Every API response * Validation errors in forms (show inline) * Background refresh operations #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#id-5.-toast-options) 5\. Toast Options You can pass additional options as the third parameter: #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#id-6.-validation-errors) 6\. Validation Errors For form validation errors that must always show (regardless of user settings), you can omit the category: Or import raw toast for critical system messages: ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#adding-a-new-category) Adding a New Category If you're adding a major new feature that doesn't fit existing categories: #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#id-1.-update-alertstore.ts) 1\. Update alertStore.ts #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#id-2.-update-profile.tsx-alerts-tab) 2\. Update Profile.tsx Alerts Tab #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#id-3.-use-the-new-category) 3\. Use the New Category ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#socket.io-real-time-toasts) Socket.IO Real-Time Toasts For real-time events via Socket.IO, the pattern is slightly different: ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#user-settings) User Settings Users control toast behavior via **Profile > Alerts**: #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#master-controls) Master Controls * **Enable Toasts**: Master toggle for all toast notifications * **Enable Sounds**: Toggle alert sounds (for supported browsers) #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#category-toggles) Category Toggles Users can enable/disable each category independently. #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#display-settings) Display Settings * **Position**: Where toasts appear (top-right, bottom-right, etc.) * **Max Visible**: Maximum toasts shown at once (1-10) * **Duration**: How long toasts stay visible (1-30 seconds) #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#actions) Actions * **Test Toast**: Preview current settings * **Clear All**: Dismiss all visible toasts * **Reset to Defaults**: Restore default settings ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#testing) Testing When testing toast functionality: 1. **Test with all categories enabled** (default) 2. **Test with specific category disabled** - verify toast is suppressed 3. **Test with master toggle disabled** - verify all toasts suppressed 4. **Test position/duration settings** - verify display changes ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#common-patterns) Common Patterns #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#crud-operations) CRUD Operations #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#copy-to-clipboard) Copy to Clipboard #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#toggle-operations) Toggle Operations ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#migration-guide) Migration Guide If you find code using raw sonner imports: ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#summary) Summary 1. **Always use** `**showToast**` from `@/utils/toast` 2. **Always include a category** as the second parameter 3. **Choose the appropriate category** based on feature type 4. **Test with user settings** to ensure proper filtering 5. **Add new categories** only for major new feature areas [Previous43 - Telegram Bot Configurationchevron-left](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration) [Next44 - PnL Trackerchevron-right](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker) Last updated 1 month ago * [Overview](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#overview) * [Architecture](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#architecture) * [Key Files](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#key-files) * [Available Categories](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#available-categories) * [Developer Guidelines](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#developer-guidelines) * [Adding a New Category](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#adding-a-new-category) * [Socket.IO Real-Time Toasts](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#socket.io-real-time-toasts) * [User Settings](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#user-settings) * [Testing](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#testing) * [Common Patterns](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#common-patterns) * [Migration Guide](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#migration-guide) * [Summary](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system#summary) sun-brightdesktopmoon Copy import { showToast } from '@/utils/toast' showToast.success('Order placed successfully', 'orders') showToast.error('Failed to load data', 'strategy') Copy // Never import toast directly from sonner in feature files import { toast } from 'sonner' // BAD toast.success('Order placed') // BAD - no category control Copy // Syntax showToast.success(message: string, category: AlertCategory, options?: ToastOptions) showToast.error(message: string, category: AlertCategory, options?: ToastOptions) showToast.warning(message: string, category: AlertCategory, options?: ToastOptions) showToast.info(message: string, category: AlertCategory, options?: ToastOptions) Copy // Order operations showToast.success('Order placed', 'orders') showToast.error('Order rejected', 'orders') // Strategy operations showToast.success('Strategy created', 'strategy') showToast.error('Failed to load strategy', 'strategy') // Copy to clipboard showToast.success('Copied to clipboard', 'clipboard') showToast.error('Failed to copy', 'clipboard') // Admin operations showToast.success('Settings saved', 'admin') showToast.error('Failed to update', 'admin') Copy showToast.warning('New order pending', 'actionCenter', { duration: 5000, // 5 seconds (default is from user settings) description: 'Click to view details' }) Copy // These always show - no category means no filtering showToast.error('Please fill all required fields') showToast.error('Invalid email format') Copy import { toast } from '@/utils/toast' // Re-exported raw toast toast.error('Critical system error') // Always shows Copy // frontend/src/stores/alertStore.ts export interface AlertCategories { // ... existing categories newFeature: boolean // Add your new category } const DEFAULT_CATEGORIES: AlertCategories = { // ... existing defaults newFeature: true, // Default to enabled } Copy // frontend/src/pages/Profile.tsx // Add to the appropriate section in CATEGORY_GROUPS { key: 'newFeature', label: 'New Feature', description: 'Notifications for new feature operations', }, Copy showToast.success('New feature action completed', 'newFeature') Copy // frontend/src/hooks/useSocket.ts import { toast } from 'sonner' import { useAlertStore, type AlertCategories } from '@/stores/alertStore' // Helper function for socket events const showCategoryToast = ( type: 'success' | 'error' | 'warning' | 'info', message: string, category?: keyof AlertCategories ) => { const { shouldShowToast } = useAlertStore.getState() if (shouldShowToast(category)) { toast[type](message) } } // Usage in socket event handlers socket.on('order_update', (data) => { showCategoryToast('success', `Order ${data.status}`, 'orders') }) Copy // Create const handleCreate = async () => { try { const response = await api.create(data) if (response.status === 'success') { showToast.success('Item created successfully', 'strategy') } else { showToast.error(response.message || 'Failed to create item', 'strategy') } } catch (error) { showToast.error('Failed to create item', 'strategy') } } // Delete const handleDelete = async () => { try { const response = await api.delete(id) if (response.status === 'success') { showToast.success('Item deleted', 'strategy') } else { showToast.error(response.message || 'Failed to delete', 'strategy') } } catch (error) { showToast.error('Failed to delete item', 'strategy') } } Copy const copyToClipboard = async (text: string) => { try { await navigator.clipboard.writeText(text) showToast.success('Copied to clipboard', 'clipboard') } catch { showToast.error('Failed to copy', 'clipboard') } } Copy const handleToggle = async () => { try { const response = await api.toggle(id) if (response.status === 'success') { showToast.success( response.data?.is_active ? 'Activated' : 'Deactivated', 'strategy' ) } else { showToast.error(response.message || 'Failed to toggle', 'strategy') } } catch { showToast.error('Failed to toggle', 'strategy') } } Copy // Before import { toast } from 'sonner' toast.success('Done') // After import { showToast } from '@/utils/toast' showToast.success('Done', 'appropriateCategory') sun-brightdesktopmoon --- # 51 - Broker and System Config | Documentation ### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#overview) Overview The Profile section in OpenAlgo provides configuration interfaces for broker credentials and system settings. These settings are stored in the `.env` file and database, with security measures for sensitive data. ### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#architecture-diagram) Architecture Diagram Copy ┌──────────────────────────────────────────────────────────────────────────────┐ │ Broker & System Configuration Architecture │ └──────────────────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────────────────┐ │ Profile Section │ │ /profile │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ [Broker Config] [System Settings] [Security] [About] │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ Broker Configuration │ │ │ │ │ │ │ │ Select Broker: [Zerodha ▼] │ │ │ │ │ │ │ │ API Key: [kite_api_key_xxxx ] │ │ │ │ API Secret: [•••••••••••••••••• ] │ │ │ │ User ID: [AB1234 ] │ │ │ │ Password: [•••••••• ] │ │ │ │ TOTP Key: [•••••••••••• ] │ │ │ │ │ │ │ │ [Test Connection] [Save Changes] │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ System Settings │ │ │ │ │ │ │ │ App Host: [127.0.0.1 ] │ │ │ │ App Port: [5000 ] │ │ │ │ Debug Mode: [ ] Enabled │ │ │ │ Log Level: [INFO ▼] │ │ │ │ │ │ │ │ WebSocket Host: [127.0.0.1 ] │ │ │ │ WebSocket Port: [8765 ] │ │ │ │ │ │ │ │ [Save Settings] │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────────────┘ │ │ Save │ ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ │ Configuration Storage │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ .env File │ │ │ │ │ │ │ │ # Broker Configuration │ │ │ │ BROKER_API_KEY=kite_api_key_xxxx │ │ │ │ BROKER_API_SECRET=encrypted_or_masked │ │ │ │ BROKER=zerodha │ │ │ │ │ │ │ │ # System Configuration │ │ │ │ FLASK_HOST=127.0.0.1 │ │ │ │ FLASK_PORT=5000 │ │ │ │ FLASK_DEBUG=False │ │ │ │ │ │ │ │ # WebSocket Configuration │ │ │ │ WEBSOCKET_HOST=127.0.0.1 │ │ │ │ WEBSOCKET_PORT=8765 │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ Database (Encrypted) │ │ │ │ │ │ │ │ broker_credentials table │ │ │ │ • Sensitive values encrypted with Fernet │ │ │ │ • Access tokens refreshed automatically │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────────────┘ ### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#broker-configuration) Broker Configuration #### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#supported-brokers) Supported Brokers Broker Auth Type Required Fields Zerodha OAuth2 API Key, API Secret Dhan API Key Client ID, Access Token Angel One API Key API Key, Client Code, Password, TOTP 5paisa OAuth2 User ID, Password, 2FA Flattrade API Key User ID, API Key, API Secret Upstox OAuth2 API Key, API Secret Fyers OAuth2 App ID, Secret ID IIFL API Key API Key, Password ... ... ... #### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#broker-specific-validation) Broker-Specific Validation #### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#credential-masking) Credential Masking ### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#system-configuration) System Configuration #### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#environment-variables) Environment Variables #### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#configuration-update-service) Configuration Update Service ### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#api-endpoints) API Endpoints #### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#get-broker-config) Get Broker Config **Response:** #### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#update-broker-config) Update Broker Config #### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#get-system-config) Get System Config **Response:** #### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#update-system-config) Update System Config #### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#test-broker-connection) Test Broker Connection **Response:** ### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#frontend-components) Frontend Components #### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#broker-config-form) Broker Config Form #### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#system-settings-form) System Settings Form ### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#security-measures) Security Measures #### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#credential-protection) Credential Protection #### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#permission-checking) Permission Checking ### [hashtag](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#key-files-reference) Key Files Reference File Purpose `blueprints/settings.py` Configuration routes `services/config_service.py` Config management logic `utils/env_utils.py` .env file utilities `database/broker_db.py` Broker credentials model `frontend/src/pages/Profile.tsx` Profile page `frontend/src/components/BrokerConfig.tsx` Broker settings UI `frontend/src/components/SystemSettings.tsx` System settings UI [Previous50 - TOTP Configurationchevron-left](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration) [Next52 - Broker Factory Implementationchevron-right](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation) Last updated 1 month ago * [Overview](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#overview) * [Architecture Diagram](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#architecture-diagram) * [Broker Configuration](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#broker-configuration) * [System Configuration](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#system-configuration) * [API Endpoints](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#api-endpoints) * [Frontend Components](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#frontend-components) * [Security Measures](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#security-measures) * [Key Files Reference](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config#key-files-reference) sun-brightdesktopmoon Copy BROKER_FIELD_PATTERNS = { 'zerodha': { 'api_key': r'^[a-z0-9]{16}$', # 16 alphanumeric 'api_secret': r'^[A-Za-z0-9]{32}$' # 32 alphanumeric }, 'dhan': { 'client_id': r'^\d{10}$', # 10 digits 'access_token': r'^[a-zA-Z0-9]+$' }, '5paisa': { 'user_id': r'^[A-Z0-9]{8}$', # 8 alphanumeric uppercase 'encryption_key': r'^[A-Za-z0-9]{32}$' }, 'flattrade': { 'user_id': r'^[A-Z]{2}\d{6}$', # 2 letters + 6 digits 'api_key': r'^[A-Za-z0-9]{32}$' } } def validate_broker_credentials(broker, credentials): """Validate broker credentials format""" patterns = BROKER_FIELD_PATTERNS.get(broker, {}) errors = [] for field, pattern in patterns.items(): value = credentials.get(field, '') if not re.match(pattern, value): errors.append(f"Invalid {field} format for {broker}") return len(errors) == 0, errors Copy def mask_sensitive_value(value, visible_chars=4): """Mask sensitive values for display""" if not value: return '' if len(value) <= visible_chars: return '•' * len(value) return value[:visible_chars] + '•' * (len(value) - visible_chars) def get_masked_credentials(broker): """Get credentials with sensitive fields masked""" creds = get_broker_credentials(broker) masked = {} sensitive_fields = ['api_secret', 'password', 'totp_key', 'access_token'] for key, value in creds.items(): if key in sensitive_fields: masked[key] = mask_sensitive_value(value) else: masked[key] = value return masked Copy ┌────────────────────────────────────────────────────────────────────────────┐ │ System Configuration Variables │ │ │ │ Flask Application │ │ ───────────────── │ │ FLASK_HOST = 127.0.0.1 # Bind address │ │ FLASK_PORT = 5000 # HTTP port │ │ FLASK_DEBUG = False # Debug mode │ │ SECRET_KEY = xxxxxx # Session encryption │ │ │ │ WebSocket Server │ │ ───────────────── │ │ WEBSOCKET_HOST = 127.0.0.1 # WebSocket bind │ │ WEBSOCKET_PORT = 8765 # WebSocket port │ │ ZMQ_PORT = 5555 # ZeroMQ port │ │ │ │ Database │ │ ───────────────── │ │ DATABASE_URL = sqlite:///db/openalgo.db │ │ LOGS_DB_URL = sqlite:///db/logs.db │ │ │ │ Logging │ │ ───────────────── │ │ LOG_LEVEL = INFO # DEBUG/INFO/WARNING/ERROR │ │ LOG_FILE = logs/app.log # Log file path │ │ │ │ Rate Limiting │ │ ───────────────── │ │ RATE_LIMIT_ORDER = 10/second # Order endpoints │ │ RATE_LIMIT_DATA = 3/second # Data endpoints │ │ │ └────────────────────────────────────────────────────────────────────────────┘ Copy import os from dotenv import set_key, dotenv_values ENV_FILE_PATH = '.env' def update_env_variable(key, value): """Update single environment variable""" # Update .env file set_key(ENV_FILE_PATH, key, value) # Update runtime environment os.environ[key] = value return True def update_broker_config(broker, credentials): """Update broker configuration""" # Validate credentials valid, errors = validate_broker_credentials(broker, credentials) if not valid: return False, errors # Update .env updates = { 'BROKER': broker, f'{broker.upper()}_API_KEY': credentials.get('api_key', ''), f'{broker.upper()}_API_SECRET': credentials.get('api_secret', ''), } for key, value in updates.items(): update_env_variable(key, value) return True, None def update_system_config(settings): """Update system configuration""" allowed_keys = [\ 'FLASK_HOST', 'FLASK_PORT', 'FLASK_DEBUG',\ 'WEBSOCKET_HOST', 'WEBSOCKET_PORT',\ 'LOG_LEVEL'\ ] for key, value in settings.items(): if key in allowed_keys: update_env_variable(key, str(value)) return True Copy GET /api/settings/broker Authorization: Bearer ADMIN_TOKEN Copy { "status": "success", "data": { "broker": "zerodha", "credentials": { "api_key": "kite_xxxx", "api_secret": "xxxx••••••••••••••••••••••••", "user_id": "AB1234" }, "status": "connected" } } Copy POST /api/settings/broker Content-Type: application/json Authorization: Bearer ADMIN_TOKEN { "broker": "zerodha", "credentials": { "api_key": "kite_api_key", "api_secret": "kite_api_secret" } } Copy GET /api/settings/system Authorization: Bearer ADMIN_TOKEN Copy { "status": "success", "data": { "flask_host": "127.0.0.1", "flask_port": 5000, "flask_debug": false, "websocket_host": "127.0.0.1", "websocket_port": 8765, "log_level": "INFO" } } Copy POST /api/settings/system Content-Type: application/json Authorization: Bearer ADMIN_TOKEN { "flask_debug": true, "log_level": "DEBUG" } Copy POST /api/settings/broker/test Authorization: Bearer ADMIN_TOKEN Copy { "status": "success", "message": "Connection successful", "data": { "broker": "zerodha", "user_id": "AB1234", "user_name": "John Doe" } } Copy function BrokerConfig() { const [broker, setBroker] = useState(''); const [credentials, setCredentials] = useState>({}); const [testing, setTesting] = useState(false); const brokerFields = { zerodha: ['api_key', 'api_secret'], dhan: ['client_id', 'access_token'], angel: ['api_key', 'client_code', 'password', 'totp_key'], '5paisa': ['user_id', 'password', 'encryption_key'], flattrade: ['user_id', 'api_key', 'api_secret'] }; const testConnection = async () => { setTesting(true); try { const result = await api.testBrokerConnection(); toast.success(`Connected as ${result.user_name}`); } catch (e) { toast.error('Connection failed'); } setTesting(false); }; const saveConfig = async () => { await api.updateBrokerConfig(broker, credentials); toast.success('Configuration saved'); }; return (

Broker Configuration

{broker && brokerFields[broker]?.map(field => (
setCredentials({...credentials, [field]: e.target.value})} className="input input-bordered" placeholder={`Enter ${formatFieldName(field)}`} />
))}
); } Copy function SystemSettings() { const [settings, setSettings] = useState({ flask_host: '127.0.0.1', flask_port: 5000, flask_debug: false, websocket_host: '127.0.0.1', websocket_port: 8765, log_level: 'INFO' }); const saveSettings = async () => { await api.updateSystemConfig(settings); toast.success('Settings saved. Restart required for some changes.'); }; return (

System Settings

setSettings({...settings, flask_host: e.target.value})} className="input input-bordered" />
setSettings({...settings, flask_port: parseInt(e.target.value)})} className="input input-bordered" />
setSettings({...settings, websocket_host: e.target.value})} className="input input-bordered" />
setSettings({...settings, websocket_port: parseInt(e.target.value)})} className="input input-bordered" />
Some changes require application restart to take effect.
); } Copy ┌────────────────────────────────────────────────────────────────────────────┐ │ Credential Security Measures │ │ │ │ 1. Storage │ │ • API secrets encrypted with Fernet before database storage │ │ • .env file permissions restricted (600 on Unix) │ │ │ │ 2. Display │ │ • Sensitive fields masked in UI (••••) │ │ • Only partial values shown in API responses │ │ │ │ 3. Access │ │ • Admin-only endpoints for configuration │ │ • CSRF protection on all forms │ │ • Rate limiting on config endpoints │ │ │ │ 4. Audit │ │ • Configuration changes logged │ │ • Failed authentication attempts tracked │ │ │ └────────────────────────────────────────────────────────────────────────────┘ Copy def check_config_permissions(): """Check if config files have secure permissions""" import stat env_path = '.env' if os.path.exists(env_path): mode = os.stat(env_path).st_mode if mode & stat.S_IROTH or mode & stat.S_IWOTH: logger.warning(".env file has insecure permissions") return False, "Config file permissions too open" return True, None sun-brightdesktopmoon --- # 50 - TOTP Configuration | Documentation ### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#overview) Overview OpenAlgo supports Time-based One-Time Password (TOTP) for two-factor authentication. Users can enable 2FA through QR code scanning with authenticator apps like Google Authenticator, Authy, or Microsoft Authenticator. ### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#architecture-diagram) Architecture Diagram Copy ┌──────────────────────────────────────────────────────────────────────────────┐ │ TOTP Configuration Architecture │ └──────────────────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────────────────┐ │ TOTP Setup Flow │ │ │ │ Step 1: Generate Secret │ │ ───────────────────────── │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ User requests 2FA setup │ │ │ │ │ │ │ │ │ ▼ │ │ │ │ Generate base32 secret (160 bits) │ │ │ │ JBSWY3DPEHPK3PXP... │ │ │ │ │ │ │ │ │ ▼ │ │ │ │ Generate provisioning URI │ │ │ │ otpauth://totp/OpenAlgo:[email protected]?secret=...&issuer=OpenAlgo│ │ │ │ │ │ │ │ │ ▼ │ │ │ │ Generate QR code image │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ Step 2: User Scans QR Code │ │ ───────────────────────────── │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ │ │ │ │ ┌───────────────────┐ Scan with ┌──────────────┐ │ │ │ │ │ ████████████████ │ ───────────────► │ Authenticator│ │ │ │ │ │ █ █ │ │ App │ │ │ │ │ │ █ QR CODE █ │ │ │ │ │ │ │ │ █ █ │ │ 123456 │ │ │ │ │ │ ████████████████ │ │ ────── │ │ │ │ │ └───────────────────┘ │ 29 sec │ │ │ │ │ └──────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ Step 3: Verify and Enable │ │ ────────────────────────── │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ User enters code from app │ │ │ │ │ │ │ │ │ ▼ │ │ │ │ Verify code against secret │ │ │ │ │ │ │ │ │ ├──► Valid: Enable TOTP, store encrypted secret │ │ │ │ │ │ │ │ │ └──► Invalid: Show error, allow retry │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────────────┘ ### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#database-schema) Database Schema #### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#totp-fields-in-users-table) TOTP Fields in users Table ### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#totp-implementation) TOTP Implementation #### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#secret-generation) Secret Generation #### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#qr-code-generation) QR Code Generation #### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#code-verification) Code Verification #### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#secret-encryption) Secret Encryption ### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#backup-codes) Backup Codes #### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#generation) Generation #### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#usage) Usage ### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#api-endpoints) API Endpoints #### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#initialize-totp-setup) Initialize TOTP Setup **Response:** #### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#enable-totp) Enable TOTP **Response:** #### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#disable-totp) Disable TOTP #### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#verify-totp-login) Verify TOTP (Login) ### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#login-flow-with-totp) Login Flow with TOTP #### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#implementation) Implementation ### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#frontend-components) Frontend Components #### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#totp-setup-component) TOTP Setup Component #### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#totp-login-component) TOTP Login Component ### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#security-considerations) Security Considerations Aspect Implementation Secret storage Fernet encrypted in database Code validity 30 seconds (RFC 6238) Clock drift ±1 window (±30 seconds) Rate limiting Max 5 attempts per pending session Backup codes One-time use, SHA-256 hashed Recovery Email reset requires TOTP or backup code ### [hashtag](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#key-files-reference) Key Files Reference File Purpose `database/user_db.py` User model with TOTP methods (`get_totp_uri()`, `verify_totp()`) `blueprints/auth.py` TOTP endpoints (reset-password with TOTP) `frontend/src/pages/TwoFactorSettings.tsx` Setup UI `frontend/src/components/TOTPVerification.tsx` Login verification > **Note**: TOTP functionality is integrated directly into the `User` model in `database/user_db.py`. The model includes: > > * `totp_secret` field - stores the TOTP secret > > * `get_totp_uri()` method - generates provisioning URI for QR codes using `pyotp` > > * `verify_totp()` method - verifies TOTP tokens > > > There are no separate `services/totp_service.py` or `utils/totp_utils.py` files. QR code generation uses the `pyotp` library's `provisioning_uri()` method. [Previous49 - Themeschevron-left](https://docs.openalgo.in/developers/design-documentation/49-themes) [Next51 - Broker and System Configchevron-right](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config) Last updated 1 month ago * [Overview](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#overview) * [Architecture Diagram](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#architecture-diagram) * [Database Schema](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#database-schema) * [TOTP Implementation](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#totp-implementation) * [Backup Codes](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#backup-codes) * [API Endpoints](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#api-endpoints) * [Login Flow with TOTP](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#login-flow-with-totp) * [Frontend Components](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#frontend-components) * [Security Considerations](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#security-considerations) * [Key Files Reference](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration#key-files-reference) sun-brightdesktopmoon Copy ┌────────────────────────────────────────────────────────────────┐ │ users table (TOTP fields) │ ├──────────────────┬──────────────┬──────────────────────────────┤ │ Column │ Type │ Description │ ├──────────────────┼──────────────┼──────────────────────────────┤ │ totp_enabled │ BOOLEAN │ Is 2FA enabled │ │ totp_secret │ TEXT │ Encrypted base32 secret │ │ totp_setup_at │ DATETIME │ When 2FA was enabled │ │ backup_codes │ TEXT │ Encrypted backup codes │ └──────────────────┴──────────────┴──────────────────────────────┘ Copy import pyotp import base64 from cryptography.fernet import Fernet def generate_totp_secret(): """Generate new TOTP secret""" # Generate 160-bit (20 bytes) random secret secret = pyotp.random_base32(length=32) return secret def get_provisioning_uri(secret, email, issuer="OpenAlgo"): """Generate provisioning URI for QR code""" totp = pyotp.TOTP(secret) return totp.provisioning_uri( name=email, issuer_name=issuer ) Copy import qrcode import io import base64 def generate_qr_code(provisioning_uri): """Generate QR code image as base64""" qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4 ) qr.add_data(provisioning_uri) qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white") # Convert to base64 buffer = io.BytesIO() img.save(buffer, format='PNG') buffer.seek(0) return base64.b64encode(buffer.read()).decode() Copy def verify_totp(secret, code, window=1): """Verify TOTP code""" if not secret or not code: return False # Decrypt secret if stored encrypted decrypted_secret = decrypt_totp_secret(secret) totp = pyotp.TOTP(decrypted_secret) # Verify with time window (allows for clock drift) # window=1 means ±30 seconds return totp.verify(code, valid_window=window) Copy def encrypt_totp_secret(secret): """Encrypt TOTP secret for storage""" key = get_fernet_key() fernet = Fernet(key) return fernet.encrypt(secret.encode()).decode() def decrypt_totp_secret(encrypted_secret): """Decrypt TOTP secret for use""" key = get_fernet_key() fernet = Fernet(key) return fernet.decrypt(encrypted_secret.encode()).decode() Copy import secrets def generate_backup_codes(count=10): """Generate backup recovery codes""" codes = [] for _ in range(count): # Generate 8-character alphanumeric code code = secrets.token_hex(4).upper() # Format as XXXX-XXXX formatted = f"{code[:4]}-{code[4:]}" codes.append(formatted) return codes def hash_backup_codes(codes): """Hash backup codes for storage""" import hashlib hashed = [] for code in codes: # Remove formatting for hashing clean_code = code.replace('-', '') hashed.append(hashlib.sha256(clean_code.encode()).hexdigest()) return hashed Copy def use_backup_code(user_id, code): """Use backup code for authentication""" user = User.query.get(user_id) # Get stored hashed codes stored_codes = json.loads(user.backup_codes or '[]') # Hash provided code clean_code = code.replace('-', '').upper() code_hash = hashlib.sha256(clean_code.encode()).hexdigest() if code_hash in stored_codes: # Remove used code stored_codes.remove(code_hash) user.backup_codes = json.dumps(stored_codes) db.session.commit() return True return False Copy POST /api/auth/totp/setup Authorization: Bearer USER_TOKEN Copy { "status": "success", "data": { "secret": "JBSWY3DPEHPK3PXP", "qr_code": "data:image/png;base64,iVBORw0KGgo...", "provisioning_uri": "otpauth://totp/OpenAlgo:[email protected]?secret=JBSWY3DPEHPK3PXP&issuer=OpenAlgo" } } Copy POST /api/auth/totp/enable Content-Type: application/json Authorization: Bearer USER_TOKEN { "code": "123456", "secret": "JBSWY3DPEHPK3PXP" } Copy { "status": "success", "message": "Two-factor authentication enabled", "data": { "backup_codes": [\ "A1B2-C3D4",\ "E5F6-G7H8",\ "I9J0-K1L2",\ "M3N4-O5P6",\ "Q7R8-S9T0"\ ] } } Copy POST /api/auth/totp/disable Content-Type: application/json Authorization: Bearer USER_TOKEN { "code": "123456", "password": "current_password" } Copy POST /api/auth/totp/verify Content-Type: application/json { "session_token": "pending_session_token", "code": "123456" } Copy ┌────────────────────────────────────────────────────────────────────────────┐ │ Login with TOTP Flow │ │ │ │ 1. User submits username/password │ │ │ │ │ ▼ │ │ 2. Validate credentials │ │ │ │ │ ├──► Invalid: Return error │ │ │ │ │ ▼ │ │ 3. Check if TOTP enabled │ │ │ │ │ ├──► Not enabled: Issue session token, login complete │ │ │ │ │ ▼ │ │ 4. TOTP enabled: Return pending session │ │ │ │ │ │ { │ │ │ "status": "totp_required", │ │ │ "session_token": "pending_xxx" │ │ │ } │ │ │ │ │ ▼ │ │ 5. User enters TOTP code │ │ │ │ │ ▼ │ │ 6. Verify TOTP code │ │ │ │ │ ├──► Valid: Upgrade to full session, login complete │ │ │ │ │ └──► Invalid: Allow retry (max 5 attempts) │ │ │ └────────────────────────────────────────────────────────────────────────────┘ Copy def login_with_credentials(username, password): """First step: validate credentials""" user = authenticate_user(username, password) if not user: return {'status': 'error', 'message': 'Invalid credentials'} if user.totp_enabled: # Create pending session pending_token = create_pending_session(user.id) return { 'status': 'totp_required', 'session_token': pending_token } # No TOTP, complete login session_token = create_session(user.id) return { 'status': 'success', 'session_token': session_token } def verify_totp_login(pending_token, code): """Second step: verify TOTP""" pending = get_pending_session(pending_token) if not pending: return {'status': 'error', 'message': 'Invalid session'} user = User.query.get(pending['user_id']) if verify_totp(user.totp_secret, code): # Upgrade to full session session_token = create_session(user.id) delete_pending_session(pending_token) return { 'status': 'success', 'session_token': session_token } return {'status': 'error', 'message': 'Invalid TOTP code'} Copy function TOTPSetup() { const [step, setStep] = useState<'init' | 'verify' | 'backup'>('init'); const [secret, setSecret] = useState(''); const [qrCode, setQrCode] = useState(''); const [code, setCode] = useState(''); const [backupCodes, setBackupCodes] = useState([]); const initSetup = async () => { const data = await api.initTOTPSetup(); setSecret(data.secret); setQrCode(data.qr_code); setStep('verify'); }; const verifyAndEnable = async () => { const data = await api.enableTOTP(code, secret); setBackupCodes(data.backup_codes); setStep('backup'); }; if (step === 'init') { return (

Enable Two-Factor Authentication

Add an extra layer of security to your account

); } if (step === 'verify') { return (

Scan QR Code

Scan with your authenticator app

TOTP QR Code

Can't scan? Enter manually:

{secret}
setCode(e.target.value)} maxLength={6} className="input input-bordered" placeholder="000000" />
); } return (

Save Backup Codes

Save these codes securely. You'll need them if you lose access to your authenticator.

{backupCodes.map((code, i) => ( {code} ))}
); } Copy function TOTPVerification({ sessionToken, onSuccess }: Props) { const [code, setCode] = useState(''); const [error, setError] = useState(''); const handleVerify = async () => { try { const result = await api.verifyTOTP(sessionToken, code); onSuccess(result.session_token); } catch (e) { setError('Invalid code. Please try again.'); setCode(''); } }; return (

Two-Factor Authentication

Enter the code from your authenticator app

{error &&
{error}
} setCode(e.target.value.replace(/\D/g, ''))} maxLength={6} className="input input-bordered text-center text-2xl tracking-widest" placeholder="000000" autoFocus />
); } sun-brightdesktopmoon --- # 52 - Broker Factory Implementation | Documentation This document describes the broker factory design that enables OpenAlgo to work with any of the 29 supported brokers while maintaining a single common interface for the WebSocket proxy system. OpenAlgo allows one user to connect to one broker at a time, and the broker factory ensures consistent implementation across all supported brokers. ### [hashtag](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#architecture-overview) Architecture Overview Copy ┌─────────────────────────────────────────────────────────────┐ │ WebSocket Proxy Server │ │ │ │ ┌────────────────────────────────────────────────────────┐ │ │ │ Broker Factory │ │ │ │ create_broker_adapter(broker_name) → Adapter Instance │ │ │ └──────────────────────────┬─────────────────────────────┘ │ │ │ │ │ ┌───────────────────────┼───────────────────────┐ │ │ ▼ ▼ ▼ │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ │ Zerodha │ │ Angel │ │ Dhan │ │ │ │ Adapter │ │ Adapter │ ... │ Adapter │ │ │ └────┬─────┘ └────┬─────┘ └────┬─────┘ │ │ │ │ │ │ │ └───────────────────┼──────────────────────┘ │ │ │ │ │ ▼ │ │ ┌────────────────────────────────────────────────────────┐ │ │ │ Base Broker WebSocket Adapter │ │ │ │ • initialize() • connect() • subscribe() │ │ │ │ • disconnect() • unsubscribe() • on_data() │ │ │ └────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────┘ ### [hashtag](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#broker-factory) Broker Factory The factory creates appropriate WebSocket adapters based on broker name: ### [hashtag](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#base-adapter-interface) Base Adapter Interface All broker adapters implement this common interface: ### [hashtag](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#broker-specific-adapters) Broker-Specific Adapters #### [hashtag](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#zerodha-adapter) Zerodha Adapter #### [hashtag](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#angel-adapter) Angel Adapter > **Note**: Angel broker sends prices in paise (1/100th of a rupee). The adapter normalizes values by dividing by 100. #### [hashtag](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#dhan-adapter) Dhan Adapter ### [hashtag](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#supported-brokers-29) Supported Brokers (29) Broker Max Symbols Depth Levels Notes Zerodha 3000 5 KiteTicker Angel 1000 5, 20 Prices in paise Dhan 1000 5, 20 DhanHQ SDK Fyers 2000 5 Fyers API v3 Upstox 1500 5, 20 Upstox API v2 5Paisa 1000 5 5Paisa SDK Kotak 1000 5 Neo API IIFL 1000 5 IIFL Markets Motilal 1000 5 Motilal API Alice Blue 1000 5 Ant API Finvasia 1000 5 NorenAPI Flattrade 1000 5 Flattrade API Firstock 1000 5 Firstock API ICICI 1000 5 ICICIdirect Compositedge 1000 5 Composite API Mastertrust 1000 5 MT API Mandot 1000 5 Mandot API Paytm 1000 5 Paytm Money Pocketful 1000 5 Pocketful API Shoonya 1000 5 Shoonya API Tradejini 1000 5 Tradejini API Wisdom 1000 5 Wisdom Capital Zebu 1000 5 Zebu API Mstock 1000 5 Mstock API Nubra 1000 5 gRPC-based streaming ### [hashtag](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#data-normalization) Data Normalization All adapters normalize broker data to OpenAlgo format: ### [hashtag](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#connection-pooling) Connection Pooling For brokers with low symbol limits, connection pooling is used: ### [hashtag](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#usage-in-application) Usage in Application ### [hashtag](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#key-files) Key Files File Purpose `websocket_proxy/broker_factory.py` Adapter factory `websocket_proxy/base_adapter.py` Abstract base class `broker/*/streaming/*_adapter.py` Broker implementations `websocket_proxy/server.py` Main proxy server ### [hashtag](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#adding-a-new-broker) Adding a New Broker 1. Create adapter file: `broker/newbroker/streaming/newbroker_adapter.py` 2. Implement `BaseBrokerWebSocketAdapter` interface 3. Handle broker-specific data normalization 4. Register in factory (or rely on dynamic import) [Previous51 - Broker and System Configchevron-left](https://docs.openalgo.in/developers/design-documentation/51-broker-and-system-config) [NextArchitecturechevron-right](https://docs.openalgo.in/security/architecture) Last updated 1 month ago * [Architecture Overview](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#architecture-overview) * [Broker Factory](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#broker-factory) * [Base Adapter Interface](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#base-adapter-interface) * [Broker-Specific Adapters](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#broker-specific-adapters) * [Supported Brokers (29)](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#supported-brokers-29) * [Data Normalization](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#data-normalization) * [Connection Pooling](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#connection-pooling) * [Usage in Application](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#usage-in-application) * [Key Files](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#key-files) * [Adding a New Broker](https://docs.openalgo.in/developers/design-documentation/52-broker-factory-implementation#adding-a-new-broker) sun-brightdesktopmoon Copy # websocket_proxy/broker_factory.py import importlib import logging from typing import Dict, Type from websocket_proxy.base_adapter import BaseBrokerWebSocketAdapter logger = logging.getLogger(__name__) # Registry of all supported broker adapters BROKER_ADAPTERS: Dict[str, Type[BaseBrokerWebSocketAdapter]] = {} def register_adapter(broker_name: str, adapter_class: Type[BaseBrokerWebSocketAdapter]): """Register a broker adapter class""" BROKER_ADAPTERS[broker_name.lower()] = adapter_class logger.info(f"Registered adapter for broker: {broker_name}") def create_broker_adapter(broker_name: str) -> BaseBrokerWebSocketAdapter: """Create an instance of the appropriate broker adapter""" broker_name = broker_name.lower() # Check if adapter is registered if broker_name in BROKER_ADAPTERS: logger.info(f"Creating adapter for broker: {broker_name}") return BROKER_ADAPTERS[broker_name]() # Try dynamic import if not registered try: module_name = f"broker.{broker_name}.streaming.{broker_name}_adapter" class_name = f"{broker_name.capitalize()}WebSocketAdapter" module = importlib.import_module(module_name) adapter_class = getattr(module, class_name) register_adapter(broker_name, adapter_class) return adapter_class() except (ImportError, AttributeError) as e: logger.error(f"Failed to load adapter for broker {broker_name}: {e}") raise ValueError(f"Unsupported broker: {broker_name}") Copy # websocket_proxy/base_adapter.py from abc import ABC, abstractmethod from typing import Dict, Optional import zmq import logging class BaseBrokerWebSocketAdapter(ABC): """Abstract base class for all broker WebSocket adapters""" def __init__(self): self.connected = False self.subscriptions: Dict[str, dict] = {} self.logger = logging.getLogger(self.__class__.__name__) self.socket: Optional[zmq.Socket] = None @abstractmethod def initialize(self, broker_name: str, user_id: str, auth_data: dict = None): """Initialize connection parameters""" pass @abstractmethod def connect(self): """Establish WebSocket connection to broker""" pass @abstractmethod def disconnect(self): """Close WebSocket connection""" pass @abstractmethod def subscribe(self, symbol: str, exchange: str, mode: int = 2, depth_level: int = 5): """Subscribe to market data Args: symbol: Trading symbol (e.g., 'RELIANCE') exchange: Exchange code (e.g., 'NSE', 'NFO') mode: 1=LTP, 2=Quote, 4=Depth depth_level: 5, 20, or 30 levels """ pass @abstractmethod def unsubscribe(self, symbol: str, exchange: str, mode: int = 2): """Unsubscribe from market data""" pass def on_open(self, ws): """Handle connection open""" self.connected = True self.logger.info("WebSocket connected") self._resubscribe_all() def on_close(self, ws, code=None, reason=None): """Handle connection close""" self.connected = False self.logger.info(f"WebSocket closed: {code} - {reason}") def on_error(self, ws, error): """Handle connection error""" self.logger.error(f"WebSocket error: {error}") def _resubscribe_all(self): """Resubscribe to all symbols after reconnection""" for sub_id, sub_info in self.subscriptions.items(): self.subscribe( sub_info['symbol'], sub_info['exchange'], sub_info['mode'] ) Copy # broker/zerodha/streaming/zerodha_adapter.py from kiteconnect import KiteTicker from websocket_proxy.base_adapter import BaseBrokerWebSocketAdapter class ZerodhaWebSocketAdapter(BaseBrokerWebSocketAdapter): """Zerodha (Kite) WebSocket adapter - 3000 symbols/connection""" MAX_SYMBOLS = 3000 def initialize(self, broker_name, user_id, auth_data=None): self.user_id = user_id self.broker_name = broker_name api_key = auth_data.get('api_key') access_token = auth_data.get('auth_token') self.ws_client = KiteTicker(api_key, access_token) self.ws_client.on_connect = self.on_open self.ws_client.on_close = self.on_close self.ws_client.on_error = self.on_error self.ws_client.on_ticks = self._on_ticks def _on_ticks(self, ws, ticks): """Process incoming tick data""" for tick in ticks: self._normalize_and_publish(tick) Copy # broker/angel/streaming/angel_adapter.py from broker.angel.streaming.smartWebSocketV2 import SmartWebSocketV2 from websocket_proxy.base_adapter import BaseBrokerWebSocketAdapter class AngelWebSocketAdapter(BaseBrokerWebSocketAdapter): """Angel One WebSocket adapter - 1000 symbols/connection""" MAX_SYMBOLS = 1000 PRICE_DIVISOR = 100 # Angel sends prices in paise def initialize(self, broker_name, user_id, auth_data=None): self.user_id = user_id self.broker_name = broker_name auth_token = auth_data.get('auth_token') feed_token = auth_data.get('feed_token') api_key = auth_data.get('api_key') self.ws_client = SmartWebSocketV2( auth_token, api_key, user_id, feed_token, max_retry_attempt=5 ) self.ws_client.on_open = self.on_open self.ws_client.on_data = self._on_data self.ws_client.on_error = self.on_error self.ws_client.on_close = self.on_close def _normalize_price(self, price): """Convert paise to rupees""" return price / self.PRICE_DIVISOR if price else 0 Copy # broker/dhan/streaming/dhan_adapter.py from dhanhq import DhanFeed from websocket_proxy.base_adapter import BaseBrokerWebSocketAdapter class DhanWebSocketAdapter(BaseBrokerWebSocketAdapter): """Dhan WebSocket adapter - 1000 symbols/connection""" MAX_SYMBOLS = 1000 def initialize(self, broker_name, user_id, auth_data=None): self.user_id = user_id self.broker_name = broker_name client_id = auth_data.get('client_id') access_token = auth_data.get('auth_token') self.ws_client = DhanFeed(client_id, access_token) Copy # Normalized LTP message { "symbol": "RELIANCE", "exchange": "NSE", "ltp": 2450.50, "timestamp": "2024-01-15T10:30:00+05:30" } # Normalized Quote message { "symbol": "RELIANCE", "exchange": "NSE", "ltp": 2450.50, "open": 2440.00, "high": 2460.00, "low": 2435.00, "close": 2448.00, "volume": 1500000, "timestamp": "2024-01-15T10:30:00+05:30" } # Normalized Depth message { "symbol": "RELIANCE", "exchange": "NSE", "ltp": 2450.50, "depth": { "buy": [\ {"price": 2450.45, "quantity": 1000, "orders": 5},\ {"price": 2450.40, "quantity": 2500, "orders": 8}\ ], "sell": [\ {"price": 2450.50, "quantity": 800, "orders": 3},\ {"price": 2450.55, "quantity": 1200, "orders": 4}\ ] } } Copy # Connection pool configuration MAX_SYMBOLS_PER_WEBSOCKET = 1000 MAX_WEBSOCKET_CONNECTIONS = 3 # Total capacity: 1000 × 3 = 3000 symbols Copy ┌─────────────────────────────────────────────────────────────┐ │ Connection Pool (Angel) │ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │ Connection 1 │ │ Connection 2 │ │ Connection 3 │ │ │ │ 1000 symbols│ │ 1000 symbols│ │ 1000 symbols│ │ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │ │ │ Total: 3000 symbols │ └─────────────────────────────────────────────────────────────┘ Copy # 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 Copy # broker/newbroker/streaming/newbroker_adapter.py from websocket_proxy.base_adapter import BaseBrokerWebSocketAdapter class NewbrokerWebSocketAdapter(BaseBrokerWebSocketAdapter): MAX_SYMBOLS = 1000 def initialize(self, broker_name, user_id, auth_data=None): # Implementation pass def connect(self): # Implementation pass def subscribe(self, symbol, exchange, mode=2, depth_level=5): # Implementation pass sun-brightdesktopmoon --- # 48 - Password Reset | Documentation ### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#overview) Overview OpenAlgo provides a secure multi-step password reset flow that supports both email-based reset tokens and TOTP verification for accounts with 2FA enabled. ### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#architecture-diagram) Architecture Diagram Copy ┌──────────────────────────────────────────────────────────────────────────────┐ │ Password Reset Architecture │ └──────────────────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────────────────┐ │ Step 1: Initiate Reset │ │ /forgot-password │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ User enters email address │ │ │ │ │ │ │ │ Email: [[email protected] ] │ │ │ │ │ │ │ │ [Send Reset Link] │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ Validate email exists │ │ │ │ │ ┌─────────────────────┴─────────────────────┐ │ │ │ │ │ │ Email Found Not Found │ │ │ │ │ │ ▼ ▼ │ │ Generate reset token Show generic message │ │ Store in database (prevent enumeration) │ │ Send email with link │ └─────────────────────────────────────────────────────────────────────────────┘ │ │ User clicks email link │ ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ │ Step 2: Verify Identity │ │ /reset-password?token=xxx │ │ │ │ Validate reset token │ │ │ │ │ ┌─────────────────────┴─────────────────────┐ │ │ │ │ │ │ Token Valid Token Invalid/Expired │ │ │ │ │ │ ▼ ▼ │ │ Check if TOTP enabled Show error message │ │ │ │ │ ┌─────────┴─────────┐ │ │ │ │ │ │ TOTP Enabled No TOTP │ │ │ │ │ │ ▼ ▼ │ │ Show TOTP Form Show Password Form │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ │ │ After verification │ ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ │ Step 3: Set New Password │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ New Password: [•••••••••••••••• ] │ │ │ │ Confirm Password: [•••••••••••••••• ] │ │ │ │ │ │ │ │ Requirements: │ │ │ │ ✓ At least 8 characters │ │ │ │ ✓ Contains uppercase letter │ │ │ │ ✓ Contains lowercase letter │ │ │ │ ✓ Contains number │ │ │ │ ✓ Contains special character │ │ │ │ │ │ │ │ [Reset Password] │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ Hash password with Argon2 + pepper │ │ Update user record │ │ Invalidate reset token │ │ Invalidate all sessions │ │ Redirect to login │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ ### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#database-schema) Database Schema #### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#password_reset_tokens-table) password\_reset\_tokens Table ### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#token-generation) Token Generation #### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#secure-token-creation) Secure Token Creation #### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#token-validation) Token Validation ### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#password-security) Password Security #### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#argon2-hashing-with-pepper) Argon2 Hashing with Pepper #### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#password-requirements) Password Requirements ### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#totp-integration) TOTP Integration #### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#reset-with-2fa) Reset with 2FA ### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#api-endpoints) API Endpoints #### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#request-reset) Request Reset **Response:** #### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#validate-token) Validate Token **Response:** #### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#reset-password) Reset Password **Response:** ### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#reset-flow-implementation) Reset Flow Implementation #### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#full-reset-service) Full Reset Service ### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#security-measures) Security Measures #### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#rate-limiting) Rate Limiting #### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#audit-logging) Audit Logging #### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#token-security) Token Security Measure Implementation Token entropy 256 bits (secrets.token\_urlsafe(32)) Token storage SHA-256 hash only Expiration 1 hour Single use Marked used after completion IP logging Request IP recorded ### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#frontend-components) Frontend Components #### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#forgot-password-form) Forgot Password Form #### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#reset-password-form) Reset Password Form ### [hashtag](https://docs.openalgo.in/developers/design-documentation/48-password-reset#key-files-reference) Key Files Reference File Purpose `blueprints/auth.py` Reset endpoints and core logic `database/user_db.py` User model with password hash `utils/email_utils.py` Password reset email sending `database/settings_db.py` SMTP settings for email `frontend/src/pages/ForgotPassword.tsx` Request form `frontend/src/pages/ResetPassword.tsx` Reset form > **Note**: Password reset logic is implemented directly in `blueprints/auth.py`. There are no separate `password_reset_db.py` or `password_reset_service.py` files. Reset tokens are stored in the session rather than a dedicated database table. [Previous47 - SMTP Configurationchevron-left](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration) [Next49 - Themeschevron-right](https://docs.openalgo.in/developers/design-documentation/49-themes) Last updated 1 month ago * [Overview](https://docs.openalgo.in/developers/design-documentation/48-password-reset#overview) * [Architecture Diagram](https://docs.openalgo.in/developers/design-documentation/48-password-reset#architecture-diagram) * [Database Schema](https://docs.openalgo.in/developers/design-documentation/48-password-reset#database-schema) * [Token Generation](https://docs.openalgo.in/developers/design-documentation/48-password-reset#token-generation) * [Password Security](https://docs.openalgo.in/developers/design-documentation/48-password-reset#password-security) * [TOTP Integration](https://docs.openalgo.in/developers/design-documentation/48-password-reset#totp-integration) * [API Endpoints](https://docs.openalgo.in/developers/design-documentation/48-password-reset#api-endpoints) * [Reset Flow Implementation](https://docs.openalgo.in/developers/design-documentation/48-password-reset#reset-flow-implementation) * [Security Measures](https://docs.openalgo.in/developers/design-documentation/48-password-reset#security-measures) * [Frontend Components](https://docs.openalgo.in/developers/design-documentation/48-password-reset#frontend-components) * [Key Files Reference](https://docs.openalgo.in/developers/design-documentation/48-password-reset#key-files-reference) sun-brightdesktopmoon Copy ┌────────────────────────────────────────────────────────────────┐ │ password_reset_tokens table │ ├──────────────────┬──────────────┬──────────────────────────────┤ │ Column │ Type │ Description │ ├──────────────────┼──────────────┼──────────────────────────────┤ │ id │ INTEGER PK │ Auto-increment │ │ user_id │ VARCHAR(255) │ User ID reference │ │ token_hash │ VARCHAR(255) │ SHA-256 hash of token │ │ created_at │ DATETIME │ Token creation time │ │ expires_at │ DATETIME │ Expiration (1 hour) │ │ used_at │ DATETIME │ When token was used │ │ ip_address │ VARCHAR(50) │ Requester IP │ │ user_agent │ TEXT │ Browser user agent │ └──────────────────┴──────────────┴──────────────────────────────┘ Copy import secrets import hashlib from datetime import datetime, timedelta def generate_reset_token(user_id, ip_address, user_agent): """Generate secure password reset token""" # Generate cryptographically secure token token = secrets.token_urlsafe(32) # 256 bits of entropy # Hash token for storage (never store plaintext) token_hash = hashlib.sha256(token.encode()).hexdigest() # Create database record reset_record = PasswordResetToken( user_id=user_id, token_hash=token_hash, created_at=datetime.utcnow(), expires_at=datetime.utcnow() + timedelta(hours=1), ip_address=ip_address, user_agent=user_agent ) db.session.add(reset_record) db.session.commit() # Return plaintext token (sent to user) return token Copy def validate_reset_token(token): """Validate password reset token""" # Hash provided token token_hash = hashlib.sha256(token.encode()).hexdigest() # Find matching record record = PasswordResetToken.query.filter_by( token_hash=token_hash, used_at=None ).first() if not record: return None, "Invalid token" # Check expiration if datetime.utcnow() > record.expires_at: return None, "Token expired" return record, None Copy from argon2 import PasswordHasher import os def hash_password(password): """Hash password with Argon2 and pepper""" pepper = os.environ.get('API_KEY_PEPPER') peppered_password = password + pepper ph = PasswordHasher( time_cost=2, # 2 iterations memory_cost=65536, # 64 MB parallelism=1, # 1 thread hash_len=32, # 32 byte hash salt_len=16 # 16 byte salt ) return ph.hash(peppered_password) def verify_password(stored_hash, password): """Verify password against stored hash""" pepper = os.environ.get('API_KEY_PEPPER') peppered_password = password + pepper ph = PasswordHasher() try: ph.verify(stored_hash, peppered_password) return True except: return False Copy import re def validate_password_strength(password): """Validate password meets security requirements""" errors = [] if len(password) < 8: errors.append("Password must be at least 8 characters") if not re.search(r'[A-Z]', password): errors.append("Password must contain an uppercase letter") if not re.search(r'[a-z]', password): errors.append("Password must contain a lowercase letter") if not re.search(r'[0-9]', password): errors.append("Password must contain a number") if not re.search(r'[!@#$%^&*(),.?":{}|<>]', password): errors.append("Password must contain a special character") return len(errors) == 0, errors Copy def process_reset_with_totp(user_id, totp_code, new_password): """Process password reset for TOTP-enabled account""" user = User.query.get(user_id) # Verify TOTP code if not verify_totp(user.totp_secret, totp_code): return False, "Invalid TOTP code" # Validate password strength valid, errors = validate_password_strength(new_password) if not valid: return False, errors # Update password user.password_hash = hash_password(new_password) user.updated_at = datetime.utcnow() db.session.commit() # Invalidate all sessions invalidate_user_sessions(user_id) return True, "Password reset successful" Copy POST /api/auth/forgot-password Content-Type: application/json { "email": "[email protected]" } Copy { "status": "success", "message": "If an account exists with this email, a reset link has been sent." } Copy GET /api/auth/reset-password/validate?token=abc123 Copy { "status": "success", "data": { "valid": true, "totp_required": true, "email": "u***@example.com" } } Copy POST /api/auth/reset-password Content-Type: application/json { "token": "abc123...", "totp_code": "123456", // Optional, only if TOTP enabled "new_password": "NewSecurePass123!", "confirm_password": "NewSecurePass123!" } Copy { "status": "success", "message": "Password reset successful. Please login with your new password." } Copy def initiate_password_reset(email, ip_address, user_agent): """Initiate password reset process""" # Find user (don't reveal if exists) user = User.query.filter_by(email=email.lower()).first() if not user: # Log attempt but don't reveal logger.info(f"Reset requested for non-existent email: {email}") return True # Always return success # Rate limit: max 3 requests per hour recent_tokens = PasswordResetToken.query.filter( PasswordResetToken.user_id == user.id, PasswordResetToken.created_at > datetime.utcnow() - timedelta(hours=1) ).count() if recent_tokens >= 3: logger.warning(f"Rate limit exceeded for password reset: {email}") return True # Still return success to prevent enumeration # Generate and send token token = generate_reset_token(user.id, ip_address, user_agent) send_password_reset_email(email, token) return True def complete_password_reset(token, new_password, totp_code=None): """Complete password reset process""" # Validate token record, error = validate_reset_token(token) if error: return False, error user = User.query.get(record.user_id) # Check if TOTP required if user.totp_enabled: if not totp_code: return False, "TOTP code required" if not verify_totp(user.totp_secret, totp_code): return False, "Invalid TOTP code" # Validate password valid, errors = validate_password_strength(new_password) if not valid: return False, errors # Check password not same as current if verify_password(user.password_hash, new_password): return False, "New password must be different from current password" # Update password user.password_hash = hash_password(new_password) user.updated_at = datetime.utcnow() # Mark token as used record.used_at = datetime.utcnow() db.session.commit() # Invalidate all sessions invalidate_user_sessions(user.id) # Send confirmation email send_password_changed_email(user.email) return True, "Password reset successful" Copy ┌────────────────────────────────────────────────────────────────────────────┐ │ Rate Limiting Rules │ │ │ │ Per Email: │ │ • Max 3 reset requests per hour │ │ • Max 10 reset requests per day │ │ │ │ Per IP Address: │ │ • Max 10 reset requests per hour │ │ • Max 50 reset requests per day │ │ │ │ Global: │ │ • Max 100 reset requests per minute │ │ │ └────────────────────────────────────────────────────────────────────────────┘ Copy def log_password_reset_event(user_id, event_type, ip_address, success): """Log password reset events for security audit""" AuditLog.create( user_id=user_id, event_type=f"password_reset_{event_type}", ip_address=ip_address, success=success, timestamp=datetime.utcnow() ) Copy function ForgotPasswordForm() { const [email, setEmail] = useState(''); const [submitted, setSubmitted] = useState(false); const handleSubmit = async (e: FormEvent) => { e.preventDefault(); await api.requestPasswordReset(email); setSubmitted(true); }; if (submitted) { return (

Check Your Email

If an account exists with {email}, you'll receive a reset link.

); } return (
setEmail(e.target.value)} placeholder="Enter your email" required />
); } Copy function ResetPasswordForm({ token }: { token: string }) { const [password, setPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const [totpCode, setTotpCode] = useState(''); const [totpRequired, setTotpRequired] = useState(false); // Validate token on mount useEffect(() => { api.validateResetToken(token) .then(data => setTotpRequired(data.totp_required)) .catch(() => navigate('/forgot-password')); }, [token]); const handleSubmit = async (e: FormEvent) => { e.preventDefault(); if (password !== confirmPassword) { toast.error('Passwords do not match'); return; } await api.resetPassword({ token, new_password: password, confirm_password: confirmPassword, totp_code: totpRequired ? totpCode : undefined }); toast.success('Password reset successful'); navigate('/login'); }; return (
{totpRequired && ( setTotpCode(e.target.value)} placeholder="Enter TOTP code" maxLength={6} /> )} ); } sun-brightdesktopmoon --- # 47 - SMTP Configuration | Documentation ### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#overview) Overview OpenAlgo uses SMTP for sending email notifications, password reset links, and alerts. SMTP credentials are stored encrypted in the database for security. ### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#architecture-diagram) Architecture Diagram Copy ┌──────────────────────────────────────────────────────────────────────────────┐ │ SMTP Configuration Architecture │ └──────────────────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────────────────┐ │ Admin Configuration │ │ /settings/smtp │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ SMTP Settings Form │ │ │ │ │ │ │ │ SMTP Server: [smtp.gmail.com ] │ │ │ │ Port: [587 ] │ │ │ │ Username: [[email protected] ] │ │ │ │ Password: [•••••••••••• ] │ │ │ │ From Email: [[email protected] ] │ │ │ │ Use TLS: [✓] Enabled │ │ │ │ │ │ │ │ [Test Connection] [Save Settings] │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ └─────────────────────────────────────────────────────────────────────────────┘ │ │ Save with Encryption │ ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ │ Database Storage │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ smtp_config table │ │ │ │ │ │ │ │ id │ smtp_server │ smtp_port │ username │ password_enc │ ... │ │ │ │ ───────────────────────────────────────────────────────────────── │ │ │ │ 1 │ smtp.gmail │ 587 │ user@... │ gAAAAB... │ │ │ │ │ (Fernet encrypted) │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────────────┘ │ │ When Email Needed │ ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ │ Email Sending Service │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ 1. Load SMTP config from database │ │ │ │ 2. Decrypt password using Fernet │ │ │ │ 3. Connect to SMTP server │ │ │ │ 4. Send email with TLS │ │ │ │ 5. Log result │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ SMTP Server │ │ │ │ (Gmail, SendGrid, etc.) │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ Email Delivered │ │ to Recipient │ └─────────────────────────────────────────────────────────────────────────────┘ ### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#database-schema) Database Schema #### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#smtp_config-table) smtp\_config Table ### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#password-encryption) Password Encryption #### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#fernet-encryption) Fernet Encryption #### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#key-derivation) Key Derivation ### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#email-service) Email Service #### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#configuration-loading) Configuration Loading #### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#send-email-function) Send Email Function #### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#test-connection) Test Connection ### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#api-endpoints) API Endpoints #### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#save-configuration) Save Configuration **Response:** #### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#test-configuration) Test Configuration **Response:** #### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#get-configuration-masked) Get Configuration (Masked) **Response:** ### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#common-smtp-providers) Common SMTP Providers #### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#gmail) Gmail #### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#sendgrid) SendGrid #### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#amazon-ses) Amazon SES ### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#email-templates) Email Templates #### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#password-reset-email) Password Reset Email #### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#order-notification-email) Order Notification Email ### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#security-considerations) Security Considerations #### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#password-storage) Password Storage #### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#best-practices) Best Practices Practice Implementation Use App Passwords Gmail requires app-specific passwords Enable TLS Always use STARTTLS on port 587 Rate Limiting Limit emails per minute Error Masking Don't expose SMTP errors to users Audit Logging Log all email attempts (without content) ### [hashtag](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#key-files-reference) Key Files Reference File Purpose `database/smtp_db.py` SMTP configuration model `services/email_service.py` Email sending logic `utils/encryption_utils.py` Fernet encryption helpers `blueprints/settings.py` SMTP configuration routes `frontend/src/pages/SmtpSettings.tsx` Configuration UI [Previous46 - Searchchevron-left](https://docs.openalgo.in/developers/design-documentation/46-search) [Next48 - Password Resetchevron-right](https://docs.openalgo.in/developers/design-documentation/48-password-reset) Last updated 1 month ago * [Overview](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#overview) * [Architecture Diagram](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#architecture-diagram) * [Database Schema](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#database-schema) * [Password Encryption](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#password-encryption) * [Email Service](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#email-service) * [API Endpoints](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#api-endpoints) * [Common SMTP Providers](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#common-smtp-providers) * [Email Templates](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#email-templates) * [Security Considerations](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#security-considerations) * [Key Files Reference](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration#key-files-reference) sun-brightdesktopmoon Copy ┌────────────────────────────────────────────────────────────────┐ │ smtp_config table │ ├──────────────────┬──────────────┬──────────────────────────────┤ │ Column │ Type │ Description │ ├──────────────────┼──────────────┼──────────────────────────────┤ │ id │ INTEGER PK │ Auto-increment │ │ smtp_server │ VARCHAR(255) │ SMTP server hostname │ │ smtp_port │ INTEGER │ SMTP port (25/465/587) │ │ smtp_username │ VARCHAR(255) │ Authentication username │ │ smtp_password │ TEXT │ Fernet-encrypted password │ │ from_email │ VARCHAR(255) │ Sender email address │ │ from_name │ VARCHAR(255) │ Sender display name │ │ use_tls │ BOOLEAN │ Enable STARTTLS │ │ use_ssl │ BOOLEAN │ Enable SSL/TLS │ │ is_active │ BOOLEAN │ Configuration active │ │ created_at │ DATETIME │ When created │ │ updated_at │ DATETIME │ Last modified │ └──────────────────┴──────────────┴──────────────────────────────┘ Copy from cryptography.fernet import Fernet from utils.env_utils import get_fernet_key def encrypt_smtp_password(password): """Encrypt SMTP password for storage""" key = get_fernet_key() # Derived from APP_KEY fernet = Fernet(key) return fernet.encrypt(password.encode()).decode() def decrypt_smtp_password(encrypted_password): """Decrypt SMTP password for use""" key = get_fernet_key() fernet = Fernet(key) return fernet.decrypt(encrypted_password.encode()).decode() Copy import hashlib import base64 def get_fernet_key(): """Derive Fernet key from APP_KEY""" app_key = os.environ.get('APP_KEY') if not app_key: raise ValueError("APP_KEY not configured") # Derive 32-byte key for Fernet key_bytes = hashlib.sha256(app_key.encode()).digest() return base64.urlsafe_b64encode(key_bytes) Copy def get_smtp_config(): """Load SMTP configuration""" config = SmtpConfig.query.filter_by(is_active=True).first() if not config: return None return { 'server': config.smtp_server, 'port': config.smtp_port, 'username': config.smtp_username, 'password': decrypt_smtp_password(config.smtp_password), 'from_email': config.from_email, 'from_name': config.from_name, 'use_tls': config.use_tls, 'use_ssl': config.use_ssl } Copy import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart def send_email(to_email, subject, body, html_body=None): """Send email via SMTP""" config = get_smtp_config() if not config: logger.error("SMTP not configured") return False try: # Create message msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = f"{config['from_name']} <{config['from_email']}>" msg['To'] = to_email # Attach text and HTML parts msg.attach(MIMEText(body, 'plain')) if html_body: msg.attach(MIMEText(html_body, 'html')) # Connect and send if config['use_ssl']: server = smtplib.SMTP_SSL(config['server'], config['port']) else: server = smtplib.SMTP(config['server'], config['port']) if config['use_tls']: server.starttls() server.login(config['username'], config['password']) server.sendmail(config['from_email'], to_email, msg.as_string()) server.quit() logger.info(f"Email sent to {to_email}") return True except Exception as e: logger.error(f"Failed to send email: {e}") return False Copy def test_smtp_connection(): """Test SMTP configuration""" config = get_smtp_config() if not config: return False, "SMTP not configured" try: if config['use_ssl']: server = smtplib.SMTP_SSL(config['server'], config['port'], timeout=10) else: server = smtplib.SMTP(config['server'], config['port'], timeout=10) if config['use_tls']: server.starttls() server.login(config['username'], config['password']) server.quit() return True, "Connection successful" except smtplib.SMTPAuthenticationError: return False, "Authentication failed" except smtplib.SMTPConnectError: return False, "Could not connect to server" except Exception as e: return False, str(e) Copy POST /api/settings/smtp Content-Type: application/json Authorization: Bearer ADMIN_TOKEN { "smtp_server": "smtp.gmail.com", "smtp_port": 587, "smtp_username": "[email protected]", "smtp_password": "app_password", "from_email": "[email protected]", "from_name": "OpenAlgo", "use_tls": true, "use_ssl": false } Copy { "status": "success", "message": "SMTP configuration saved" } Copy POST /api/settings/smtp/test Authorization: Bearer ADMIN_TOKEN Copy { "status": "success", "message": "Connection successful" } Copy GET /api/settings/smtp Authorization: Bearer ADMIN_TOKEN Copy { "status": "success", "data": { "smtp_server": "smtp.gmail.com", "smtp_port": 587, "smtp_username": "[email protected]", "smtp_password": "••••••••", "from_email": "[email protected]", "use_tls": true } } Copy GMAIL_CONFIG = { 'smtp_server': 'smtp.gmail.com', 'smtp_port': 587, 'use_tls': True, 'use_ssl': False # Note: Requires App Password with 2FA enabled } Copy SENDGRID_CONFIG = { 'smtp_server': 'smtp.sendgrid.net', 'smtp_port': 587, 'use_tls': True, 'use_ssl': False # Username: 'apikey' # Password: Your SendGrid API key } Copy SES_CONFIG = { 'smtp_server': 'email-smtp.{region}.amazonaws.com', 'smtp_port': 587, 'use_tls': True, 'use_ssl': False } Copy def send_password_reset_email(user_email, reset_token): """Send password reset email""" reset_url = f"{get_base_url()}/reset-password?token={reset_token}" subject = "Reset Your OpenAlgo Password" body = f""" Hello, You requested to reset your OpenAlgo password. Click the link below to reset your password: {reset_url} This link expires in 1 hour. If you didn't request this, please ignore this email. Best regards, OpenAlgo Team """ html_body = f"""

Reset Your Password

You requested to reset your OpenAlgo password.

Reset Password

This link expires in 1 hour.

If you didn't request this, please ignore this email.

""" return send_email(user_email, subject, body, html_body) Copy def send_order_notification(user_email, order_details): """Send order execution notification""" subject = f"Order Executed: {order_details['action']} {order_details['symbol']}" body = f""" Order Executed Symbol: {order_details['symbol']} Action: {order_details['action']} Quantity: {order_details['quantity']} Price: ₹{order_details['price']} Order ID: {order_details['order_id']} Time: {order_details['time']} """ return send_email(user_email, subject, body) Copy ┌────────────────────────────────────────────────────────────────────────────┐ │ SMTP Password Security │ │ │ │ 1. Password entered in admin UI │ │ │ │ │ ▼ │ │ 2. Encrypted with Fernet (AES-128-CBC) │ │ Key derived from APP_KEY via SHA-256 │ │ │ │ │ ▼ │ │ 3. Stored as encrypted blob in database │ │ gAAAAABh... (base64 encoded) │ │ │ │ │ ▼ │ │ 4. Decrypted only when needed to send email │ │ Password never logged or displayed │ │ │ └────────────────────────────────────────────────────────────────────────────┘ sun-brightdesktopmoon --- # 44 - PnL Tracker | Documentation ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#overview) Overview The PnL (Profit & Loss) Tracker provides real-time intraday P&L monitoring by combining tradebook data with historical price data. It calculates mark-to-market (MTM) P&L for all positions throughout the trading day and displays it via interactive charts. ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#architecture-diagram) Architecture Diagram Copy ┌──────────────────────────────────────────────────────────────────────────────┐ │ PnL Tracker Architecture │ └──────────────────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────────────────┐ │ Data Sources │ │ │ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ │ │ Tradebook │ │ Position Book │ │ History API │ │ │ │ (Broker API) │ │ (Broker API) │ │ (1-minute bars)│ │ │ └────────┬────────┘ └────────┬────────┘ └────────┬────────┘ │ │ │ │ │ │ │ └────────────────────┼────────────────────┘ │ │ │ │ │ ▼ │ └─────────────────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ │ PnL Calculation (blueprints/pnltracker.py) │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ Position Window Tracking │ │ │ │ │ │ │ │ 1. Parse trades from tradebook │ │ │ │ 2. Group by symbol/exchange │ │ │ │ 3. Create position windows (start_time, end_time, qty, price) │ │ │ │ 4. Apply rate limiting (2 calls/sec for history API) │ │ │ │ 5. Calculate MTM using historical close prices │ │ │ │ 6. Aggregate all symbols into portfolio P&L │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ P&L Calculation Formula │ │ │ │ │ │ │ │ For LONG positions: │ │ │ │ MTM P&L = (Current Price - Entry Price) × Quantity │ │ │ │ │ │ │ │ For SHORT positions: │ │ │ │ MTM P&L = (Entry Price - Current Price) × Quantity │ │ │ │ │ │ │ │ Realized P&L = (Exit Price - Entry Price) × Quantity [Long] │ │ │ │ = (Entry Price - Exit Price) × Quantity [Short] │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ │ Frontend Display │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ Metrics Cards │ │ │ │ │ │ │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ │ │ │ Current │ │ Max │ │ Min │ │ Max │ │ │ │ │ │ MTM │ │ MTM │ │ MTM │ │ Drawdown │ │ │ │ │ │ +₹3,750 │ │ +₹4,200 │ │ +₹1,000 │ │ -₹800 │ │ │ │ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ P&L Chart (LightWeight Charts) │ │ │ │ │ │ │ │ ₹ │ │ │ │ 4000│ ╭──────╮ │ │ │ │ 3000│ ╭───╯ ╰──╮ │ │ │ │ 2000│╭───╯ ╰────── │ │ │ │ 1000│ │ │ │ │ 0├────────────────────────────► Time │ │ │ │ 9:15 10:00 11:00 12:00 1:00 │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────────────┘ ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#implementation-details) Implementation Details #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#position-window-tracking) Position Window Tracking The PnL tracker creates "position windows" to track when positions were opened and closed: #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#trade-timestamp-parsing) Trade Timestamp Parsing The system handles multiple timestamp formats from different brokers: #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#rate-limiting) Rate Limiting Historical data API calls are rate-limited to avoid broker rate limits: #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#carry-forward-position-pnl-tracking) Carry-Forward Position PnL Tracking The PnL tracker handles carry-forward positions — positions opened on previous days that are still open today. This is critical for NRML/CNC positions that span multiple trading sessions. **Position Detection:** * Compares current positions (from positionbook) against today's trades * Positions with quantities but no matching entry trades are carry-forward * Historical data fetched from 9:15 AM to calculate intraday P&L movement **P&L Calculation for Carry-Forward:** * Uses previous day's close price as the reference * Tracks MTM from market open using 1-minute historical bars * Merges carry-forward PnL series with regular trade PnL series ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#api-endpoint) API Endpoint #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#get-p-and-l-data) Get P&L Data **Response:** #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#response-fields) Response Fields Field Type Description `current_mtm` number Current mark-to-market P&L `max_mtm` number Maximum P&L reached during the day `max_mtm_time` string Time when max P&L was reached (HH:MM) `min_mtm` number Minimum P&L during the day `min_mtm_time` string Time when min P&L was reached (HH:MM) `max_drawdown` number Largest drawdown from peak (negative) `pnl_series` array Time series data for P&L chart `drawdown_series` array Time series data for drawdown chart ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#calculation-flow) Calculation Flow ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#data-dependencies) Data Dependencies The PnL tracker relies on these services (no dedicated database): Service Purpose `services/tradebook_service.py` Get today's executed trades `services/positionbook_service.py` Get current positions `services/history_service.py` Get 1-minute historical bars `database/auth_db.py` Get user auth token and API key ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#frontend-components) Frontend Components #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#react-page) React Page **Location:** `frontend/src/pages/PnLTracker.tsx` The React frontend: * Polls `/pnltracker/api/pnl` periodically * Renders metrics cards (current MTM, max, min, drawdown) * Uses LightWeight Charts for interactive P&L visualization * Shows separate drawdown chart below main chart #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#legacy-jinja-template) Legacy Jinja Template **Location:** `templates/pnltracker.html` Available at `/pnltracker/legacy` for backwards compatibility. ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#edge-cases-handled) Edge Cases Handled #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#sub-minute-trades) Sub-Minute Trades When a position is opened and closed within the same minute (no historical data points): #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#pre-trade-period) Pre-Trade Period Zero P&L data is added from market open (9:15 AM IST) to first trade time for complete visualization. #### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#timezone-handling) Timezone Handling All timestamps are converted to IST (Asia/Kolkata) timezone: ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#drawdown-calculation) Drawdown Calculation ### [hashtag](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#key-files-reference) Key Files Reference File Purpose `blueprints/pnltracker.py` Blueprint with P&L calculation logic `services/tradebook_service.py` Fetches tradebook from broker `services/positionbook_service.py` Fetches current positions `services/history_service.py` Fetches historical price data `frontend/src/pages/PnLTracker.tsx` React UI component `templates/pnltracker.html` Legacy Jinja template [Previous44 - Toast Notifications Systemchevron-left](https://docs.openalgo.in/developers/design-documentation/44-toast-notifications-system) [Next46 - Searchchevron-right](https://docs.openalgo.in/developers/design-documentation/46-search) Last updated 1 month ago * [Overview](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#overview) * [Architecture Diagram](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#architecture-diagram) * [Implementation Details](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#implementation-details) * [API Endpoint](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#api-endpoint) * [Calculation Flow](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#calculation-flow) * [Data Dependencies](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#data-dependencies) * [Frontend Components](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#frontend-components) * [Edge Cases Handled](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#edge-cases-handled) * [Drawdown Calculation](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#drawdown-calculation) * [Key Files Reference](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker#key-files-reference) sun-brightdesktopmoon Copy # Data structure for each position window position_window = { "start_time": datetime, # When position was opened "end_time": datetime, # When position was closed (None if still open) "qty": float, # Position quantity "price": float, # Entry price "action": str, # "BUY" or "SELL" "exit_price": float # Exit price (None if still open) } Copy # Supported formats in parse_trade_timestamp(): formats = [\ "%d-%b-%Y %H:%M:%S", # AngelOne: "17-Dec-2025 10:54:03"\ "%H:%M:%S %d-%m-%Y", # Flattrade: "09:41:01 17-12-2025"\ "%d-%m-%Y %H:%M:%S", # "17-12-2025 09:41:01"\ "%Y-%m-%d %H:%M:%S", # ISO-like: "2025-12-17 10:30:00"\ "%Y-%m-%dT%H:%M:%S", # ISO: "2025-12-17T10:30:00"\ ] Copy class RateLimiter: """Thread-safe rate limiter for API calls""" def __init__(self, calls_per_second=2): self.calls_per_second = calls_per_second self.min_interval = 1.0 / calls_per_second self.last_call_time = 0 self.lock = threading.Lock() def wait(self): """Wait if necessary to respect rate limit""" with self.lock: current_time = time_module.time() elapsed = current_time - self.last_call_time if elapsed < self.min_interval: sleep_time = self.min_interval - elapsed time_module.sleep(sleep_time) self.last_call_time = time_module.time() # Global instance - 2 calls per second (conservative) history_rate_limiter = RateLimiter(calls_per_second=2) Copy # Carry-forward position handling: # 1. Detect open positions not in today's tradebook (no entry trade today) # 2. Fetch historical data from market open to track MTM # 3. Calculate P&L relative to previous close price # 4. Two cases handled: # Case 1: Open carry-forward position (still held, no today trades) # Case 2: Closed carry-forward position (exit-only trades today) Copy POST /pnltracker/api/pnl Content-Type: application/json Cookie: session=... Copy { "status": "success", "data": { "current_mtm": 3750.00, "max_mtm": 4200.00, "max_mtm_time": "11:30", "min_mtm": 1000.00, "min_mtm_time": "09:45", "max_drawdown": -800.00, "pnl_series": [\ {"time": 1706165700000, "value": 1000.00},\ {"time": 1706165760000, "value": 1500.00},\ {"time": 1706165820000, "value": 2200.00}\ ], "drawdown_series": [\ {"time": 1706165700000, "value": 0.00},\ {"time": 1706165760000, "value": -200.00},\ {"time": 1706165820000, "value": 0.00}\ ] } } Copy ┌─────────────────────────────────────────────────────────────────┐ │ P&L Calculation Flow │ └─────────────────────────────────────────────────────────────────┘ Request arrives at /pnltracker/api/pnl │ ▼ ┌─────────────────────────┐ │ Get broker from session │ └───────────┬─────────────┘ │ ▼ ┌─────────────────────────┐ ┌─────────────────────┐ │ Get tradebook via │────▶│ services/tradebook │ │ get_tradebook(api_key) │ │ _service.py │ └───────────┬─────────────┘ └─────────────────────┘ │ ▼ ┌─────────────────────────┐ ┌─────────────────────┐ │ Get positions via │────▶│ services/positionbook│ │ get_positionbook() │ │ _service.py │ └───────────┬─────────────┘ └─────────────────────┘ │ ▼ ┌─────────────────────────┐ │ Group trades by symbol │ │ Create position windows │ └───────────┬─────────────┘ │ ▼ ┌─────────────────────────┐ │ For each symbol: │ │ 1. Rate limit wait │ │ 2. Get 1m history │ │ 3. Calculate MTM │ │ 4. Track realized P&L │ └───────────┬─────────────┘ │ ▼ ┌─────────────────────────┐ │ Aggregate portfolio │ │ Calculate drawdown │ │ Return JSON response │ └─────────────────────────┘ Copy # Calculate realized PnL even without historical data if is_closed_position: if window["action"] == "BUY": realized = (window["exit_price"] - window["price"]) * window["qty"] else: # SELL realized = (window["price"] - window["exit_price"]) * window["qty"] Copy ist = pytz.timezone("Asia/Kolkata") if df["datetime"].dt.tz is None: df["datetime"] = df["datetime"].dt.tz_localize("UTC").dt.tz_convert(ist) Copy # Drawdown = Current P&L - Peak P&L (running maximum) portfolio_pnl["Peak"] = portfolio_pnl["Total_PnL"].cummax() portfolio_pnl["Drawdown"] = portfolio_pnl["Total_PnL"] - portfolio_pnl["Peak"] # Max drawdown is the minimum value (most negative) max_drawdown = portfolio_pnl["Drawdown"].min() sun-brightdesktopmoon --- # 46 - Search | Documentation ### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#overview) Overview OpenAlgo provides fast symbol search across equity, futures, and options instruments. The search system uses an in-memory cache with database fallback for optimal performance. ### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#architecture-diagram) Architecture Diagram Copy ┌──────────────────────────────────────────────────────────────────────────────┐ │ Search Architecture │ └──────────────────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────────────────┐ │ Search Request │ │ │ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ │ │ React UI │ │ REST API │ │ MCP Tools │ │ │ │ /search │ │ /api/search │ │ search_inst │ │ │ └────────┬────────┘ └────────┬────────┘ └────────┬────────┘ │ │ │ │ │ │ │ └────────────────────┼────────────────────┘ │ │ │ │ │ Search Service │ │ │ │ └────────────────────────────────┼────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ │ BrokerSymbolCache (Singleton) │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ In-Memory Data Structures │ │ │ │ │ │ │ │ symbols_list[] - All symbols for iteration │ │ │ │ symbol_index{} - symbol → data (O(1) lookup) │ │ │ │ exchange_index{} - exchange → [symbols] (filtered search) │ │ │ │ type_index{} - instrument_type → [symbols] │ │ │ │ expiry_index{} - underlying → [expiry_dates] │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ┌───────────────┴───────────────┐ │ │ │ │ │ │ Cache Hit Cache Miss │ │ │ │ │ │ ▼ ▼ │ │ Return from memory Query database │ │ (microseconds) (milliseconds) │ │ │ │ │ ▼ │ │ Update cache │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ ### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#cache-architecture) Cache Architecture #### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#singleton-pattern) Singleton Pattern #### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#index-structures) Index Structures ### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#search-types) Search Types #### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#basic-symbol-search) Basic Symbol Search #### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#fno-search-with-filters) FNO Search with Filters #### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#exact-lookup-o-1) Exact Lookup (O(1)) ### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#database-fallback) Database Fallback ### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#cache-loading) Cache Loading #### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#initial-load) Initial Load #### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#cache-refresh) Cache Refresh ### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#api-endpoints) API Endpoints #### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#search-symbols) Search Symbols **Response:** #### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#search-f-and-o) Search F&O **Response:** #### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#get-expiries) Get Expiries **Response:** ### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#frontend-integration) Frontend Integration #### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#search-component) Search Component #### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#f-and-o-filter-component) F&O Filter Component ### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#performance-characteristics) Performance Characteristics Operation Time Complexity Notes Exact lookup O(1) Hash map access Prefix search O(n) Linear scan with filter Exchange filter O(k) k = symbols in exchange F&O filter O(k × m) k = candidates, m = filters Cache load O(n) n = total symbols ### [hashtag](https://docs.openalgo.in/developers/design-documentation/46-search#key-files-reference) Key Files Reference File Purpose `services/search_service.py` Search logic and cache `database/token_db.py` Symbol database queries `restx_api/search.py` Search API endpoints `frontend/src/components/SymbolSearch.tsx` Search UI component `frontend/src/pages/FnOChain.tsx` F&O search interface [Previous44 - PnL Trackerchevron-left](https://docs.openalgo.in/developers/design-documentation/44-pnl-tracker) [Next47 - SMTP Configurationchevron-right](https://docs.openalgo.in/developers/design-documentation/47-smtp-configuration) Last updated 1 month ago * [Overview](https://docs.openalgo.in/developers/design-documentation/46-search#overview) * [Architecture Diagram](https://docs.openalgo.in/developers/design-documentation/46-search#architecture-diagram) * [Cache Architecture](https://docs.openalgo.in/developers/design-documentation/46-search#cache-architecture) * [Search Types](https://docs.openalgo.in/developers/design-documentation/46-search#search-types) * [Database Fallback](https://docs.openalgo.in/developers/design-documentation/46-search#database-fallback) * [Cache Loading](https://docs.openalgo.in/developers/design-documentation/46-search#cache-loading) * [API Endpoints](https://docs.openalgo.in/developers/design-documentation/46-search#api-endpoints) * [Frontend Integration](https://docs.openalgo.in/developers/design-documentation/46-search#frontend-integration) * [Performance Characteristics](https://docs.openalgo.in/developers/design-documentation/46-search#performance-characteristics) * [Key Files Reference](https://docs.openalgo.in/developers/design-documentation/46-search#key-files-reference) sun-brightdesktopmoon Copy class BrokerSymbolCache: """Singleton cache for broker symbols""" _instance = None _lock = threading.Lock() def __new__(cls): if cls._instance is None: with cls._lock: if cls._instance is None: cls._instance = super().__new__(cls) cls._instance._initialized = False return cls._instance def __init__(self): if self._initialized: return self.symbols_list = [] self.symbol_index = {} # symbol:exchange → data self.exchange_index = {} # exchange → [symbols] self.type_index = {} # type → [symbols] self.expiry_index = {} # underlying → [expiries] self._initialized = True Copy ┌────────────────────────────────────────────────────────────────────────────┐ │ Index Data Structures │ │ │ │ symbol_index (Hash Map) │ │ ───────────────────────────────────────── │ │ "SBIN:NSE" → {symbol, exchange, token, lotsize, ...} │ │ "NIFTY:NFO" → {symbol, exchange, token, lotsize, expiry, ...} │ │ "RELIANCE:NSE" → {symbol, exchange, token, lotsize, ...} │ │ │ │ exchange_index (Inverted Index) │ │ ───────────────────────────────────────── │ │ "NSE" → ["SBIN", "RELIANCE", "INFY", ...] │ │ "NFO" → ["NIFTY25JAN21500CE", "BANKNIFTY25JAN48000PE", ...] │ │ "MCX" → ["CRUDEOIL", "GOLD", "SILVER", ...] │ │ │ │ type_index (Inverted Index) │ │ ───────────────────────────────────────── │ │ "EQ" → ["SBIN", "RELIANCE", ...] │ │ "FUTIDX" → ["NIFTY25JANFUT", "BANKNIFTY25JANFUT", ...] │ │ "OPTIDX" → ["NIFTY25JAN21500CE", "NIFTY25JAN21500PE", ...] │ │ │ │ expiry_index (Grouped Index) │ │ ───────────────────────────────────────── │ │ "NIFTY" → ["30JAN25", "06FEB25", "27FEB25", ...] │ │ "BANKNIFTY" → ["29JAN25", "05FEB25", "26FEB25", ...] │ │ │ └────────────────────────────────────────────────────────────────────────────┘ Copy def search_symbols(query, exchange=None, limit=50): """Search symbols by partial match""" cache = BrokerSymbolCache() query = query.upper() results = [] # Filter by exchange if specified if exchange: candidates = cache.exchange_index.get(exchange, []) else: candidates = cache.symbols_list # Partial match search for symbol in candidates: if query in symbol: data = cache.symbol_index.get(f"{symbol}:{exchange or 'NSE'}") if data: results.append(data) if len(results) >= limit: break return results Copy def search_fno( underlying, exchange="NFO", instrument_type=None, expiry=None, strike_from=None, strike_to=None, option_type=None ): """Search F&O instruments with filters""" cache = BrokerSymbolCache() results = [] # Get all symbols for underlying candidates = [\ s for s in cache.exchange_index.get(exchange, [])\ if s.startswith(underlying)\ ] for symbol in candidates: data = cache.symbol_index.get(f"{symbol}:{exchange}") if not data: continue # Apply filters if instrument_type and data.get('instrument_type') != instrument_type: continue if expiry and data.get('expiry') != expiry: continue if strike_from and data.get('strike', 0) < strike_from: continue if strike_to and data.get('strike', 0) > strike_to: continue if option_type and data.get('option_type') != option_type: continue results.append(data) return results Copy def get_symbol(symbol, exchange): """Get exact symbol data - O(1) lookup""" cache = BrokerSymbolCache() key = f"{symbol}:{exchange}" return cache.symbol_index.get(key) Copy def search_with_fallback(query, exchange=None): """Search with database fallback""" # Try cache first cache = BrokerSymbolCache() if cache.is_loaded: return search_symbols(query, exchange) # Fallback to database from database.token_db import SymToken filters = [SymToken.symbol.ilike(f"%{query}%")] if exchange: filters.append(SymToken.exchange == exchange) results = SymToken.query.filter(*filters).limit(50).all() return [\ {\ 'symbol': r.symbol,\ 'exchange': r.exchange,\ 'token': r.token,\ 'lotsize': r.lotsize\ }\ for r in results\ ] Copy def load_cache(broker): """Load all symbols into cache""" cache = BrokerSymbolCache() # Get all symbols from database from database.token_db import SymToken symbols = SymToken.query.all() for sym in symbols: data = { 'symbol': sym.symbol, 'brsymbol': sym.brsymbol, 'exchange': sym.exchange, 'token': sym.token, 'lotsize': sym.lotsize, 'tick_size': sym.tick_size, 'instrument_type': sym.instrument_type, 'expiry': sym.expiry, 'strike': sym.strike, 'option_type': sym.option_type } # Add to all indexes key = f"{sym.symbol}:{sym.exchange}" cache.symbol_index[key] = data cache.symbols_list.append(sym.symbol) # Exchange index if sym.exchange not in cache.exchange_index: cache.exchange_index[sym.exchange] = [] cache.exchange_index[sym.exchange].append(sym.symbol) # Type index if sym.instrument_type: if sym.instrument_type not in cache.type_index: cache.type_index[sym.instrument_type] = [] cache.type_index[sym.instrument_type].append(sym.symbol) # Expiry index (for F&O) if sym.expiry and hasattr(sym, 'underlying'): underlying = sym.underlying or sym.symbol[:5] if underlying not in cache.expiry_index: cache.expiry_index[underlying] = set() cache.expiry_index[underlying].add(sym.expiry) cache.is_loaded = True logger.info(f"Cache loaded: {len(cache.symbols_list)} symbols") Copy def refresh_cache(): """Refresh cache after master contract download""" cache = BrokerSymbolCache() # Clear existing data cache.symbols_list.clear() cache.symbol_index.clear() cache.exchange_index.clear() cache.type_index.clear() cache.expiry_index.clear() cache.is_loaded = False # Reload load_cache(get_active_broker()) Copy GET /api/v1/search?query=SBIN&exchange=NSE&limit=20 Authorization: Bearer YOUR_API_KEY Copy { "status": "success", "data": [\ {\ "symbol": "SBIN",\ "exchange": "NSE",\ "token": "779",\ "lotsize": 1,\ "instrument_type": "EQ"\ },\ {\ "symbol": "SBIN-EQ",\ "exchange": "NSE",\ "token": "779",\ "lotsize": 1,\ "instrument_type": "EQ"\ }\ ] } Copy GET /api/v1/search/fno?underlying=NIFTY&exchange=NFO&expiry=30JAN25&option_type=CE Authorization: Bearer YOUR_API_KEY Copy { "status": "success", "data": [\ {\ "symbol": "NIFTY25JAN21500CE",\ "exchange": "NFO",\ "token": "12345",\ "lotsize": 50,\ "strike": 21500,\ "option_type": "CE",\ "expiry": "30JAN25"\ }\ ] } Copy GET /api/v1/search/expiries?underlying=NIFTY&exchange=NFO Authorization: Bearer YOUR_API_KEY Copy { "status": "success", "data": ["30JAN25", "06FEB25", "27FEB25", "27MAR25"] } Copy function SymbolSearch() { const [query, setQuery] = useState(''); const [results, setResults] = useState([]); const debouncedQuery = useDebounce(query, 300); useEffect(() => { if (debouncedQuery.length >= 2) { api.searchSymbols(debouncedQuery) .then(data => setResults(data)) .catch(console.error); } else { setResults([]); } }, [debouncedQuery]); return (
setQuery(e.target.value)} placeholder="Search symbols..." className="input input-bordered w-full" /> {results.length > 0 && (
    {results.map((item) => (
  • onSelect(item)} > {item.symbol} {item.exchange}
  • ))}
)}
); } Copy function FnOSearch() { const [filters, setFilters] = useState({ underlying: 'NIFTY', exchange: 'NFO', expiry: '', optionType: '', strikeFrom: '', strikeTo: '' }); const { data: expiries } = useQuery({ queryKey: ['expiries', filters.underlying], queryFn: () => api.getExpiries(filters.underlying) }); const { data: results } = useQuery({ queryKey: ['fno-search', filters], queryFn: () => api.searchFnO(filters), enabled: !!filters.expiry }); return (
{/* Results table */}
); } sun-brightdesktopmoon --- # 42 - Action Center | Documentation ### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#overview) Overview The Action Center is a centralized order approval system for semi-automated trading. When enabled, orders are queued for manual approval before execution, essential for managed accounts and regulatory compliance (RA - Relationship Advisor mode). ### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#architecture-diagram) Architecture Diagram Copy ┌──────────────────────────────────────────────────────────────────────────────┐ │ Action Center Architecture │ └──────────────────────────────────────────────────────────────────────────────┘ External Order Request (TradingView, API, etc.) │ ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ │ Order Router Service │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ should_route_to_pending(api_key, api_type) │ │ │ │ │ │ │ │ Check 1: Is user in semi_auto mode? │ │ │ │ Check 2: Is this a restricted operation? │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ┌─────────────────────┴─────────────────────┐ │ │ │ │ │ │ Auto Mode Semi-Auto Mode │ │ or Restricted (Queue Order) │ │ │ │ │ │ ▼ ▼ │ │ Execute Immediately Create Pending Order │ │ with Broker in Action Center │ └─────────────────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ │ Action Center UI │ │ /action-center │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ [Pending (3)] [Approved] [Rejected] [All Orders] │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ Statistics │ │ │ │ Pending: 3 │ Buy: 2 │ Sell: 1 │ Approved: 15 │ Rejected: 2 │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ Strategy │ Symbol │ Exchange │ Action │ Qty │ Price │ Actions │ │ │ ├─────────────────────────────────────────────────────────────────────┤ │ │ │ MyStrat │ SBIN │ NSE │ BUY │ 100 │ MKT │ ✓ Approve │ │ │ │ │ │ │ │ │ │ ✗ Reject │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ [Approve All Pending] │ └─────────────────────────────────────────────────────────────────────────────┘ │ User clicks Approve │ ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ │ Pending Order Execution Service │ │ │ │ 1. Mark order status = 'approved' │ │ 2. Execute order with broker API │ │ 3. Get broker order status │ │ 4. Update broker_order_id and broker_status │ │ 5. Emit SocketIO event │ └─────────────────────────────────────────────────────────────────────────────┘ ### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#order-mode-configuration) Order Mode Configuration #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#setting-order-mode) Setting Order Mode #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#mode-toggle-api) Mode Toggle API ### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#semi-auto-workflow) Semi-Auto Workflow ### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#database-schema) Database Schema #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#pending_orders-table) pending\_orders Table #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#indexes) Indexes ### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#supported-order-types) Supported Order Types API Type Description placeorder Standard order smartorder Position-aware order basketorder Multiple orders splitorder Split large orders optionsorder Options contracts ### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#restricted-operations) Restricted Operations These operations ALWAYS execute immediately, even in semi-auto mode: Operation Reason closeposition Prevent stuck positions closeallpositions Emergency close cancelorder Order management cancelallorder Bulk cancel modifyorder Order adjustment orderstatus Status query orderbook Data retrieval tradebook Data retrieval positions Data retrieval holdings Data retrieval funds Data retrieval ### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#api-endpoints) API Endpoints #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#get-orders) Get Orders **Response:** #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#approve-order) Approve Order **Response:** #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#reject-order) Reject Order #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#approve-all) Approve All **Response:** #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#delete-order) Delete Order Note: Only approved or rejected orders can be deleted. #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#get-pending-count) Get Pending Count **Response:** ### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#real-time-updates) Real-Time Updates #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#socketio-events) SocketIO Events Event Trigger Data pending\_order\_created New order queued order\_id, user\_id pending\_order\_updated Approve/Reject order\_id, status #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#frontend-handling) Frontend Handling ### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#react-component-features) React Component Features #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#tabbed-interface) Tabbed Interface #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#statistics-dashboard) Statistics Dashboard #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#order-table-columns) Order Table Columns Column Content Strategy Strategy name Symbol Trading symbol Exchange NSE/NFO/MCX badge Action BUY (green) / SELL (red) Quantity Order quantity Price Price or "MARKET" Order Type placeorder/smartorder/etc Product CNC/MIS/NRML badge Created Relative time ("5 min ago") Actions Approve/Reject/Delete buttons #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#expandable-details) Expandable Details Click chevron to view raw order data: ### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#service-implementation) Service Implementation #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#order-router) Order Router #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#queue-order) Queue Order #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#execute-approved-order) Execute Approved Order ### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#security-and-compliance) Security & Compliance #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#audit-trail) Audit Trail All actions are logged with: * Timestamp (IST) * Username * Action taken * Reason (for rejections) #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#api-key-security) API Key Security * API keys never stored in pending\_orders * Only user\_id reference maintained * Keys retrieved at execution time #### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#analyzer-mode-restriction) Analyzer Mode Restriction When in semi\_auto mode, analyzer toggle is blocked to ensure RA compliance. ### [hashtag](https://docs.openalgo.in/developers/design-documentation/42-action-center#key-files-reference) Key Files Reference File Purpose `database/action_center_db.py` PendingOrder model `services/action_center_service.py` Order parsing, stats `services/order_router_service.py` Route decisions `services/pending_order_execution_service.py` Execute approved `blueprints/orders.py` Action center routes `blueprints/apikey.py` Mode toggle `frontend/src/pages/ActionCenter.tsx` React UI [Previous41 - MCP Architecturechevron-left](https://docs.openalgo.in/developers/design-documentation/41-mcp-architecture) [Next43 - Telegram Bot Configurationchevron-right](https://docs.openalgo.in/developers/design-documentation/43-telegram-bot-configuration) Last updated 1 month ago * [Overview](https://docs.openalgo.in/developers/design-documentation/42-action-center#overview) * [Architecture Diagram](https://docs.openalgo.in/developers/design-documentation/42-action-center#architecture-diagram) * [Order Mode Configuration](https://docs.openalgo.in/developers/design-documentation/42-action-center#order-mode-configuration) * [Semi-Auto Workflow](https://docs.openalgo.in/developers/design-documentation/42-action-center#semi-auto-workflow) * [Database Schema](https://docs.openalgo.in/developers/design-documentation/42-action-center#database-schema) * [Supported Order Types](https://docs.openalgo.in/developers/design-documentation/42-action-center#supported-order-types) * [Restricted Operations](https://docs.openalgo.in/developers/design-documentation/42-action-center#restricted-operations) * [API Endpoints](https://docs.openalgo.in/developers/design-documentation/42-action-center#api-endpoints) * [Real-Time Updates](https://docs.openalgo.in/developers/design-documentation/42-action-center#real-time-updates) * [React Component Features](https://docs.openalgo.in/developers/design-documentation/42-action-center#react-component-features) * [Service Implementation](https://docs.openalgo.in/developers/design-documentation/42-action-center#service-implementation) * [Security & Compliance](https://docs.openalgo.in/developers/design-documentation/42-action-center#security-and-compliance) * [Key Files Reference](https://docs.openalgo.in/developers/design-documentation/42-action-center#key-files-reference) sun-brightdesktopmoon Copy # Via API Key settings page order_mode = 'auto' # Direct execution (default) order_mode = 'semi_auto' # Queue for approval Copy POST /apikey/mode Content-Type: application/json {"mode": "semi_auto"} Copy ┌────────────────────────────────────────────────────────────────────────────┐ │ Semi-Auto Order Flow │ │ │ │ 1. Order Received ────────────────────────────────────────────────────► │ │ │ │ │ ▼ │ │ 2. Check Order Mode ──────────────────────────────────────────────────► │ │ │ │ │ │ semi_auto = True │ │ ▼ │ │ 3. Create Pending Order ──────────────────────────────────────────────► │ │ │ │ │ ├──► Store in pending_orders table │ │ │ │ │ ├──► Emit 'pending_order_created' SocketIO event │ │ │ │ │ └──► Return pending_order_id to caller │ │ │ │ │ ▼ │ │ 4. User Reviews in Action Center ─────────────────────────────────────► │ │ │ │ │ ├──────────────────┬──────────────────┐ │ │ │ │ │ │ │ Approve Reject Ignore │ │ │ │ │ │ │ ▼ ▼ ▼ │ │ 5a. Execute Order 5b. Mark Rejected 5c. Stays Pending │ │ with Broker Store reason │ │ │ │ │ │ ▼ ▼ │ │ 6. Update Broker Emit SocketIO │ │ Status Event │ │ │ └────────────────────────────────────────────────────────────────────────────┘ Copy ┌────────────────────────────────────────────────────────────────┐ │ pending_orders table │ ├──────────────────┬──────────────┬──────────────────────────────┤ │ Column │ Type │ Description │ ├──────────────────┼──────────────┼──────────────────────────────┤ │ id │ INTEGER PK │ Unique order identifier │ │ user_id │ VARCHAR(255) │ User who placed order │ │ api_type │ VARCHAR(50) │ Order type │ │ order_data │ TEXT │ JSON order details │ │ created_at │ DATETIME │ Creation time (UTC) │ │ created_at_ist │ VARCHAR(50) │ Creation time (IST) │ │ status │ VARCHAR(20) │ pending/approved/rejected │ │ approved_at │ DATETIME │ Approval time (UTC) │ │ approved_at_ist │ VARCHAR(50) │ Approval time (IST) │ │ approved_by │ VARCHAR(255) │ Approver username │ │ rejected_at │ DATETIME │ Rejection time (UTC) │ │ rejected_at_ist │ VARCHAR(50) │ Rejection time (IST) │ │ rejected_by │ VARCHAR(255) │ Rejector username │ │ rejected_reason │ TEXT │ Reason for rejection │ │ broker_order_id │ VARCHAR(255) │ Broker's order ID │ │ broker_status │ VARCHAR(20) │ complete/open/rejected │ └──────────────────┴──────────────┴──────────────────────────────┘ Copy CREATE INDEX idx_user_status ON pending_orders(user_id, status); CREATE INDEX idx_created_at ON pending_orders(created_at); Copy POST /action-center/api/data?status=pending Copy { "status": "success", "orders": [\ {\ "id": 1,\ "strategy": "MyStrategy",\ "symbol": "SBIN",\ "exchange": "NSE",\ "action": "BUY",\ "quantity": 100,\ "price": 0,\ "price_type": "MARKET",\ "product": "MIS",\ "order_type": "placeorder",\ "status": "pending",\ "created_at": "5 minutes ago"\ }\ ], "statistics": { "total_pending": 3, "total_approved": 15, "total_rejected": 2, "total_buy_orders": 10, "total_sell_orders": 10 } } Copy POST /action-center/approve/{order_id} Copy { "status": "success", "message": "Order approved and executed", "broker_order_id": "123456789" } Copy POST /action-center/reject/{order_id} Content-Type: application/json {"reason": "Invalid price level"} Copy POST /action-center/approve-all Copy { "status": "success", "approved": 5, "executed": 5, "failed": 0 } Copy DELETE /action-center/delete/{order_id} Copy GET /action-center/count Copy { "count": 3 } Copy // Listen for new orders socket.on('pending_order_created', () => { playAlertSound(); showToast('New order pending approval'); refreshOrders(); }); // Listen for status changes socket.on('pending_order_updated', () => { refreshOrders(); }); Copy [Pending (3)] [Approved] [Rejected] [All Orders] ↓ (pulse animation when pending > 0) Copy ┌─────────────────────────────────────────────────────────────────┐ │ Pending: 3 │ Buy: 2 │ Sell: 1 │ Approved: 15 │ │ (yellow) (green) (red) (green) │ └─────────────────────────────────────────────────────────────────┘ Copy ┌─────────────────────────────────────────────────────────────────┐ │ ▼ Order Details │ │ │ │ apikey: **** │ │ strategy: MyStrategy │ │ symbol: SBIN │ │ exchange: NSE │ │ action: BUY │ │ quantity: 100 │ │ pricetype: MARKET │ │ product: MIS │ └─────────────────────────────────────────────────────────────────┘ Copy def should_route_to_pending(api_key, api_type=None): """Check if order should be queued""" # Skip restricted operations if api_type in IMMEDIATE_EXECUTION_OPERATIONS: return False # Check user's order mode user_id = get_user_id_from_api_key(api_key) order_mode = get_order_mode(user_id) return order_mode == 'semi_auto' Copy def queue_order(api_key, order_data, api_type): """Queue order for approval""" user_id = get_user_id_from_api_key(api_key) pending_order_id = create_pending_order( user_id=user_id, api_type=api_type, order_data=order_data ) # Emit real-time event socketio.emit('pending_order_created', { 'order_id': pending_order_id, 'user_id': user_id }) return True, { 'status': 'success', 'message': 'Order queued for approval', 'mode': 'semi_auto', 'pending_order_id': pending_order_id }, 200 Copy def execute_approved_order(pending_order_id): """Execute approved order with broker""" order = get_pending_order_by_id(pending_order_id) # Route to appropriate service if order.api_type == 'placeorder': result = place_order(order.order_data, api_key) elif order.api_type == 'smartorder': result = place_smart_order(order.order_data, api_key) # ... other types # Update broker status update_broker_status( pending_order_id, result['orderid'], result['broker_status'] ) return result sun-brightdesktopmoon --- # 49 - Themes | Documentation ### [hashtag](https://docs.openalgo.in/developers/design-documentation/49-themes#overview) Overview OpenAlgo's React frontend supports theme customization with light/dark modes and 12 base colors. Theme preferences persist across sessions using Zustand with localStorage. The theme system also manages "App Mode" (live vs analyzer) with distinct visual states. ### [hashtag](https://docs.openalgo.in/developers/design-documentation/49-themes#architecture-diagram) Architecture Diagram Copy ┌──────────────────────────────────────────────────────────────────────────────┐ │ Theme Architecture │ └──────────────────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────────────────┐ │ Theme Configuration │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ Zustand Theme Store │ │ │ │ │ │ │ │ state: { │ │ │ │ mode: 'light' | 'dark', │ │ │ │ color: 'zinc' | 'blue' | 'green' | 'violet' | ... │ │ │ │ appMode: 'live' | 'analyzer', │ │ │ │ isTogglingMode: boolean │ │ │ │ } │ │ │ │ │ │ │ │ actions: { │ │ │ │ setMode(mode), │ │ │ │ setColor(color), │ │ │ │ setAppMode(appMode), │ │ │ │ toggleMode(), │ │ │ │ toggleAppMode(), // async - calls backend │ │ │ │ syncAppMode() // sync with backend state │ │ │ │ } │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ │ persist to localStorage │ │ │ │ │ ▼ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ localStorage │ │ │ │ │ │ │ │ openalgo-theme: { │ │ │ │ "state": { │ │ │ │ "theme": "dark", │ │ │ │ "accentColor": "blue" │ │ │ │ } │ │ │ │ } │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────────────┘ │ │ Apply to DOM │ ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ │ DOM Application │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ CSS Variables Applied │ │ │ │ │ │ │ │ --primary: hsl(217, 91%, 60%) /* Accent color */ │ │ │ │ --secondary: hsl(217, 33%, 17%) │ │ │ │ --accent: hsl(217, 91%, 70%) │ │ │ │ --base-100: hsl(0, 0%, 100%) /* Light mode */ │ │ │ │ --base-100: hsl(220, 13%, 18%) /* Dark mode */ │ │ │ │ --base-content: hsl(220, 13%, 69%) │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────────────┘ ### [hashtag](https://docs.openalgo.in/developers/design-documentation/49-themes#theme-store-implementation) Theme Store Implementation #### [hashtag](https://docs.openalgo.in/developers/design-documentation/49-themes#zustand-store) Zustand Store #### [hashtag](https://docs.openalgo.in/developers/design-documentation/49-themes#dom-application) DOM Application ### [hashtag](https://docs.openalgo.in/developers/design-documentation/49-themes#available-themes) Available Themes #### [hashtag](https://docs.openalgo.in/developers/design-documentation/49-themes#color-modes) Color Modes #### [hashtag](https://docs.openalgo.in/developers/design-documentation/49-themes#theme-colors-12-options) Theme Colors (12 options) Color Use Case Zinc Default neutral gray Slate Blue-gray neutral Stone Warm gray neutral Gray Pure gray Neutral Balanced neutral Red Errors, sell actions Rose Soft pink accent Orange Warnings, attention Green Success, growth Blue Professional, primary Yellow Caution, pending Violet Creative accent ### [hashtag](https://docs.openalgo.in/developers/design-documentation/49-themes#app-mode-live-vs-analyzer) App Mode (Live vs Analyzer) The theme store manages two distinct app modes with different visual states: #### [hashtag](https://docs.openalgo.in/developers/design-documentation/49-themes#implementation) Implementation ### [hashtag](https://docs.openalgo.in/developers/design-documentation/49-themes#theme-settings-ui) Theme Settings UI #### [hashtag](https://docs.openalgo.in/developers/design-documentation/49-themes#theme-toggle-component) Theme Toggle Component #### [hashtag](https://docs.openalgo.in/developers/design-documentation/49-themes#color-picker-component) Color Picker Component #### [hashtag](https://docs.openalgo.in/developers/design-documentation/49-themes#settings-page-section) Settings Page Section ### [hashtag](https://docs.openalgo.in/developers/design-documentation/49-themes#css-implementation) CSS Implementation #### [hashtag](https://docs.openalgo.in/developers/design-documentation/49-themes#daisyui-theme-configuration) DaisyUI Theme Configuration #### [hashtag](https://docs.openalgo.in/developers/design-documentation/49-themes#accent-color-css) Accent Color CSS ### [hashtag](https://docs.openalgo.in/developers/design-documentation/49-themes#system-preference-detection) System Preference Detection ### [hashtag](https://docs.openalgo.in/developers/design-documentation/49-themes#key-files-reference) Key Files Reference File Purpose `frontend/src/stores/themeStore.ts` Zustand theme store `frontend/src/components/ThemeToggle.tsx` Toggle button `frontend/src/components/AccentColorPicker.tsx` Color picker `frontend/src/styles/accent-colors.css` Accent CSS vars `frontend/tailwind.config.js` DaisyUI themes [Previous48 - Password Resetchevron-left](https://docs.openalgo.in/developers/design-documentation/48-password-reset) [Next50 - TOTP Configurationchevron-right](https://docs.openalgo.in/developers/design-documentation/50-totp-configuration) Last updated 1 month ago * [Overview](https://docs.openalgo.in/developers/design-documentation/49-themes#overview) * [Architecture Diagram](https://docs.openalgo.in/developers/design-documentation/49-themes#architecture-diagram) * [Theme Store Implementation](https://docs.openalgo.in/developers/design-documentation/49-themes#theme-store-implementation) * [Available Themes](https://docs.openalgo.in/developers/design-documentation/49-themes#available-themes) * [App Mode (Live vs Analyzer)](https://docs.openalgo.in/developers/design-documentation/49-themes#app-mode-live-vs-analyzer) * [Theme Settings UI](https://docs.openalgo.in/developers/design-documentation/49-themes#theme-settings-ui) * [CSS Implementation](https://docs.openalgo.in/developers/design-documentation/49-themes#css-implementation) * [System Preference Detection](https://docs.openalgo.in/developers/design-documentation/49-themes#system-preference-detection) * [Key Files Reference](https://docs.openalgo.in/developers/design-documentation/49-themes#key-files-reference) sun-brightdesktopmoon Copy // frontend/src/stores/themeStore.ts import { create } from 'zustand'; import { persist } from 'zustand/middleware'; type ThemeMode = 'light' | 'dark'; type AppMode = 'live' | 'analyzer'; type ThemeColor = 'zinc' | 'slate' | 'stone' | 'gray' | 'neutral' | 'red' | 'rose' | 'orange' | 'green' | 'blue' | 'yellow' | 'violet'; interface ThemeState { theme: Theme; accentColor: AccentColor; setTheme: (theme: Theme) => void; setAccentColor: (color: AccentColor) => void; toggleTheme: () => void; } export const useThemeStore = create()( persist( (set) => ({ theme: 'light', accentColor: 'blue', setTheme: (theme) => { set({ theme }); applyTheme(theme); }, setAccentColor: (accentColor) => { set({ accentColor }); applyAccentColor(accentColor); }, toggleTheme: () => { set((state) => { const newTheme = state.theme === 'light' ? 'dark' : 'light'; applyTheme(newTheme); return { theme: newTheme }; }); } }), { name: 'openalgo-theme', partialize: (state) => ({ theme: state.theme, accentColor: state.accentColor }) } ) ); Copy function applyTheme(theme: Theme) { const html = document.documentElement; // DaisyUI theme attribute html.setAttribute('data-theme', theme); // Tailwind dark mode class if (theme === 'dark') { html.classList.add('dark'); } else { html.classList.remove('dark'); } } function applyAccentColor(color: AccentColor) { const html = document.documentElement; // Remove existing accent classes const accentClasses = ['accent-blue', 'accent-green', 'accent-purple',\ 'accent-orange', 'accent-red', 'accent-yellow',\ 'accent-pink', 'accent-cyan']; html.classList.remove(...accentClasses); // Add new accent class html.classList.add(`accent-${color}`); } Copy ┌────────────────────────────────────────────────────────────────────────────┐ │ Theme Modes │ │ │ │ Light Mode Dark Mode │ │ ─────────── ───────── │ │ Background: #FFFFFF Background: #1F2937 │ │ Surface: #F3F4F6 Surface: #374151 │ │ Text: #111827 Text: #F9FAFB │ │ Border: #E5E7EB Border: #4B5563 │ │ │ │ Optimized for: Optimized for: │ │ • Daylight visibility • Reduced eye strain │ │ • Print-friendly • Low-light environments │ │ • Professional settings • OLED displays │ │ │ └────────────────────────────────────────────────────────────────────────────┘ Copy ┌────────────────────────────────────────────────────────────────────────────┐ │ App Mode Behavior │ │ │ │ LIVE MODE (default): │ │ • User can toggle light/dark mode │ │ • User can change theme color (zinc, blue, green, etc.) │ │ • Normal application appearance │ │ │ │ ANALYZER MODE (sandbox): │ │ • Theme changes are BLOCKED (setMode, setColor, toggleMode disabled) │ │ • Fixed dark purple theme via CSS class 'analyzer' │ │ • Visual distinction for paper trading environment │ │ • Mode synced with backend via /auth/analyzer-mode │ │ │ │ Switching modes: │ │ • toggleAppMode() - async call to /auth/analyzer-toggle │ │ • syncAppMode() - fetches current mode from backend │ │ • Mode changes emit events via onModeChange() listener │ │ │ └────────────────────────────────────────────────────────────────────────────┘ Copy // Handle analyzer mode theme changes const useAnalyzerTheme = () => { const { setAccentColor, accentColor } = useThemeStore(); const { isAnalyzerMode } = useAnalyzerStore(); const previousColorRef = useRef(accentColor); useEffect(() => { if (isAnalyzerMode) { // Save current and switch to purple previousColorRef.current = accentColor; setAccentColor('purple'); } else { // Restore previous color setAccentColor(previousColorRef.current); } }, [isAnalyzerMode]); }; Copy function ThemeToggle() { const { theme, toggleTheme } = useThemeStore(); return ( ); } Copy const ACCENT_COLORS = [\ { name: 'blue', label: 'Blue', class: 'bg-blue-500' },\ { name: 'green', label: 'Green', class: 'bg-green-500' },\ { name: 'purple', label: 'Purple', class: 'bg-purple-500' },\ { name: 'orange', label: 'Orange', class: 'bg-orange-500' },\ { name: 'red', label: 'Red', class: 'bg-red-500' },\ { name: 'yellow', label: 'Yellow', class: 'bg-yellow-500' },\ { name: 'pink', label: 'Pink', class: 'bg-pink-500' },\ { name: 'cyan', label: 'Cyan', class: 'bg-cyan-500' },\ ]; function AccentColorPicker() { const { accentColor, setAccentColor } = useThemeStore(); return (
{ACCENT_COLORS.map((color) => (
); } Copy function ThemeSettings() { const { theme, accentColor, setTheme, setAccentColor } = useThemeStore(); return (

Appearance

{/* Theme Mode */}
{/* Accent Color */}
); } Copy // tailwind.config.js module.exports = { content: ['./src/**/*.{js,ts,jsx,tsx}'], darkMode: ['class', '[data-theme="dark"]'], plugins: [require('daisyui')], daisyui: { themes: [\ {\ light: {\ "primary": "#3B82F6",\ "secondary": "#6B7280",\ "accent": "#8B5CF6",\ "neutral": "#374151",\ "base-100": "#FFFFFF",\ "base-200": "#F3F4F6",\ "base-300": "#E5E7EB",\ "info": "#3ABFF8",\ "success": "#36D399",\ "warning": "#FBBD23",\ "error": "#F87272",\ },\ dark: {\ "primary": "#3B82F6",\ "secondary": "#6B7280",\ "accent": "#8B5CF6",\ "neutral": "#1F2937",\ "base-100": "#1F2937",\ "base-200": "#374151",\ "base-300": "#4B5563",\ "info": "#3ABFF8",\ "success": "#36D399",\ "warning": "#FBBD23",\ "error": "#F87272",\ }\ }\ ] } }; Copy /* frontend/src/styles/accent-colors.css */ /* Blue accent (default) */ .accent-blue { --color-primary: 217 91% 60%; --color-primary-focus: 217 91% 50%; } /* Green accent */ .accent-green { --color-primary: 142 76% 36%; --color-primary-focus: 142 76% 30%; } /* Purple accent */ .accent-purple { --color-primary: 270 76% 60%; --color-primary-focus: 270 76% 50%; } /* Orange accent */ .accent-orange { --color-primary: 24 95% 53%; --color-primary-focus: 24 95% 45%; } /* Red accent */ .accent-red { --color-primary: 0 84% 60%; --color-primary-focus: 0 84% 50%; } /* Yellow accent */ .accent-yellow { --color-primary: 45 93% 47%; --color-primary-focus: 45 93% 40%; } /* Pink accent */ .accent-pink { --color-primary: 330 81% 60%; --color-primary-focus: 330 81% 50%; } /* Cyan accent */ .accent-cyan { --color-primary: 187 92% 41%; --color-primary-focus: 187 92% 35%; } Copy // Detect system color scheme preference function useSystemTheme() { const { setTheme } = useThemeStore(); useEffect(() => { // Check if user has set a preference const stored = localStorage.getItem('openalgo-theme'); if (stored) return; // User preference takes precedence // Use system preference const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)'); setTheme(mediaQuery.matches ? 'dark' : 'light'); // Listen for changes const handler = (e: MediaQueryListEvent) => { setTheme(e.matches ? 'dark' : 'light'); }; mediaQuery.addEventListener('change', handler); return () => mediaQuery.removeEventListener('change', handler); }, []); } sun-brightdesktopmoon --- # release | Documentation [Version 2.0.0.5 Releasedchevron-right](https://docs.openalgo.in/change-log/release/version-2.0.0.5-released) [Version 2.0.0.4 Releasedchevron-right](https://docs.openalgo.in/change-log/release/version-2.0.0.4-released) [Version 2.0.0.3 Releasedchevron-right](https://docs.openalgo.in/change-log/release/version-2.0.0.3-released) [Version 2.0.0.2 Releasedchevron-right](https://docs.openalgo.in/change-log/release/version-2.0.0.2-released) [Version 2.0.0.1 Releasedchevron-right](https://docs.openalgo.in/change-log/release/version-2.0.0.1-released) [Version 2.0.0.0 Releasedchevron-right](https://docs.openalgo.in/change-log/release/version-2.0.0.0-released) [Version 1.0.0.41 Releasedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.41-released) [Version 1.0.0.40 Releasedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.40-released) [Version 1.0.0.39 Releasedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released) [Version 1.0.0.38 Releasedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released) [Version 1.0.0.37 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.37-launched) [Version 1.0.0.36 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.36-launched) [Version 1.0.0.35 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.35-launched) [Version 1.0.0.34 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.34-launched) [Version 1.0.0.33 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.33-launched) [Version 1.0.0.32 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.32-launched) [Version 1.0.0.31 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.31-launched) [Version 1.0.0.30 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.30-launched) [Version 1.0.0.29 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.29-launched) [Version 1.0.0.28 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.28-launched) [Version 1.0.0.27 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.27-launched) [Version 1.0.0.26 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.26-launched) [Version 1.0.0.25 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.25-launched) [Version 1.0.0.24 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.24-launched) [Version 1.0.0.23 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.23-launched) [Version 1.0.0.22 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.22-launched) [Version 1.0.0.21 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.21-launched) [Version 1.0.0.20 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.20-launched) [Version 1.0.0.19 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.19-launched) [Version 1.0.0.18 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.18-launched) [Version 1.0.0.17 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.17-launched) [Version 1.0.0.16 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.16-launched) [Version 1.0.0.15 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.15-launched) [Version 1.0.0.14 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.14-launched) [Version 1.0.0.13 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.13-launched) [Version 1.0.0.12 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.12-launched) [Version 1.0.0.11 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.11-launched) [Version 1.0.0.10 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.10-launched) [Version 1.0.0.9 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.9-launched) [Version 1.0.0.8 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.8-launched) [Version 1.0.0.7 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.7-launched) [Version 1.0.0.6 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.6-launched) [Version 1.0.0.5 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.5-launched) [Version 1.0.0.4 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.4-launched) [Version 1.0.0.3 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.3-launched) [Version 1.0.0.2 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.2-launched) [Version 1.0.0.1 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.1-launched) [Version 1.0.0.0 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.0-launched) [PreviousPracticeschevron-left](https://docs.openalgo.in/security/practices) [NextVersion 2.0.0.5 Releasedchevron-right](https://docs.openalgo.in/change-log/release/version-2.0.0.5-released) sun-brightdesktopmoon sun-brightdesktopmoon --- # Version 2.0.0.5 Released | Documentation [hashtag](https://docs.openalgo.in/change-log/release/version-2.0.0.5-released#version-2.0.0.5-released) Version 2.0.0.5 Released -------------------------------------------------------------------------------------------------------------------------------------- **Date: 23rd Apr 2026** **Feature Release: Strategy Builder, Multi-Strike OI Chart, Market-Agnostic Trading Window, Plotly Partial Bundle & Broker Fixes** This is a feature release featuring **40 commits** (excluding auto-builds) from **3 contributors**, focused on a full-featured multi-leg Strategy Builder under /tools (payoff/Greeks/live P&L with saved portfolios), two new chart tabs (Strategy Chart + Multi Strike OI), a market-agnostic last-N-trading-days date window used across every historical-chart tool, a 75%-smaller Plotly bundle, security hardening, and broker-specific fixes for Firstock, Zerodha, Flattrade, and Shoonya. * * * **Highlights** * **Strategy Builder (new /tools feature)** — Build multi-leg option strategies from 40+ templates or manually, with live Greeks, payoff diagram, what-if simulators (spot %, IV %, days-elapsed), moneyness labels, live P&L streaming via shared WebSocket, true max-profit/max-loss computation, and saved Portfolio (MyTrades + Simulation watchlists). Zerodha basket-margin fix included so the margin row populates correctly. * **Strategy Chart & Multi Strike OI Tabs** — Two new tabs in the Strategy Builder: a historical combined-premium time series (`|Σ sign × close|` — absolute net credit/debit, qty-independent) with underlying overlay and IST-aware tooltips; and a per-leg OI overlay with distinct palette, per-series legend toggles, and live auto-refetch on leg add/remove. Both gracefully degrade when the broker doesn't serve intraday candles for index tokens (e.g., Zerodha 1m on NIFTY). * **Market-Agnostic Last-N-Trading-Days Window** — `/strategybuilder`, `/straddle`, `/ivchart`, `/straddlepnl`, and `/oiprofile` now fetch a generous calendar window and post-filter the returned series to the **last N distinct trading dates that actually have data**. Queries at 02:16 IST (after midnight, market closed) correctly yield 3 full trading days instead of 2 days + an empty today. Same logic works for NSE/BFO/MCX/CDS/crypto without hardcoding any session-close time. * **Plotly Partial Bundle (75% first-load reduction)** — Replaced the full `plotly.js-dist-min` with two custom builds: `plotly-2d` (scatter/bar/candlestick — 6 tools) and `plotly-3d` (surface — VolSurface only). First-time chart-tool download drops from **1.48 MB gzip → ~385 kB gzip** for 2D tools; shared `plotly.js/lib/core` is deduped into a cached vendor chunk. * **F&O Stock Coverage in Strategy Builder** — Index/Stock dropdown now populates every F&O stock (RELIANCE, TCS, HDFCBANK, …) in addition to indices, sourced from the same API as the Option Chain page. * **Zerodha History Performance** — Daily-interval history now requests in 2000-day chunks (instead of 60-day chunks used for intraday). Massively fewer API calls for multi-year backfills in Historify. * **Firstock V1.7 Alignment** — Order/position bug fixes, basket margin via `/V1/basketMargin`, WebSocket migration to V2 with unwrapped V2 tick format, FD-leak-free lifecycle. * * * **New Features** **Strategy Builder (/strategybuilder)** * 40+ pre-built strategies across Bullish / Bearish / Non-Directional families — long/short call/put, spreads, butterflies, condors, straddles/strangles, iron fly/condor, ratio spreads, jade lizard, calendars, diagonals, Batman, double fly/condor, and more * Manual leg builder with option and future segments, multi-expiry leg support (for calendars/diagonals) * Live Greeks per leg (delta, gamma, theta, vega, IV) via batched `/multioptiongreeks` * Payoff chart: "At Expiry" + "T+0" curves with ±σ shading, true max-profit / max-loss / breakevens * What-if simulators: spot-shift %, IV-shift %, days-forward (capped to nearest leg's expiry) * Per-leg moneyness labels (ATM, ITM1–ITM50, OTM1–OTM50) * Live P&L streaming via shared WebSocket — ticks only re-render the P&L tab, not Greeks / payoff / positions panel * Opstra-style per-leg active checkbox — unchecked legs excluded from payoff / Greeks / P&L analysis * Auto-refresh entry price on leg edits, per-leg lot ratios preserved from templates * Broker margin integration with Zerodha basket-margin fix so the Margin row displays correctly * Save / Update strategy to two fixed watchlists: **MyTrades** and **Simulation**, with live portfolio P&L streaming **Strategy Chart Tab** * Historical combined-premium series: `net_premium(t) = Σᵢ (signᵢ × priceᵢ(t))`, plotted as `| net_premium(t) |` (always positive, qty-independent) * Static credit/debit tag derived once from entry premia * Underlying overlay on left axis; combined premium on right axis * IST-aware `tickMarkFormatter` and tooltip with timestamp * Enable/disable toggles for both Underlying and Strategy series * Debounced auto-refetch (300 ms) on leg add/remove/toggle/side-flip — no manual refresh * Graceful degradation when broker returns empty underlying candles (e.g., Zerodha 1m index) — chart renders with a blue banner; P&L curves from leg history still show **Multi Strike OI Tab** * One OI series per active option leg on the right axis; underlying close on the left * Stable 10-colour palette keyed by leg symbol (survives reorders) * Human-readable legend labels: `NIFTY 28 APR 24500 CALL` * Tooltip lists every visible series with `L` / `Cr` OI formatting * Per-series and underlying toggles via the legend * Warns if the broker doesn't report historical OI for the selected legs **Other Tools** * Tools exchange picker restricted to **NFO / BFO** (+ CRYPTO for crypto brokers) to prevent invalid combinations * * * **Performance** * **Plotly partial bundles** — 6 tools now pull only scatter/bar/candlestick (no 3D engine); VolSurface stays in its own 3D chunk. First-visit Plotly download drops from **1,477 kB gzip to ~385 kB gzip (≈74% smaller)** for 2D tools, ~543 kB gzip for VolSurface (≈63% smaller). Shared `plotly.js/lib/core` is cached after the first Plotly-page visit. * **Zerodha daily history chunking** — daily-interval requests now use 2000-day chunks (Kite's documented per-request limit), preserving 60-day chunks for intraday. Cuts multi-year backfill API calls by ~33×. * **Strategy Builder UI** — split P&L columns and stopped live-tick layout jitter; scoped live-price re-renders so unrelated tabs don't repaint on ticks. * * * **Bug Fixes** **/strategybuilder / tools** * Compute true max-profit / max-loss for the payoff table (not just sample maxima) * Tighten payoff chart x-axis to ±10% around spot * Reshape calendar-family template icons * Remove duplicate close button in TemplateDialog * Preserve per-leg lot ratios when applying templates * Sequence symbol-switch fetches to avoid a stale-underlying race on the broker * Switch to shadcn `Checkbox` so Biome a11y lint passes in CI * Silence Biome `useSemanticElements` on StrategyPortfolio row **Broker Fixes** * Firstock: align with V1.7 API, fix order/position bugs, migrate WebSocket to V2 endpoint with V2 tick unwrapping, overhaul WS lifecycle to close FD leaks (#1285) * Firstock: basket margin calculator via `/V1/basketMargin`, demote per-tick / per-chunk logs from info to debug (#1288) * Flattrade: switch margin calculator from `SpanCalc` to `GetBasketMargin` (#1279) * Shoonya: switch margin calculator from `SpanCalc` to `GetBasketMargin` * Zerodha: 2000-day chunks for daily history (60 for intraday) **Security** * Refuse dev-server startup when `FLASK_DEBUG=true` is paired with a non-loopback bind * Bind ZeroMQ message bus to loopback only (prevents raw tick-feed exposure on public IPs) * Drop idle unauthenticated WebSocket clients * Force `protocol-buffers-schema >= 3.6.1` to patch prototype-pollution vulnerability **Auth / Login / Install** * Rate-limited login no longer falsely shows "Login successful" and redirects to `/broker` * Add `/socket.io/` nginx block in `install.sh` to prevent SocketIO session drops behind the reverse proxy **Flow** * Restore ConfigPanel scroll by adding `min-h-0` to `ScrollArea` (#1277) **Tools Date-Window Correctness** * `/straddle`, `/ivchart`, `/straddlepnl`, `/oiprofile` previously returned 2 trading days of data when queried at night/pre-market for `days=3`. All four now share the `_resolve_trading_window` + `_cap_last_n_trading_dates` helpers from `strategy_chart_service` so the cap counts actual returned dates rather than a hardcoded session close. * `/straddlepnl` simulation loop now iterates only the last N distinct trading days so `pnl_series`, `trades`, and `summary` all stay consistent with the chart range. * * * **Frontend Enhancements** * All F&O stocks populated in the Strategy Builder Index/Stock dropdown (not just major indices) * Save / Portfolio actions colocated above the payoff tabs — no scroll-to-top required * Opstra-style per-leg active checkbox with unchecked-leg exclusion from analysis * Moneyness labels (ATM/ITM/OTM with step count) on every leg row * Live-streaming portfolio P&L on the Strategy Portfolio page * * * **Documentation & Examples** * cURL request examples added to every endpoint page of the API docs * Phased implementation plan for GTT orders (`docs/plans`) * NIFTY 50 YTD 2026 heatmap example * NIFTY 50 YTD gainers/losers ranking example (via Historify DuckDB) * * * **Dependencies** * Bump 17 Python packages, including `python-multipart 0.0.26` (closes GHSA-59g5-xgcq-4qw3) * `actions/download-artifact`: 6 → 8 (#1270) * `protocol-buffers-schema`: pinned ≥ 3.6.1 (security) * `.gitignore`: DuckDB WAL files * * * **Contributors** Special thanks to everyone who made this release possible: * **@marketcalls (Rajandran)** — Strategy Builder (full feature + portfolio + live P&L + ~18 follow-on fixes), Strategy Chart and Multi Strike OI tabs, market-agnostic trading-day window across 5 services, Plotly partial bundle (75% first-load reduction), F&O stock dropdown, security hardening (dev-server bind guard, ZMQ loopback, WS idle drop), Zerodha daily-history chunking, install.sh SocketIO block, version management * **@Kalaiviswa (Kalaivani)** — Firstock V1.7 API alignment + V2 WebSocket migration + FD-leak fixes, Firstock/Flattrade/Shoonya basket-margin calculators, GTT orders phased plan * **@sivamudusu** — Flow ConfigPanel scroll restoration (#1277) * * * **Upgrade** No migration required. The Strategy Builder is automatically available under **Tools → Strategy Builder** after restart, and existing tools (`/straddle`, `/ivchart`, `/straddlepnl`, `/oiprofile`) will now return the correct N trading days of data without any configuration change. * * * **Links** * **Repository**: [https://github.com/marketcalls/openalgoarrow-up-right](https://github.com/marketcalls/openalgo) * **Documentation**: [https://docs.openalgo.inarrow-up-right](https://docs.openalgo.in/) * **Discord**: [https://www.openalgo.in/discordarrow-up-right](https://www.openalgo.in/discord) * **YouTube**: [https://www.youtube.com/@openalgoarrow-up-right](https://www.youtube.com/@openalgo) [Previousreleasechevron-left](https://docs.openalgo.in/change-log/release) [NextVersion 2.0.0.4 Releasedchevron-right](https://docs.openalgo.in/change-log/release/version-2.0.0.4-released) Last updated 2 days ago sun-brightdesktopmoon Copy # Pull latest cd /path/to/openalgo git pull origin main # Sync dependencies uv sync # Run the app uv run app.py # Restart # Docker: docker compose down && docker compose up -d # Systemd: sudo systemctl restart openalgo sun-brightdesktopmoon --- # Version 2.0.0.3 Released | Documentation #### [hashtag](https://docs.openalgo.in/change-log/release/version-2.0.0.3-released#version-2.0.0.3-released) Version 2.0.0.3 Released **Date: 13th Apr 2026** **Feature Release: Async-to-Sync WebSocket Migration, Market Price Protection (MPP), Samco 2FA, Shoonya OAuth, Multi-Device Session Tracking & Security Hardening** This is a feature release featuring **59 commits** (excluding auto-builds) from **7 contributors**, focused on migrating broker WebSocket adapters from asyncio to sync for Docker/eventlet compatibility, Market Price Protection (MPP) for Zerodha/Kotak/Samco/Tradejini, Samco 2FA authentication, Shoonya OAuth migration, multi-device session tracking, Telegram bot enhancements, and security hardening. * * * **Highlights** * **Async-to-Sync WebSocket Migration** — Converted Zerodha, Upstox, and mstock streaming adapters from asyncio `websockets` to sync `websocket-client`, eliminating greenlet conflicts in Docker (Gunicorn + eventlet) deployments * **Market Price Protection (MPP)** — Added automatic MARKET/SL-M to LIMIT/SL conversion with MPP for Zerodha, Kotak, Samco, and Tradejini, protecting traders from extreme price slippage * **Samco 2FA Authentication** — Complete Samco 2FA implementation with OTP, secret key, IP management, and order status normalization * **Shoonya OAuth Migration** — Migrated Shoonya from TOTP login to OAuth (GenAcsTok) authentication with WebSocket and SL-M MPP fixes * **Multi-Device Session Tracking** — Session resume support across devices with active session monitoring and login activity tracking * **Telegram Bot Commands** — New `/closeall` and `/mode` Telegram commands for remote position management and mode switching * **Dynamic Browser Tab Titles** — All 80+ pages now show descriptive titles in browser tabs (e.g., "OI Tracker | OpenAlgo") * **Synthetic Future API Optimization** — Reduced broker API calls from 4+ to 2 using multiquotes batching, cutting Dhan response time from ~8s to ~2s * **Multi-Arch Docker Images** — CI/CD now builds both amd64 and arm64 Docker images on native runners * **Security Patches** — Updated cryptography, axios, vite, Pygments, and lodash-es for CVE fixes * * * **New Features** **Async-to-Sync WebSocket Migration** * Convert Zerodha streaming from async websockets to sync websocket-client * Convert Upstox streaming from async websockets to sync websocket-client * Convert mstock streaming from async websockets to sync websocket-client * Reset Upstox and mstock reconnect counters on successful connection **Market Price Protection (MPP)** * Enable market protection for Zerodha market orders with decimal strike preservation * Add MPP for Kotak market orders (MARKET → LIMIT, SL-M → SL with tick-based price protection) * Convert MARKET/SL-M orders to LIMIT/SL with MPP for Samco * Add MPP and fix orderbook status mapping for Tradejini * Guard `trigger_price` float conversion in SL-M MPP handler **Samco 2FA Authentication** * Implement Samco 2FA authentication with OTP, secret key, and IP management * Refactor Samco 2FA to auth table with `aux_param` columns * Fix order status normalization for Cancel/Modify buttons in orderbook * Resolve FD leaks and resource issues in Samco WebSocket streaming * Use equity segment only for Samco funds to avoid double-counting **Shoonya OAuth Migration** * Migrate Shoonya from TOTP login to OAuth (GenAcsTok) authentication * Fix Shoonya WebSocket, SL-M MPP conversion, and circular import * Fix review issues: input validation, null safety, log redaction **Multi-Device Session & Login Activity** * Multi-device session resume and active session tracking * Login activity tracking and security dashboard tabs * Resolve file descriptor and memory leak from uncleaned database sessions **Telegram Bot Enhancements** * Add `/closeall` and `/mode` Telegram bot commands for remote trading control * Fix `/chart` rendering in Docker and eventlet environments **Frontend Enhancements** * Dynamic browser tab titles for all 80+ pages (#881) * Copy and download buttons for Python strategy logs (#1233) * Add aria-labels to TradeBook buttons for accessibility (#1189) **Tradejini Broker Improvements** * Add index symbol normalization and fix WebSocket exchange mapping * Prevent WebSocket FD leaks in quotes, depth, and streaming * Add MPP and fix orderbook status mapping **Smart Order Optimization** * Remove 500ms smart order delay, add position cache + per-symbol lock for faster execution **Infrastructure** * Build multi-arch Docker images (amd64 + arm64) on native runners * Replace `traceback.print_exc()` with `logger.exception()` across all REST API endpoints (#1012) * * * **Bug Fixes** * Fix: prevent duplicate order execution race condition in sandbox mode * Fix: optimize synthetic future API — reduce broker API calls from 4+ to 2 using multiquotes (#855) * Fix: return mock response object instead of None for MPP ValueError * Fix: address cubic-dev P1 issues in order\_api and auth\_api * Fix: IIFL Capital index symbol normalization and quotes update * Fix: add IIFL Capital to install script files * Fix: add missing security headers to Flask responses (#1014) * Fix: standardize error logging with `logger.exception()` (#1017) * Fix: adjust font sizes and cell heights in seasonality heatmap * Fix: refine monthly data fetching and processing in seasonality * Fix: update openalgo SDK to 1.0.47, remove numba/llvmlite dependencies * * * **Security** * Bump cryptography to 46.0.7 (security patch) * Bump vite to 7.3.2 (security patch) * Bump axios to 1.15.0 (security patches) * Upgrade cryptography, Pygments, and lodash-es for security * * * **Contributors** Special thanks to all contributors who made this release possible: * @Kalaiviswa (kalaivani) — Async-to-sync WebSocket migration (Zerodha, Upstox, mstock), Tradejini MPP/FD fixes, Shoonya OAuth migration, Samco 2FA, multi-device session tracking * @marketcalls — Synthetic future optimization, browser tab titles, strategy log buttons, Telegram commands, smart order optimization, seasonality fixes * @Na1neeth (Navaneeth) — Samco 2FA authentication and WebSocket FD fixes * @Chessing234 (Taksh) — Security headers and error logging standardization * @LuckyAnsari22 — Database docstrings, TradeBook accessibility * @mvanhorn — Replace traceback.print\_exc() with logger.exception() * * * **Links** * **Repository**: [https://github.com/marketcalls/openalgoarrow-up-right](https://github.com/marketcalls/openalgo) * **Documentation**: [https://docs.openalgo.inarrow-up-right](https://docs.openalgo.in/) * **Discord**: [https://www.openalgo.in/discordarrow-up-right](https://www.openalgo.in/discord) * **YouTube**: [https://www.youtube.com/@openalgoarrow-up-right](https://www.youtube.com/@openalgo) * * * [PreviousVersion 2.0.0.4 Releasedchevron-left](https://docs.openalgo.in/change-log/release/version-2.0.0.4-released) [NextVersion 2.0.0.2 Releasedchevron-right](https://docs.openalgo.in/change-log/release/version-2.0.0.2-released) Last updated 12 days ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Version 2.0.0.4 Released | Documentation **Date: 16th Apr 2026** **Feature Release: Exchange-Aware /python Strategies, Event-Driven Dashboard, Compound Rate Limits, Structured Error Logging & Broker Fixes** This is a feature release featuring **41 commits** (excluding auto-builds) from **6 contributors**, focused on making /python strategy hosting exchange-aware with per-strategy holiday calendars, replacing polling with event-driven SocketIO refresh across trading pages, adding structured JSON error logging, sandbox performance optimization, compound rate limit support, and broker-specific fixes for Motilal, Groww, Zebu, Flattrade, and Definedge. * * * **Highlights** * **Exchange-Aware /python Strategies** — Each strategy now carries its own exchange (NSE/BSE/NFO/BFO/MCX/BCD/CDS/CRYPTO). The host gates start/stop using that exchange's holiday calendar — MCX strategies keep running on NSE/BSE holidays during the MCX evening session, CRYPTO strategies ignore all holidays, and SPECIAL\_SESSION entries (Muhurat, DR-drill) override weekend rejects. No migration needed for existing strategies. * **Event-Driven Dashboard & Trading Pages** — Dashboard, OrderBook, TradeBook, Positions, and Holdings now refresh instantly via SocketIO events instead of polling every 30 seconds. Faster updates, less server load. * **Compound Rate Limits** — Rate limit settings now support Flask-Limiter's compound syntax (e.g., `"10 per second;40 per minute"`), matching broker-specific API limits like Flattrade's order rate. * **Structured JSON Error Log** — New `log/errors.jsonl` with timestamped JSON entries containing full traceback, logger name, source file:line, and Flask request context for every ERROR+ event. * **Sandbox Performance Optimization** — Basket orders, split orders, and options multi-orders now pre-fetch quotes in bulk via multiquotes — fewer API calls, faster paper trading execution. * **Motilal Broker Fixes** — MARKET/SL-M order handling, get\_holdings, tick\_size, WebSocket FD/thread leak fixes, and shared NSE\_INDEX/BSE\_INDEX symbol normalization. * **Eventlet asyncio Guard** — Real OS threads for asyncio event loops under eventlet, plus runtime event loop guards for Zebu, Flattrade, and Definedge to prevent `asyncio.run()` crashes in Docker. * * * **New Features** **Exchange-Aware /python Strategy Hosting** * Each strategy picks its own exchange via a new UI dropdown (NSE/BSE/NFO/BFO/MCX/BCD/CDS/CRYPTO) * Host gates start/stop using the strategy's exchange holiday calendar, not a hardcoded NSE check * MCX strategies run on NSE/BSE holidays during MCX's per-date session window (e.g., 17:00-23:55 on 14-Apr-2026) * CRYPTO strategies run 24/7, skip all holiday checks * SPECIAL\_SESSION rows (Sunday Muhurat, Saturday DR-drill) override weekend rejects per-exchange * `is_within_schedule_time` intersects user's schedule with the exchange's effective session window * New `OPENALGO_STRATEGY_EXCHANGE` env var injected into every strategy subprocess * Legacy strategies auto-backfilled to `exchange=NSE` on first load — zero migration required * Exchange badge displayed on the strategy card in the /python dashboard * Smart defaults on upload: CRYPTO pre-fills 24/7 + all 7 days, MCX pre-fills 09:00-23:55 * Resource limits guide (`strategies/RESOURCE_LIMITS.md`) documenting per-strategy memory, FD, CPU, and log caps **Event-Driven Dashboard Refresh** * Replace 30-second polling with SocketIO event-driven refresh on Dashboard * Replace polling with event-driven refresh on OrderBook, TradeBook, Positions, Holdings, and Funds pages * Type `ORDER_BOOK_EVENTS` as `OrderEventType[]` and wire into `useOrderEventRefresh` **Structured Error Logging** * New `log/errors.jsonl` — structured JSON Lines, ERROR+ only, with timestamp, module, source file:line, traceback, and Flask request context * Replace all manual `traceback.print_exc()` with `logger.exception()` across REST API, brokers, and websocket\_proxy * Add missing error logging to silent exception handlers **Compound Rate Limits** * Support semicolon-delimited compound rate limits in `.env` validation (e.g., `ORDER_RATE_LIMIT="10 per second;40 per minute"`) * Updated `.sample.env` and rate-limiting documentation with compound syntax examples **Sandbox Performance** * Pre-fetch quotes via multiquotes for sandbox basket orders * Pre-fetch quote once for sandbox split orders * Pre-fetch quotes via multiquotes for sandbox options multiorder * * * **Bug Fixes** * Fix: correct `get_open_position` exchange match in Groww smart orders (#1255) * Fix: clean up `logs_session` for non-banned IPs in SecurityMiddleware (#1256) * Fix: platform-aware health monitor FD thresholds + null-safe UI * Fix: move startup banner to print when server is actually ready * Fix: set HOME in systemd service so Telegram `/chart` works on Linux * Fix: revert StaticPool to NullPool and fix missing datetime import (SQLite connection handling) * Fix: duplicate rows on sort in TradeBook; use ArrowUp/ArrowDown for sort indicators * Fix: add missing `HEALTH_DATABASE_URL` to `.sample.env` and `install-multi.sh` **Broker Fixes** * Motilal: MARKET/SL-M order handling, get\_holdings, tick\_size, plug FD/thread leaks in WebSocket adapter, shared NSE\_INDEX/BSE\_INDEX symbol normalization (#1259) * Zebu/Flattrade/Definedge: auto-detect eventlet to prevent `asyncio.run()` crash in Docker * Runtime event loop guard for async batch quotes across brokers * Real OS threads for asyncio event loops under eventlet (websocket proxy + client) **/python Strategy Fixes** * Inject documented env vars (`OPENALGO_API_KEY`, `STRATEGY_ID`, `STRATEGY_NAME`) into strategy subprocess (#1247) * Improve reliability and FD hygiene for long-running strategies (#1258) * Document `.env` inheritance for strategies and fix `OPENALGO_API_KEY` references * Rewrite `/python/guide` with exchange-aware scheduling, env vars, and updated sample strategy * * * **Frontend Enhancements** * Client-side sorting for TradeBook and OrderBook (#1240) * Exchange dropdown and badge in /python strategy pages * CRYPTO smart-defaults (24/7 + all 7 days) on strategy upload * * * **Documentation** * Resource limits guide (`strategies/RESOURCE_LIMITS.md`) — per-strategy memory, FD, CPU, process, and log limits with realistic usage numbers and server sizing table * Updated `strategies/README.md` — exchange-aware gating, env var precedence (`HOST_SERVER` vs `OPENALGO_HOST`), worked examples (14-Apr-2026, Sunday Muhurat), troubleshooting, and migration notes * Enhanced `CLAUDE.md` with architectural context for Claude Code * Updated rate-limiting docs with compound syntax * * * **Security** * Update pillow, pytest, follow-redirects for dependabot alerts * Compound rate limit support prevents misconfigured single-limit workarounds * * * **Contributors** Special thanks to all contributors who made this release possible: * @marketcalls (Rajandran) — Exchange-aware /python strategies, event-driven dashboard, sandbox optimization, structured error logging, compound rate limits, version management * @Kalaiviswa (Kalaivani) — Eventlet asyncio guards, Zebu/Flattrade/Definedge fixes, /python guide rewrite, real OS thread migration * @iAbhi001 — Client-side sorting for TradeBook and OrderBook * @Sadhanandhann — StaticPool investigation for traffic logs DB * @mvanhorn (Mallikharjuna) — Replace traceback.print\_exc() with logger.exception() across brokers * * * **Upgrade** For existing /python strategies trading MCX or CRYPTO: open each strategy → Schedule → pick the correct exchange from the new dropdown → Save. NSE strategies need no changes. * * * **Links** * **Repository**: [https://github.com/marketcalls/openalgoarrow-up-right](https://github.com/marketcalls/openalgo) * **Documentation**: [https://docs.openalgo.inarrow-up-right](https://docs.openalgo.in/) * **Discord**: [https://www.openalgo.in/discordarrow-up-right](https://www.openalgo.in/discord) * **YouTube**: [https://www.youtube.com/@openalgoarrow-up-right](https://www.youtube.com/@openalgo) * * * [PreviousVersion 2.0.0.5 Releasedchevron-left](https://docs.openalgo.in/change-log/release/version-2.0.0.5-released) [NextVersion 2.0.0.3 Releasedchevron-right](https://docs.openalgo.in/change-log/release/version-2.0.0.3-released) Last updated 8 days ago sun-brightdesktopmoon Copy # Pull latest cd /path/to/openalgo git pull origin main # Sync dependencies uv sync # Rebuild frontend (if running locally) cd frontend && npm install && npm run build && cd .. # Restart # Docker: docker compose down && docker compose up -d # Systemd: sudo systemctl restart openalgo sun-brightdesktopmoon --- # Version 1.0.0.39 Released | Documentation Version **1.0.0.39** is a **major milestone release**, introducing a new Tier-1 broker (Kotak), expanding MultiQuote capabilities, and delivering extensive performance, stability, and data-pipeline improvements. * * * ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#id-0.-mandatory-upgrade-notice) **0\. Mandatory Upgrade Notice** This version **requires mandatory upgrade steps** due to new DB indexes, migration updates, and broker integrations. Upgrade guide: [**https://docs.openalgo.in/installation-guidelines/getting-started/upgrade**arrow-up-right](https://docs.openalgo.in/installation-guidelines/getting-started/upgrade) * * * ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#id-1.-major-new-integration-motilal-oswal-added) **1\. Major New Integration: Motilal Oswal Added** OpenAlgo now officially includes **full Motilal Oswal Integration**. **Motilal Oswal Integration Includes** * Order placement, modification, cancellation * Funds, positions, holdings * WebSocket support * Margin API * Contract & exchange mapping * Fully production-ready routing Motilal joins Angel, Dhan, Zerodha, Fyers, Upstox, and Kotak as a primary supported broker. This is one of the **largest broker integrations since OpenAlgo launched**. * * * ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#id-2.-multiquote-api-pilot-release) **2\. MultiQuote API – Pilot Release** A new-generation **MultiQuote API** has been introduced. **Pilot Launch** * **Fyers MultiQuote API** added. * Designed for ultra-fast multi-symbol quote retrieval. MultiQuote provides low-latency quotes for scanners, dashboards, and strategies. _(Further broker rollout will occur in upcoming versions.)_ * * * ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#id-3.-platform-improvements) **3\. Platform Improvements** #### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#websocket-verbose-mode) **WebSocket Verbose Mode** * New toggleable verbose mode to reduce noise and improve streaming efficiency. #### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#database-and-latency-engine) **Database & Latency Engine** * Added multiple high-impact DB indexes. * Unified migration system implemented. * Latency stats optimized (N+1 query fix). * latency.db storage trimmed by removing heavy request/response data. #### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#pnltracker) **PNLTracker** * Now supports **sub-minute trades** for precise scalping and HFT-style analytics. #### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#python-sdk-v1.0.40) **Python SDK v1.0.40** * Updated for compatibility with v1.0.0.39. * Enhanced WebSocket support with verbose control. * * * ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#id-4.-major-motilal-enhancements) **4\. Major Motilal Enhancements** **WebSocket Updates** * Normalized depth levels 2–5 (set to zero values). * Fixed depth feed and LTP updates for Index symbols. * Full LTP + quotes + 1-level depth implemented. * SSL certificate issue handled by disabling SSL until broker fixes. **Market Data & Contracts** * Master contract updated with Index contracts. * Historical API aligned with new contract updates. * Index quote logic improved. **Orders, Margin & Holdings** * Quantity-to-lot conversion fixed. * Minor order API bugs resolved. * Holdings API updated and stabilized. * Margin API enhanced. * * * ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#id-5.-options-engine-enhancements) **5\. Options Engine Enhancements** **OptionsMultiOrder** * Response formatting fixed. * Underlying LTP “None” issue resolved. * Multi-quote underlying resolution improved. * Multiple fixes based on PR review. **Options APIs** * Cleanup and parameter corrections across OptionsOrder and OptionSymbol. * * * ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#id-6.-additional-broker-level-improvements) **6\. Additional Broker-Level Improvements** **Dhan** * depth\_level fixes. * Depth 5/20 activation. * unsubscribe\_all fixed. **Fyers** * TBT unsubscription fixed. * TBT 50-level depth upgraded. **Zebu, PayTM, TradeJini** * Margin APIs updated (standardized for non-margin brokers). **General** * Multiple contract mapping and feed consistency fixes across brokers. * * * ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#id-7.-ui-security-and-documentation) **7\. UI, Security & Documentation** * Design documentation updated for November release. * Security updates including IDOR fixes and safer endpoint routing. * Removed unused login decorators from Playground. * Navigation/UI clean-ups. * Migration scripts updated for order mode changes. * * * ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#summary) **Summary** Version **1.0.0.39** introduces: * **Full Kotak integration** * **Pilot MultiQuote API for Fyers** * **Mandatory upgrade procedure** * Major Motilal WebSocket, depth & contract fixes * Database indexing & latency engine optimizations * Sub-minute PNL tracking * WebSocket verbose mode * Python SDK 1.0.40 * Dozens of broker stability improvements This release significantly strengthens OpenAlgo’s real-time data layer, multi-broker coverage, and execution reliability. * * * * * * [PreviousVersion 1.0.0.40 Releasedchevron-left](https://docs.openalgo.in/change-log/release/version-1.0.0.40-released) [NextVersion 1.0.0.38 Releasedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released) Last updated 4 months ago * [0\. Mandatory Upgrade Notice](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#id-0.-mandatory-upgrade-notice) * [1\. Major New Integration: Motilal Oswal Added](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#id-1.-major-new-integration-motilal-oswal-added) * [2\. MultiQuote API – Pilot Release](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#id-2.-multiquote-api-pilot-release) * [3\. Platform Improvements](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#id-3.-platform-improvements) * [4\. Major Motilal Enhancements](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#id-4.-major-motilal-enhancements) * [5\. Options Engine Enhancements](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#id-5.-options-engine-enhancements) * [6\. Additional Broker-Level Improvements](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#id-6.-additional-broker-level-improvements) * [7\. UI, Security & Documentation](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#id-7.-ui-security-and-documentation) * [Summary](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released#summary) sun-brightdesktopmoon sun-brightdesktopmoon --- # Version 1.0.0.38 Released | Documentation Version **1.0.0.38** is a feature-heavy release focused on **Options Trading APIs**, **Python 3.14 compatibility**, **Playground upgrades**, **WebSocket improvements**, and **major broker updates**. This is also the release where **OptionMultiOrder** becomes production-ready. * * * [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#major-feature-updates) **Major Feature Updates** ------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#id-1.-optionsmultiorder-calendar-diagonal-multi-expiry-support) **1\. OptionsMultiOrder – Calendar, Diagonal, Multi-Expiry Support** * OptionsMultiOrder now supports **different expiries** for each leg. * Enables **Calendar Spreads**, **Diagonal Spreads**, **Multi-expiry Condors**, etc. * Underlying LTP handling improved (None-type issues fixed). * Multi-leg duplication bug removed. ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#id-2.-synthetic-futures-api) **2\. Synthetic Futures API** * New lightweight API to generate **Synthetic Futures** using CE/PE combos. * Faster than computing spreads manually. * Part of the expanding derivatives toolkit. ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#id-3.-strikes-lookup-cache) **3\. Strikes Lookup Cache** * Implemented **in-memory caching** for near-instant strike discovery. * Massive performance boost for OptionsOrder, OptionsSymbol, OptionsMultiOrder. ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#id-4.-python-3.14-compatibility) **4\. Python 3.14 Compatibility** * OpenAlgo Python SDK upgraded to **v1.0.38**. * Ensures clean installs on macOS, Windows, Linux. * Fixes around dependency chain and wheel compatibility. ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#id-5.-api-playground-major-refresh) **5\. API Playground – Major Refresh** * Alphabetical sorting for endpoints. * Modern UI with cleaner validation. * Request builder improvements. * Local assets only (no CDN usage). * Ability to load endpoints directly from Bruno files. * New playground.js with improved utilities. * NavBar cleaned (playground removed from top nav and moved to Tools section). ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#id-6.-security-improvements) **6\. Security Improvements** * Multiple **security documentation updates**. * IDor vulnerability fixes. * Removed unused `login_required` decorators. * Safer routing between POST and GET usage. * * * [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#broker-wise-enhancements) **Broker-wise Enhancements** ------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#motilal-oswal) **Motilal Oswal** * MCX Options master scrip symbol issue fixed. ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#mstock) **MStock** * History API fixes. * Index values corrected in master contract. * OA exchange mapping fixed in orderbook, tradebook, positionbook. * Net P&L in positionbook corrected. ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#dhan) **Dhan** * Depth-level WebSocket: 5-level and 20-level depth fully activated. * depth\_level parameter bug fixed. * WebSocket unsubscribe\_all fixed. ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#fyers) **Fyers** * TBT (Tick-by-Tick) WebSocket unsubscription fixed. * TBT 50-level depth update implemented. ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#indmoney) **IndMoney** * LTP WebSocket improved. * Tradebook updated. ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#kotak) **Kotak** * Margin API updated. ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#groww) **Groww** * Margin API updated. ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#zebu) **Zebu** * Margin API updated (broker does not support margin; aligned accordingly). ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#tradejini) **TradeJini** * Margin API updated (non-margin broker standardization). ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#paytm-money) **PayTM Money** * Margin API cleaned (non-margin broker standardization). ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#fivepaisa) **Fivepaisa** * Margin API updated. ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#firstock) **Firstock** * Margin API updated. ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#definedge) **Definedge** * Margin API updated. ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#aliceblue) **AliceBlue** * Margin API updated. * * * [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#execution-and-engine-improvements) **Execution & Engine Improvements** ----------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#id-1.-options-engine) **1\. Options Engine** * Multi-quote fix added for underlying price fetch. * strike\_int parameter removed from OptionsOrder and OptionSymbol (optional for backward compatibility only). ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#id-2.-websockets) **2\. WebSockets** * Improved depth streaming and TBT stability. * Memory cleanup in WebSocket pipelines. * Logging noise heavily reduced. ### [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#id-3.-sandbox-fixes) **3\. Sandbox Fixes** * Race condition issue in parallel order placement fixed. * SmartOrder sandbox bug resolved earlier in 1.0.0.37, reinforced here. * * * [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#latency-and-storage-optimizations) **Latency & Storage Optimizations** ----------------------------------------------------------------------------------------------------------------------------------------------------------- * Latency monitoring optimized. * Requests and Responses trimmed to **NULL** inside latency.db to prevent DB bloat. * Database writes reduced significantly. * * * [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#ui-ux-and-misc-updates) **UI, UX, and Misc Updates** ----------------------------------------------------------------------------------------------------------------------------------------- * Password strength validation added. * Navbar improved using flex alignment. * Removed theme toggle from Playground (simplified UI). * Updated DaisyUI compiled CSS. * Fixed multiple mapping issues across the platform. * README updated with latest examples and SDK instructions. * * * [hashtag](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#summary) **Summary** --------------------------------------------------------------------------------------------------------- Version **1.0.0.38** delivers critical upgrades across the entire stack: * OptionsMultiOrder now supports **multi-expiry spreads** * Python SDK fully compatible with **Python 3.14** * Playground modern UI, utilities, security, and performance * Synthetic Futures API added * Huge batch of **Margin API** updates * Improved **WebSocket depth, TBT, and data pipelines** * Multiple **MStock**, **Dhan**, **Fyers**, **IndMoney**, and **Motilal** fixes * DB trimming + latency monitoring optimization This release focuses on **speed, reliability, and advanced options workflow automation**. [PreviousVersion 1.0.0.39 Releasedchevron-left](https://docs.openalgo.in/change-log/release/version-1.0.0.39-released) [NextVersion 1.0.0.37 Launchedchevron-right](https://docs.openalgo.in/change-log/release/version-1.0.0.37-launched) Last updated 5 months ago * [Major Feature Updates](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#major-feature-updates) * [1\. OptionsMultiOrder – Calendar, Diagonal, Multi-Expiry Support](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#id-1.-optionsmultiorder-calendar-diagonal-multi-expiry-support) * [2\. Synthetic Futures API](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#id-2.-synthetic-futures-api) * [3\. Strikes Lookup Cache](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#id-3.-strikes-lookup-cache) * [4\. Python 3.14 Compatibility](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#id-4.-python-3.14-compatibility) * [5\. API Playground – Major Refresh](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#id-5.-api-playground-major-refresh) * [6\. Security Improvements](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#id-6.-security-improvements) * [Broker-wise Enhancements](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#broker-wise-enhancements) * [Motilal Oswal](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#motilal-oswal) * [MStock](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#mstock) * [Dhan](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#dhan) * [Fyers](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#fyers) * [IndMoney](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#indmoney) * [Kotak](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#kotak) * [Groww](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#groww) * [Zebu](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#zebu) * [TradeJini](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#tradejini) * [PayTM Money](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#paytm-money) * [Fivepaisa](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#fivepaisa) * [Firstock](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#firstock) * [Definedge](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#definedge) * [AliceBlue](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#aliceblue) * [Execution & Engine Improvements](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#execution-and-engine-improvements) * [1\. Options Engine](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#id-1.-options-engine) * [2\. WebSockets](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#id-2.-websockets) * [3\. Sandbox Fixes](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#id-3.-sandbox-fixes) * [Latency & Storage Optimizations](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#latency-and-storage-optimizations) * [UI, UX, and Misc Updates](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#ui-ux-and-misc-updates) * [Summary](https://docs.openalgo.in/change-log/release/version-1.0.0.38-released#summary) sun-brightdesktopmoon sun-brightdesktopmoon ---