# What is OpenAlgo?

OpenAlgo is a free, open source, self hosted algorithmic trading platform that bridges trading ideas with execution. Built with Python Flask and a modern React frontend, it provides a unified API layer across 35 broker plugins: 34 securities integrations and Delta Exchange for crypto derivatives. It supports automation from Amibroker, TradingView, GoCharting, N8N, Python, Java, Go, .NET, Node.js, ChartInk, MetaTrader, Excel, and Google Sheets.

### 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.

{% embed url="<https://www.youtube.com/watch?v=S5myMo9WUdQ>" %}

***

### 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. OpenAlgo reduces this friction with common request and response shapes. Exchange coverage, authentication, market-data entitlement, GTT support, and other optional capabilities still vary by plugin and broker account.

{% embed url="<https://www.youtube.com/watch?v=ImQS-tz_GIo>" %}

***

### Who Should Use OpenAlgo?

#### 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.

***

#### 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

{% embed url="<https://www.youtube.com/watch?v=es6UUTWtG8Q>" %}

***

### Key Capabilities

#### 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

Broker plugins follow the common API structure for the operations they support.

***

#### 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.

***

#### Portfolio Analysis

OpenAlgo includes two authenticated, read-only portfolio workflows:

* **Portfolio Backtester** simulates a target NSE/BSE allocation using Historify or broker history, with rebalancing, drift bands, costs, benchmarks, robustness analysis, and a downloadable HTML tearsheet.
* **Portfolio Analyzer** loads current broker holdings and evaluates how today's market-value allocation would have behaved over a selected historical lookback.

Neither workflow places or modifies orders. See [Portfolio Backtester and Analyzer](/new-features/portfolio-analytics).

***

#### Chart Trading Terminal

The `/trading` terminal provides seven persisted layouts, from a single chart to an eight-chart `4×2` grid. Each pane supports its own symbol, interval, chart type, indicators, drawings, history backfill, market depth, and order entry while sharing one drawing toolbar and the application's real-time market-data connection.

See [Chart Trading Terminal](/new-features/trading-terminal).

***

#### 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**
* Configurable sandbox margin and order behavior
* Configurable MIS square-off schedules
* Simulated order and account state isolated from live broker execution

***

#### 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.

***

#### Security and Privacy

Security and data ownership are core principles of OpenAlgo:

* Broker session tokens are encrypted; `.env` credentials must be protected by the operator
* 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.

***

### 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.

### 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                 |

### 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       |

### Summary

| Aspect                | OpenAlgo                                                |
| --------------------- | ------------------------------------------------------- |
| **Cost**              | Free (Open Source, AGPL License)                        |
| **Brokers**           | 35 plugins: 34 securities integrations + Delta Exchange |
| **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                                 |

***


# Why to Build with OpenAlgo?

*"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.

<figure><img src="/files/UjpAdfwBmV39kDfDKeS1" alt=""><figcaption></figcaption></figure>

***

### What Makes OpenAlgo Different?

#### 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           |

#### Sandbox Testing & API Analyzer

The **Analyzer Mode** works like a local sandbox—test signals, APIs, and strategies with ₹1 Crore default sandbox capital without sending simulated orders to the broker. Market prices can still come from broker data services.

| 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    |
| **Execution Isolation** | Sandbox orders stay in the sandbox store |

#### 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, TXT, ZIP, or Parquet    |

#### Multi-Broker, Multi-Platform

OpenAlgo ships **35 broker plugins**: 34 securities integrations and Delta Exchange for crypto derivatives. The securities plugins share normalized API and WebSocket interfaces, reducing broker-specific strategy code.

```
┌─────────────────────────────────────────────────────────────────┐
│                     Your Strategy Code                          │
│                    (Write Once)                                 │
└─────────────────────────────┬───────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                   OpenAlgo Unified API                          │
│          (Common Interface Across Broker Plugins)               │
└───┬─────────┬─────────┬─────────┬─────────┬─────────┬──────────┘
    │         │         │         │         │         │
    ▼         ▼         ▼         ▼         ▼         ▼
┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐
│Zerodha│ │ Angel │ │  Dhan │ │ Fyers │ │Upstox │ │ More  │
└───────┘ └───────┘ └───────┘ └───────┘ └───────┘ └───────┘
```

#### 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 OpenAlgo symbol format, subject to each plugin's exchange coverage.**

***

### Speed, Stability, and Control

#### Performance Optimizations

| Feature                       | Impact                                               |
| ----------------------------- | ---------------------------------------------------- |
| **HTTPX Connection Pooling**  | Reuses outbound connections to reduce setup overhead |
| **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    |

#### Real-Time Monitoring

| Tool                    | Purpose                                        |
| ----------------------- | ---------------------------------------------- |
| **Latency Monitor**     | Track order round-trip times                   |
| **Traffic Logs**        | Request metadata, status, and duration history |
| **P\&L Tracker**        | Real-time profit/loss visualization            |
| **WebSocket Dashboard** | Monitor live data connections                  |

#### Notification & Alerts

| Channel               | Capabilities                          |
| --------------------- | ------------------------------------- |
| **Telegram Bot**      | Trade notifications, commands, alerts |
| **WebSocket Updates** | Real-time order and position changes  |
| **Dashboard Alerts**  | Visual notifications in UI            |

***

### 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 Protection** | Argon2 hashing plus encrypted retrieval copy |
| **Process Isolation**  | Hosted strategies run in separate processes  |

Deploy locally, in **Docker**, or on cloud servers. Public deployments still require correct TLS, proxy, firewall, secret, and update configuration.

***

### SDKs, Add-ins, and Ecosystem

#### Official SDKs

| Language    | Package              |
| ----------- | -------------------- |
| **Python**  | `openalgo` on PyPI   |
| **Node.js** | REST API integration |
| **Go**      | REST API integration |

#### 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      |

#### Deployment Options

| Option           | Best For                        |
| ---------------- | ------------------------------- |
| **Local**        | Personal desktop trading        |
| **Docker**       | Clean, reproducible deployments |
| **Cloud Server** | 24/7 automated trading          |
| **VPS**          | Low-latency remote access       |

***

### 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             | 35 plugin directories            |
| **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**.

***

### Open Source Freedom

Licensed under **AGPL**, OpenAlgo gives you:

| Freedom                        | Description                             |
| ------------------------------ | --------------------------------------- |
| **Full Source Code**           | Inspect, modify, extend                 |
| **Self-Hosting**               | Run on your infrastructure              |
| **No OpenAlgo Per-Order Fees** | Broker and exchange charges still apply |
| **No Vendor Lock-in**          | Switch or fork anytime                  |
| **Commercial Use**             | Build products on top (with compliance) |
| **Community Support**          | Discord, GitHub, documentation          |

***

### 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&#x20;*****access*****.** **OpenAlgo gives you&#x20;*****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


# OpenAlgo Architecture

## Windows/Mac Hosting Architecture

<figure><img src="/files/CoAwMmqyKatYfPRuWFRF" alt=""><figcaption></figcaption></figure>

## Linux Server Hosting Architecture

<figure><img src="/files/Y96Irj9qPfZShz2tEfdq" alt=""><figcaption></figcaption></figure>


# Mini FOSS Universe

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.

***

### Core Project

| Component            | Repository                                |
| -------------------- | ----------------------------------------- |
| 🧠 **OpenAlgo Core** | <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.

***

### 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.

#### 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

***

### 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-library> |
| Node.js             | <https://github.com/marketcalls/openalgo-node>           |
| Java                | <https://github.com/marketcalls/openalgo-java>           |
| RUST                | <https://github.com/marketcalls/openalgo-rust>           |
| .NET / C#           | <https://github.com/marketcalls/openalgo.NET>            |
| Go                  | <https://github.com/marketcalls/openalgo-go>             |

***

### 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-Excel>    |
| 📉 **Amibroker Plugin**            | <https://github.com/marketcalls/OpenAlgoPlugin>    |
| 🔁 **Backtrader Integration**      | <https://github.com/p2c2e/openalgo-backtrader>     |
| ⚡ **PineTS**                       | <https://github.com/marketcalls/openalgo-pinets>   |
| 🪞 **AlgoMirror**                  | <https://github.com/marketcalls/algomirror>        |
| ⚡ OpenAlgo chart                   | <https://github.com/crypt0inf0/openalgo-chart>     |
| 🌐 OpenAlgo Helm Chart             | <https://github.com/p2c2e/openalgo_helm>           |
| 🤖 **MCP / AI Agents**             | <https://github.com/marketcalls/openalgo-mcp>      |
| 📱 **OpenAlgo Mobile**             | <https://github.com/marketcalls/openalgo-mobile>   |
| 🌐 **Web Portal**                  | <https://github.com/marketcalls/openalgo-webpage>  |
| 🧩 **Chrome Plugin**               | <https://github.com/marketcalls/openalgo-chrome>   |
| 🚄 **Fast Scalper (Rust + Tauri)** | <https://github.com/marketcalls/fastscalper-tauri> |

***

### 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/python>
* Node.js — <https://docs.openalgo.in/trading-platform/nodejs>
* Java — <https://docs.openalgo.in/trading-platform/java>
* .NET — <https://docs.openalgo.in/trading-platform/.net>
* Go — <https://docs.openalgo.in/trading-platform/go>
* RUST — <https://docs.openalgo.in/trading-platform/rust>
* Excel — <https://docs.openalgo.in/trading-platform/excel>
* Amibroker Plugin — <https://docs.openalgo.in/trading-platform/amibroker/amibroker-plugin>
* MCP / AI Agents — <https://docs.openalgo.in/mcp>

***

### 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.


# Community Support

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.

### How to Join

To become a part of our growing community, please use the invitation link below: [Join the OpenAlgo Discord Community](https://discord.gg/UPh7QPsNhP) and you can raise your issues and feature request in [openalgo github section](https://github.com/marketcalls/openalgo/issues)

### 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.

### 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.

### [OpenAlgo Virtual Meet](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.

### Support and FAQ

#### 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.

#### Are there any regular events or meetups?

Yes, we host the OpenAlgo Virtual Meet annually. You can find the details in the #announcements channel.

#### How do I report inappropriate behavior?

Contact a moderator via direct message or use the `@moderator` tag in the #general channel.

### Resources

* \[OpenAlgo API Documentation]
* \[Tutorials and Guides]
* \[Trading Strategies and Tips]
* \[Code Repositories]

### Contact Us

For direct support or inquiries, please contact the community moderators or reach out through the following email: <support@openalgo.com>.


# OpenAlgo GPT

OpenAlgo GPT is an AI assistant built to help traders, investors, algo trading learners, and developers understand OpenAlgo and build trading strategies faster.

<figure><img src="/files/WK3pXPpf6HT4k4ExOMUO" alt=""><figcaption></figcaption></figure>

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/>

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/>

Join the OpenAlgo community:

<https://openalgo.in/discord>

Read the OpenAlgo documentation:

[https://docs.openalgo.in](https://docs.openalgo.in/)


# New Features

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 current feature guides cover:

* [Portfolio Backtester and Analyzer](/new-features/portfolio-analytics) for authenticated, read-only portfolio simulation and current-holdings scenarios.
* [Chart Trading Terminal](/new-features/trading-terminal) for multi-chart analysis, drawings, market depth, and order entry.
* [Flow Visual Strategy Builder](/new-features/flow-visual-strategy-builder) for validated node graphs and schedule, webhook, price-alert, and order-update triggers.
* [Python Strategy Hosting](/new-features/python-strategy-hosting) for process-isolated trusted scripts and scheduling.
* [Historify](/new-features/historify) for local DuckDB history ingestion, scheduling, charts, and export.
* [Scalping Terminal](/new-features/fast-scalper), [API Analyzer](/new-features/api-analyzer), [Action Center](/new-features/action-center), [PnL Tracker](/new-features/pnl-tracker), and the [Traffic/Latency Monitor](/new-features/traffic-latency-monitor).

Feature availability still depends on the active broker's supported exchanges, account entitlement, and market-data/order capabilities.


# Portfolio Backtester and Analyzer

OpenAlgo provides two authenticated, read-only portfolio workflows:

* **Portfolio Backtester** simulates a target allocation over a historical window.
* **Portfolio Analyzer** reads the holdings currently reported by the connected broker, weights them by current market value, and tests how that allocation would have behaved over a selected lookback.

Neither workflow places, modifies, or cancels an order.

## Before You Start

* Create an OpenAlgo API key.
* For the default **Historify** source, ingest daily history for every holding and the selected benchmark.
* For the **Broker API** source, log in to the broker and confirm that its history API covers the required symbols and dates.
* The engine supports long-only NSE/BSE cash equities and ETFs. It does not model derivatives, short positions, or a separate cash sleeve.

## Backtest a Portfolio

1. Open `/portfolio-backtester`.
2. Add up to 50 unique NSE/BSE holdings and assign a positive weight to each. Weights can be percentages or fractions; OpenAlgo normalizes their ratio.
3. Choose the date range and optional index benchmark.
4. Choose a history source:
   * `db` reads the local Historify store in one multi-symbol query.
   * `api` calls the active broker's history service sequentially.
5. Select `never`, `monthly`, `quarterly`, or `yearly` rebalancing. An optional drift band can trigger an earlier rebalance.
6. Configure capital, risk-free rate, slippage, and either the Indian delivery-cost schedule or a flat basis-point cost.
7. Run the backtest. The results page uses one internally consistent result object; changing tabs does not rerun the simulation.

## Understand the Results

The analysis can include:

* portfolio and benchmark equity curves;
* returns, volatility, drawdown, Sharpe/Sortino, capture, and rolling statistics;
* holding contributions and trailing returns;
* correlation, effective-holdings concentration, co-movement groups, and allocation drift;
* realized trading costs, turnover, and rebalancing dates;
* walk-forward windows, Monte Carlo paths, crisis periods, attribution, and seasonality;
* a portfolio-health grade whose inputs, formulas, and pillar weights are returned with the score.

Use **Download tearsheet** to export the same model as a self-contained `portfolio-tearsheet.html` file.

## Analyze Current Holdings

1. Log in to the broker.
2. Open `/portfolio-analyzer`.
3. Choose a 60-3650 day lookback, history source, benchmark, and risk-free rate.
4. OpenAlgo loads usable broker holdings, calculates market-value weights, and runs the same analytics engine.

Unsupported exchanges remain visible in the holdings summary and are listed as skipped. This is a current-allocation historical scenario, not an account-performance report: holdings data does not reveal when each lot was bought or the investor's cash flows.

## Limits

* Results use close-to-close price returns. Dividends are absent unless the selected history source embeds an adjusted series.
* Missing holding history fails the run instead of silently dropping the asset.
* Missing benchmark history degrades benchmark-relative sections but does not invalidate the portfolio calculation.
* Results depend on history quality, the chosen allocation, and cost assumptions. They are not a forecast or investment advice.

See the [Portfolio API](/api-documentation/v1/portfolio) for automation and [Portfolio Analytics Architecture](/developers/design-documentation/55-portfolio-analytics) for implementation boundaries.


# Chart Trading Terminal

The `/trading` route is OpenAlgo's multi-chart trading workspace. It combines historical and live market data, chart analysis, drawings, market depth, and order entry in one React interface.

## Layouts and State

Seven persisted layouts are available:

* one chart;
* two charts side by side;
* two charts stacked;
* a three-chart `1 + 2` layout with one large pane;
* a `2×2` four-chart grid;
* a six-chart `3×2` grid;
* an eight-chart `4×2` grid.

Each pane retains its own symbol and chart state. Layout choice and supported chart preferences persist in the browser or application preference store so returning to the terminal restores the workspace.

## Charts and History

The terminal supports candles, bars, line/area variants, Heikin Ashi, Renko, Range Bars, and Line Break views. Scrolling to the left edge requests older history so analysis is not limited to the initial window.

Indicators are loaded from the chart library catalog. Multiple instances can be added and configured per pane. Volume and grid display can be adjusted independently from the primary price scale.

## Drawing Tools

One drawing rail controls the active pane and includes line, channel, Fibonacci/Gann, shape, cycle, forecast, measurement, and text tools. Drawings support styling, locking, magnet mode, undo/redo, and per-pane persistence.

The shared rail deliberately targets only the active pane. Confirm the highlighted pane before adding, editing, or removing a drawing in a multi-chart layout.

## Symbols, Market Data, and Orders

Symbol search is ranked and debounced and can be opened independently for every pane. The terminal receives live ticks from OpenAlgo's raw WebSocket proxy, with REST quote fallback where required. The same market-data manager is shared across the page rather than opening one Gunicorn request thread per chart.

The order dialog supports inline order entry and market-depth review. Account-level order updates arrive through the order-update stream when the active broker provides a push adapter; Groww uses the server's explicit orderbook-polling fallback.

## Operational Boundaries

* Historical range, live fields, depth levels, and order-update latency depend on the active broker and account entitlement.
* Market data uses the raw WebSocket proxy on port `8765` (normally exposed as `/ws` behind the production reverse proxy); it is separate from Flask-SocketIO application events.
* A displayed quote or analytical drawing is not a guarantee of execution price.
* Test order entry in Analyzer mode before using the terminal with live capital.

See [WebSocket API](/api-documentation/v1/websockets) for the underlying market-data and order-update protocol.


# Scalping Terminal

The Scalping Terminal is a built-in, session-authenticated OpenAlgo workspace at `/scalping`. It combines contract selection, live prices, market-order entry, order and position books, optional charts, and server-managed stop protection in one browser page. No separate desktop installer or API-key configuration is required.

## Supported Markets

| Market              | Exchanges          | Products  |
| ------------------- | ------------------ | --------- |
| Equity              | NSE, BSE           | MIS, CNC  |
| Futures and options | NFO, BFO, MCX, CDS | MIS, NRML |

For derivatives, select an underlying and expiry. Options mode provides independent call and put strike selectors; futures mode resolves the selected futures contract. Equity mode uses symbol search.

## Live Workspace

The terminal shows live LTP and normalized quote fields through OpenAlgo's shared WebSocket feed. When the feed is unavailable, the page identifies its slower REST polling fallback so stale-data risk is visible.

Charts are optional and disabled by default. Enable them to view 1-minute, 5-minute, or 15-minute candles with volume. The chart toggle and timeframe are saved in the browser.

## Order Entry

All entries are market orders stamped with the `Scalping` strategy name. Configure quantity in shares for equities or lots for derivatives, select the product, and arm One-Click before sending entries.

| Market            | Keyboard action                                               |
| ----------------- | ------------------------------------------------------------- |
| Equity or futures | Up/Right buys; Down/Left sells                                |
| Options           | Up buys call; Down sells call; Right buys put; Left sells put |
| All modes         | F6 closes scalping positions; F7 cancels open orders          |

Held-key auto-repeat is ignored. Entry shortcuts are ignored while typing in an input. F6 and F7 remain risk-reducing actions even when One-Click is off; the on-screen buttons are available when an operating system intercepts function keys.

Server validation limits manual derivative entries to 20 lots and all requests to 100,000 units. Derivative quantity must match the contract lot size. Exit operations derive the reducing side from the actual position and cannot increase exposure.

## Stops And Targets

Predefined stop-loss and target values can be applied to new entries in points or percent. An open leg can also be assigned an exact stop price, optional target, and optional trailing step.

Stop configuration is persisted by symbol, exchange, product, application mode, and position side. The browser displays and edits this state, but a server-side risk monitor evaluates live ticks and sends a reducing exit when a stop or target is breached. Protection therefore continues after leaving the page or closing the browser, provided OpenAlgo and its market-data feed remain running.

Trailing stops move only in the favorable direction. Before an exit, the monitor rechecks the live position and submits whole-lot, freeze-safe reducing orders.

## Books And Mode

The workspace includes current positions, today's scalping orders, and today's scalping trades. Tracked legs remain visible while their persisted stop or tracking state is active.

Live and Analyzer modes are separated in the database. Analyzer mode uses sandbox positions and orders; live mode uses the authenticated broker session. Always confirm the mode badge before arming One-Click.

## Operational Notes

* A broker login and valid OpenAlgo API key are still required by the application, but the terminal resolves the key from the signed-in session.
* The terminal's session APIs are under `/scalping/api`; they are not public `/api/v1` API-key endpoints.
* Closing all positions only targets positions attributed to the scalping strategy. Cancel All cancels eligible open orders.
* If OpenAlgo or the broker feed is stopped, server-side stop evaluation cannot continue.


# Python Strategy Hosting

***

## Hosting Python Strategies in OpenAlgo

OpenAlgo hosts trusted Python trading strategies as separate subprocesses. Each run has its own process and log file, but lifecycle and scheduling state are still owned by the single OpenAlgo web worker.

{% embed url="<https://www.youtube.com/watch?v=pFy2Yx-kqkI>" %}

### 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.

### 2. Adding a New Strategy

Click the **Add Strategy** button to open the configuration interface.

#### 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.

#### 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**, **Stop Time**, and active days. Scheduling is required. Regular exchanges default to 09:00-16:00 IST on weekdays; crypto can run on all seven days.

### 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.

### 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.

### 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`           | Decrypted application API key, when one is configured. |
| `STRATEGY_ID`                | Unique identifier for the strategy.                    |
| `STRATEGY_NAME`              | Strategy display name.                                 |
| `OPENALGO_HOST`              | Internal host URL for REST requests.                   |
| `OPENALGO_STRATEGY_EXCHANGE` | Exchange selected in the strategy schedule.            |

Do not use the obsolete `OPENALGO_APIKEY` spelling. Build the WebSocket URL from the deployment configuration or your own strategy setting; `OPENALGO_WS_URL` is not one of the values injected by the current process launcher.

### 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.

***

#### 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.
* Run only code you trust. Hosted scripts execute as the OpenAlgo operating-system user and inherit the application environment.
* Keep one Gunicorn web worker. Strategy ownership, schedules, and live process state are process-local.
* One open live-log page uses one long-lived server execution slot. Size an experimental gthread deployment for the expected number of simultaneous `/python` tabs and other streams.
* Current main still has known threaded-shutdown risks around Unix `preexec_fn` and forced process-tree cleanup. Do not interpret process isolation as a guarantee of unattended 24x7 lifecycle recovery; after an abnormal server stop, verify that no old strategy process remains.

The production default remains Gunicorn with one eventlet worker. The [gthread migration](/installation-guidelines/getting-started/gthread-migration) is opt-in and experimental until it is merged into the application main branch.


# Flow - Visual Strategy Builder

Flow is OpenAlgo's visual workflow editor and synchronous execution engine. A workflow is a directed graph with exactly one trigger and a reachable chain of data, condition, trading, streaming, and notification nodes.

## Current Capabilities

* 61 node types kept in parity across the editor, backend validator, executor, and tests.
* Four triggers: Schedule, Price Alert, Webhook, and Order Update.
* Regular, smart, options, basket, split, modify, cancel, and close-position actions.
* Quote, depth, history, indicator, account, options, and calendar data nodes.
* Branch conditions and AND/OR/NOT gates.
* LTP/Quote/Depth subscriptions, logging, variables, math, HTTP requests, delays, wait-until, Telegram, and WhatsApp actions.
* Strategy-level realized/unrealized P\&L.
* JSON import, export, and validated in-place replacement.
* Execution history and per-node logs.

Flow does not provide loops, foreach/switch nodes, cross-run variables, automatic retry/error-handler nodes, built-in backtesting, or version-control history.

## Build a Workflow

1. Open `/flow` and create a workflow.
2. Drag one trigger onto the canvas.
3. Add downstream nodes and connect them in execution order.
4. Configure each node. Give a producer an `outputVariable` when a later node needs its result.
5. Branch from conditions using the `true`/`false` or `yes`/`no` handles.
6. Save while editing. Incomplete graphs may be saved, but corrupt node types, duplicate IDs, and dangling edges are rejected.
7. Use **Run Now** to validate and test a complete graph.
8. Activate the workflow when its trigger should remain registered.

## Trigger Types

| Trigger                             | Behavior                                                    | Important configuration                                              |
| ----------------------------------- | ----------------------------------------------------------- | -------------------------------------------------------------------- |
| Schedule (`start`)                  | Once, daily, weekly, or interval execution                  | IST time/day values and optional weekday market-hours gate           |
| Price Alert (`priceAlert`)          | Watches LTP for a level, cross, channel, or percentage move | Symbol/exchange, thresholds, once/every-time, expiration             |
| Webhook (`webhookTrigger`)          | Executes from a tokenized public POST                       | Optional symbol filter and payload or URL-secret authentication      |
| Order Update (`orderUpdateTrigger`) | Executes on normalized live/sandbox order state             | Order ID or symbol filter, optional exchange/status, once/every-time |

Every complete workflow must contain exactly one trigger. Multiple triggers, cycles, unreachable executable nodes, invalid edges, missing required fields, and oversized graphs are rejected before a broker call.

## Variables

Use `{{path}}` inside string fields:

```
{{quote.data.ltp}}
{{chain.data.results[0].ce.ltp}}
{{webhook.symbol}}
{{timestamp}}
{{session_date}}
```

Dotted dictionary keys and non-negative list indexes are supported. Most missing paths remain literal in the rendered string so the execution log exposes the mistake. A Variable Condition is stricter: an unresolved operand takes neither branch.

## Example: Signal to Order

```
Webhook Trigger -> Place Order -> Telegram Alert
```

Configure order fields with payload values such as `{{webhook.symbol}}`, `{{webhook.action}}`, and `{{webhook.quantity}}`. Give the order an output variable such as `order`, then notify with `{{order.orderid}}`.

Webhook URLs are:

```
POST /flow/webhook/<token>
POST /flow/webhook/<token>/<symbol>
```

Tokens and secrets are generated by the server. Use HTTPS for an internet-facing webhook.

## Import, Export, and Replace

Imported JSON uses this top-level shape:

```json
{"name": "Example", "nodes": [], "edges": []}
```

Import creates a new workflow. **Replace from JSON** changes the graph of an existing workflow while preserving its ID, webhook token/secret, API key, and active flag. If active trigger configuration changes, deactivate and reactivate the workflow so the trigger is registered again.

See [Flow Editor](/flow-editor/flow-editor) for the execution model, complete node reference, import behavior, tested tutorials, and current limitations.

## Execution and Safety

* One per-workflow lock prevents overlapping executions of the same workflow.
* A graph is limited to 500 nodes, 1000 edges, depth 100, and 500 total node visits.
* Schedule jobs use `coalesce=true`, `max_instances=1`, and a 60-second misfire grace.
* Active price and order-update watches are removed on deactivation/deletion and restored after restart when persisted configuration permits it.
* Order nodes use the same service layer and Analyzer/semi-auto routing rules as the REST API.
* Delay nodes and external broker/HTTP calls keep execution synchronous; avoid long waits across many active workflows.


# Historify

Historify downloads normalized broker candles into a local DuckDB database for reuse in charts, research, exports, and backtests. It also manages a symbol watchlist, data catalog, background download jobs, metadata, and recurring schedules.

{% embed url="<https://www.youtube.com/watch?v=NgRdbs0Xr5Q>" %}

## Access

Open **Profile -> Historify**, or navigate to `/historify` after signing in. The page and its `/historify/api` administration routes use the OpenAlgo browser session.

Historify administration is not part of the public `/api/v1` namespace. Public API clients can read stored candles through `/api/v1/history` with `source: "db"`.

## Storage

OpenAlgo uses six primary configured stores for separate application concerns. Historify owns `db/historify.duckdb`; it does not replace the main, traffic, latency, health, or sandbox databases.

The DuckDB schema stores:

* OHLCV and open-interest candles.
* Watchlist entries and symbol metadata.
* Catalog ranges and record counts.
* Download jobs and per-symbol job items.
* Schedules and schedule execution history.

Candles are upserted by symbol, exchange, interval, and timestamp to avoid duplicate rows. DuckDB connections use the application's locking and retry behavior.

## Watchlist And Discovery

Use the watchlist as the symbol source for bulk downloads and schedules. Symbols are validated against current contract data before persistence. The Historify page also exposes exchange and interval discovery plus futures and options contract selectors.

## Download Jobs

You can download one symbol or create a multi-symbol job from a watchlist, custom selection, option chain, or futures chain. Jobs run in a bounded background pool and report progress to the page through Socket.IO.

Supported job operations include:

* Pause, resume, cancel, retry, and delete.
* Incremental downloads for missing data before or after the stored range.
* Per-symbol status, downloaded records, timestamps, and broker errors.
* Restart recovery that marks orphaned active jobs failed so they can be retried.

Historical availability depends on the active broker, requested interval, and requested date range. A completed job can still contain symbol-level no-data or broker errors.

## Intervals And Charts

`1m` and `D` are the primary downloaded and stored intervals. Supported higher and calendar intervals can be derived from stored candles for charts, API queries, and exports. The running application exposes the exact current list through its Historify interval-discovery route.

Charts display stored historical candles, not a real-time feed. Use them to inspect gaps, range coverage, and unexpected values before relying on a dataset.

## Import And Export

Historify accepts validated CSV and Parquet uploads. Sample-file endpoints show the required structure.

Exports support CSV, TXT, ZIP, and Parquet with symbol, exchange, interval, and date filters. The preview reports matching records and estimated size. Generated temporary files are streamed and removed after download.

## Scheduling

Schedules use the Historify watchlist as their symbol source. Create interval-based or daily schedules, enable or disable them, pause or resume them, trigger them manually, and inspect execution history and the next run time.

OpenAlgo and the broker session must be available when a scheduled download runs. Broker token lifetime and market-data history limits remain broker-specific.

## Public History API

Choose the history source per request:

| Source | Behavior                                        |
| ------ | ----------------------------------------------- |
| `api`  | Fetch normalized candles from the active broker |
| `db`   | Query locally stored Historify candles          |

See [History](/api-documentation/v1/data-api/history) for the public request and response contract.

## Operational Notes

* Stored data is broker-independent after download, but its original quality and availability depend on the broker response.
* Analyzer and live trading databases are separate from Historify.
* Configure the DuckDB file with `HISTORIFY_DATABASE_PATH`; the default is `db/historify.duckdb`. The obsolete `HISTORIFY_DATABASE_URL` spelling is not a runtime alias.
* Back up the DuckDB file before destructive maintenance or host migration.


# API Analyzer

### What Analyzer Mode Does

Analyzer Mode routes supported trading and account operations to OpenAlgo's sandbox instead of the live broker. Simulated orders, trades, positions, holdings, funds, and configuration are stored in the separate `sandbox.db` store.

Market prices still come from the active broker data services. A broker connection and the relevant market-data entitlement may therefore be required. Analyzer Mode is an execution sandbox, not an exchange emulator or portfolio backtesting engine.

### Enable and Verify

Use the mode control in OpenAlgo, or call:

```http
POST /api/v1/analyzer
POST /api/v1/analyzer/toggle
```

Enable with:

```json
{
  "apikey": "<your_app_apikey>",
  "mode": true
}
```

The setting is application-wide for the single-user deployment, not per API key. The toggle API is blocked in semi-auto mode; in that posture the client must change mode from the authenticated UI.

Always verify the current mode before an automated run. Turning Analyzer Mode off returns supported order flows to live broker execution.

### Supported Behavior

* Regular, smart, basket, split, options, and multi-options services use sandbox paths where implemented.
* MARKET orders can complete from current prices; LIMIT, SL, and SL-M orders can remain pending until their conditions are met.
* The execution engine uses WebSocket prices when available and can fall back to polling.
* Position book, holdings, funds, order book, trade book, status, modify, cancel, close, and P\&L services use sandbox state where their analyzer branches exist.
* Analyzer GTT place, modify, cancel, and order-book services currently return HTTP 501.

Broker-specific RMS checks, queue priority, slippage, partial fills, outages, and exchange microstructure can differ from Analyzer results.

### Default Sandbox Configuration

Open `/sandbox` to inspect and update settings. Fresh sandbox databases use:

| Setting                        |          Default |
| ------------------------------ | ---------------: |
| Starting capital               |   INR 10,000,000 |
| Automatic fund reset           | Never (disabled) |
| Reset time when enabled        |        00:00 IST |
| Pending-order check interval   |        5 seconds |
| MTM update interval            |        5 seconds |
| NSE/BSE/NFO/BFO MIS square-off |        15:15 IST |
| CDS/BCD MIS square-off         |        16:45 IST |
| MCX MIS square-off             |        23:30 IST |
| NCDEX MIS square-off           |        17:00 IST |
| Equity MIS leverage            |               5x |
| Equity CNC leverage            |               1x |
| Futures leverage               |              10x |
| Option buy leverage            |               1x |
| Option sell leverage           |               1x |

These values configure the local simulator and can be changed. They are not promises about the active broker's live margin or square-off policy.

### Validation Workflow

1. Confirm `/api/v1/analyzer` reports `analyze_mode: true`.
2. Place one MARKET order and verify order book, trade book, position book, and funds.
3. Place a LIMIT or stop order away from the market and verify pending execution.
4. Exercise modify, cancel, smart, basket, and split flows used by the strategy.
5. Verify square-off and reset configuration instead of assuming defaults.
6. Review sandbox P\&L, order events, and errors.
7. Before live use, reduce quantity, verify mode again, and monitor the broker terminal.

### Reset Behavior

The Sandbox page provides manual reset controls and optional scheduled fund resets. A reset affects simulated state only. The default `reset_day` is `Never`, so the system does not perform a weekly reset unless an operator enables one.


# PNL Tracker

### 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.

<figure><img src="/files/b3EGNem1BO4WI1Id4HK7" alt=""><figcaption></figcaption></figure>

## PnL Tracker Documentation

### 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.

### Features

#### 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

#### 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)

### Technical Architecture

#### 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

#### Data Flow

```
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
```

### PnL Calculation Logic

#### For Executed Trades

```python
# For each trade in tradebook:
if action == 'BUY':
    pnl = (current_price - executed_price) × quantity
else:  # SELL
    pnl = (executed_price - current_price) × quantity
```

#### For Open Positions (No Trades)

```python
# 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)
```

#### Portfolio MTM

* Individual symbol PnLs are combined into portfolio PnL
* Time-synchronized data using pandas DataFrame joins
* Forward-fill missing data points for continuity

### 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

### Error Handling

#### 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

#### Logging

* Comprehensive logging at INFO, WARNING, and ERROR levels
* Detailed error messages for debugging
* Performance metrics logging

### Time Filtering

* **Start Time**: 9:00 AM IST (market open)
* **End Time**: Current time
* **Frequency**: 1-minute intervals
* **Timezone**: Asia/Kolkata (IST)

### Performance Optimization

#### Manual Refresh Only

* No automatic refresh to reduce server load
* User-initiated refresh via button click
* Prevents unnecessary API calls

#### Data Batching

* Single API call fetches all required data
* Parallel processing of multiple symbols
* Efficient pandas operations for calculations

#### Caching Strategy

* Session-based authentication caching
* Reuses auth tokens within session
* Minimizes database queries

### Broker Compatibility

#### Supported Features by Broker

* All brokers supporting tradebook API
* All brokers supporting 1-minute historical data
* Position tracking across all integrated brokers

#### 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

### Usage

#### 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

#### Understanding the Display

* **Green values**: Profit positions
* **Red values**: Loss positions
* **Purple line**: MTM PnL curve
* **Pink area**: Drawdown from peak

### Troubleshooting

#### 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

####


# Traffic/Latency Monitor

OpenAlgo provides separate views for HTTP traffic metadata and measured API/order latency.

### Traffic Monitor

Open **Logs > Traffic** or visit `/logs/traffic`.

The traffic table stores:

* timestamp;
* client IP;
* HTTP method and path;
* response status;
* middleware duration;
* request host;
* an unhandled error field, when present.

It does **not** store request bodies, response bodies, headers, user agents, or a processing timeline. This avoids persisting API keys and order payloads in the traffic table.

Summary panels show total requests, errors, average duration, and selected endpoint statistics. Filters can limit the view to all traffic or `/api/v1` traffic and to all, successful, or error responses. CSV export contains the same stored metadata.

Traffic rows live in `logs.db`. `TRAFFIC_LOG_RETENTION_DAYS` defaults to 30 days in `.sample.env`, and expired rows are purged when logging initializes.

### Latency Monitor

Open the Latency page to review timing records produced by instrumented OpenAlgo operations. The view is useful for comparing observed request durations and identifying changes on the actual deployment.

Latency depends on host load, network distance, broker response time, market conditions, connection reuse, and the operation being measured. The monitor reports observations; it does not guarantee an execution time or isolate exchange latency from every other component.

### Security Boundary

Both dashboards require an authenticated application session. Proxy-derived client IPs are trusted only when `TRUST_PROXY_HEADERS` is enabled; use that setting only behind a controlled reverse proxy.


# Chartink Integration

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.

<br>

Simply connect your Chartink webhook, configure strategies in OpenAlgo, and automate your trading flow.


# Action Center

### What is Action Center?

**Action Center** is an approval queue for eligible live order requests in semi-auto mode. Supported queued orders wait for review before the approval executor sends them to the broker.

<figure><img src="/files/CMZoqoqNrwI4SrTdnzKS" alt=""><figcaption></figcaption></figure>

Think of it as a **safety checkpoint** between your trading strategy and your real money.

### Why Would You Use It?

#### 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

### How It Works

#### Two Modes

**1. Auto Mode (Default) - Fully Automated**

```
Trading Signal → OpenAlgo → Broker → Order Executed
                (instant)
```

Orders execute immediately without any manual intervention.

**2. Semi-Auto Mode - Manual Approval Required**

```
Trading Signal → OpenAlgo → Action Center (WAIT) → You Approve → Broker → Order Executed
                            (paused here)              ↓
                                                 You Reject → Order Cancelled
```

Orders wait in Action Center for you to review and approve.

### Step-by-Step Setup

#### 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"

#### Step 2: Send Orders from Your Strategy

Your Python code stays exactly the same:

```python
api.placeorder({
    "apikey": "YOUR_API_KEY",
    "symbol": "SBIN",
    "action": "BUY",
    "quantity": "10"
})
```

But now the response will be different:

```json
{
    "status": "success",
    "message": "Order queued for approval in Action Center",
    "mode": "semi_auto"
}
```

#### 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

#### 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

### 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)

### 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

### Special Features

#### Auto-Refresh

Socket.IO events refresh the list when pending orders are created or updated. A manual refresh control is also available.

#### Statistics Dashboard

At the top, you see:

* Pending Approval: 5 orders
* Buy Orders: 3
* Sell Orders: 2
* Approved: 15
* Rejected: 2

#### Audit Trail

Every action is logged:

* Who approved/rejected
* When it was approved/rejected
* Rejection reason (if you provide one)

### Common Questions

#### Q: Do I need to change my trading code?

**A:** No! Your API calls stay exactly the same. Just toggle the mode in settings.

#### 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.

#### 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.

#### Q: Which order types can the approval executor dispatch?

**A:** The current executor supports:

* Regular orders (`placeorder`)
* Smart orders (`placesmartorder`)
* Basket orders (`basketorder`)
* Split orders (`splitorder`)
* Options orders (`optionsorder`)

`optionsmultiorder` and `placegttorder` services can currently create pending rows, but the approval executor has no dispatch branch for them. Approval reports `Unknown order type` and marks broker execution rejected. Close, cancel, cancel-all, modify, modify-GTT, and cancel-GTT operations are blocked by their services in semi-auto live mode rather than queued.

#### 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)

### 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        |

### When to Use Which Mode

#### Use Auto Mode When:

* Your strategy is proven and tested
* You need high-frequency trading
* You trust the strategy 100%
* Speed is critical

#### Use Semi-Auto Mode When:

* Testing a new strategy
* Learning algorithmic trading
* High-risk trades need verification
* You want full control over every order

### 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

### 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

###

***

**Remember**: Action Center gives you control. Use it wisely to protect your capital while testing new strategies!


# Responsibilities

Responsibilities for OpenAlgo Users

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.

***

### 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.

***

### 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.

***

### 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.

***

### 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.

***

### 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.

***

### 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.

***

### 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.

***

### 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.

***

### 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.

### 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.

***

### 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**.

***


# Compliance

## 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.

### 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.

### 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.

### 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.

### 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.

### 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.

### 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.*


# Contributors

### 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.

***

### 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.

***

### 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

***

### Technology Stack

OpenAlgo uses a **Python Flask** backend with a **React 19** single-page application frontend.

#### 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 resources and schema validation; Swagger UI is intentionally disabled
* **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

#### Frontend Technologies

* **React 19** - Component-based UI library
* **TypeScript 7.0+** - Type-safe JavaScript
* **Vite 8+** - 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 8** - 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

#### 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

#### 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.

***

### Development Setup

#### Prerequisites

Before you begin, make sure you have the following installed:

* **Python 3.12+** - [Download Python](https://www.python.org/downloads/)
* **Node.js 20, 22, or 24** - [Download Node.js](https://nodejs.org/)
* **Git** - [Download Git](https://git-scm.com/downloads)
* **Code Editor** - VS Code recommended with extensions:
  * Python
  * Pylance
  * Biome
  * Tailwind CSS IntelliSense
* **Basic Knowledge** of Flask and React

#### Install Dependencies

```bash
# 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 ..
```

> \[!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.

#### Configure Environment

```bash
# 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
```

> \[!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.

***

### Local Development

#### Run the Application

```bash
# Development mode (auto-reloads on backend code changes)
uv run app.py

# Application will be available at http://127.0.0.1:5000
```

#### 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):**

```bash
cd frontend
npm run dev
# Frontend dev server at http://localhost:5173 with hot module replacement
```

**Terminal 2 - Flask Backend:**

```bash
uv run app.py
# Backend API at http://127.0.0.1:5000
```

> **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.

#### Production Mode (Linux only)

```bash
# Run with Gunicorn
uv run gunicorn --worker-class eventlet -w 1 app:app

# IMPORTANT: Use -w 1 (one worker) for WebSocket compatibility
```

#### 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

#### Access Points

* **Main app**: <http://127.0.0.1:5000>
* **React frontend**: <http://127.0.0.1:5000/react>
* **API documentation**: [OpenAlgo API v1](/api-documentation/v1)
* **API Analyzer**: <http://127.0.0.1:5000/analyzer>

***

### Project Structure

Understanding the codebase structure will help you contribute effectively:

```
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/                   # 35 broker plugin directories
│   ├── 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)
```

#### 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 resources and schemas mounted at `/api/v1`; the maintained contract is in this GitBook
* **`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/`**: Six primary stores for isolation (main, traffic logs, latency, health, sandbox, and Historify)

***

### Development Workflow

#### 1. Fork and Clone

```bash
# Fork the repository on GitHub (click Fork button)
# Clone your fork
git clone https://github.com/YOUR_USERNAME/openalgo.git
cd openalgo

# Add upstream remote
git remote add upstream https://github.com/marketcalls/openalgo.git

# Verify remotes
git remote -v
```

> **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.

#### 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

#### 3. Create a Feature Branch

```bash
# 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
```

#### 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:

```bash
# Check Python code
uv run ruff check .

# Auto-fix issues
uv run ruff check --fix .

# Format code
uv run ruff format .
```

**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:

```bash
cd frontend

# Lint code
npm run lint

# Format code
npm run format

# Lint + format in one command
npm run check
```

**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:

```bash
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"
```

#### 5. Test Your Changes

```bash
# 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: run documented requests against http://127.0.0.1:5000/api/v1
# 4. API Analyzer: http://127.0.0.1:5000/analyzer
```

**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)

#### 6. Push to Your Fork

```bash
# 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
```

#### 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

***

### Contributing Guidelines

#### 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.

***

#### 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"](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

***

### Testing

#### Python Backend Tests

```bash
# 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
```

#### React Frontend Tests

```bash
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
```

#### Writing Python Tests

```python
# test/test_feature.py
import pytest

def test_feature():
    """Test your feature here."""
    result = some_function()
    assert result == expected_value
```

#### Writing React Tests

```typescript
// 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(<MyComponent />);
    expect(screen.getByText('Expected Text')).toBeInTheDocument();
  });
});
```

#### Writing E2E Tests

```typescript
// 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();
});
```

***

### Adding a New Broker

One of the most valuable contributions is adding support for new brokers. Here's a comprehensive guide:

#### 1. Broker Integration Structure

Create a new directory under `/broker/your_broker_name/`:

```
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
```

#### 2. Implement Required Modules

**2.1 Authentication API (`api/auth_api.py`)**

```python
"""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
```

**2.2 Order API (`api/order_api.py`)**

```python
"""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
```

**2.3 Data API (`api/data.py`)**

```python
"""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
```

**2.4 Plugin Configuration (`plugin.json`)**

```json
{
  "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
  }
}
```

#### 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 implemented endpoint with its documented request shape and automated API coverage
5. Test WebSocket streaming (if supported)
6. Validate error handling

#### 4. Reference Implementations

Study existing broker implementations:

* `/broker/zerodha/` - Most complete implementation
* `/broker/dhan/` - Modern API design
* `/broker/angel/` - WebSocket streaming

***

### Frontend Development

#### 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**

```bash
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/
```

**Component Library**

OpenAlgo uses [shadcn/ui](https://ui.shadcn.com/) built on Radix UI primitives with Tailwind CSS:

```tsx
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';

function PortfolioCard() {
  return (
    <Card>
      <CardHeader>
        <CardTitle>Portfolio Value</CardTitle>
      </CardHeader>
      <CardContent>
        <p className="text-2xl font-bold">₹1,25,000</p>
      </CardContent>
    </Card>
  );
}
```

**Server State with TanStack Query**

```tsx
import { useQuery } from '@tanstack/react-query';

function Positions() {
  const { data, isLoading, error } = useQuery({
    queryKey: ['positions'],
    queryFn: () => api.getPositions(),
  });

  if (isLoading) return <div>Loading...</div>;
  // render positions...
}
```

**Client State with Zustand**

```tsx
import { create } from 'zustand';

interface AppState {
  selectedBroker: string;
  setSelectedBroker: (broker: string) => void;
}

const useAppStore = create<AppState>((set) => ({
  selectedBroker: '',
  setSelectedBroker: (broker) => set({ selectedBroker: broker }),
}));
```

**Styling with Tailwind CSS 4**

Use Tailwind utility classes directly. Always use responsive and theme-aware patterns:

```tsx
{/* Responsive grid */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
  <div>Column 1</div>
  <div>Column 2</div>
  <div>Column 3</div>
</div>

{/* Use CSS variables for theme colors — adapts to light/dark mode */}
<div className="bg-background text-foreground">
  Automatically adapts to theme
</div>
```

**Linting and Formatting**

```bash
cd frontend

# Lint
npm run lint

# Format
npm run format

# Both (with auto-fix)
npm run check
```

***

### Documentation

#### Code Documentation

1. **Python Docstrings** - Use Google-style:

   ```python
   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
   ```
2. **TypeScript** - Use JSDoc where types alone aren't sufficient:

   ```typescript
   /**
    * Fetches positions for the current user.
    * Requires active broker authentication.
    */
   async function getPositions(): Promise<Position[]> {
     // ...
   }
   ```
3. **API Documentation** - Use Flask-RESTX decorators:

   ```python
   @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
   ```

***

### Best Practices

#### Security

1. **Never commit sensitive data**

   ```python
   # Bad - Never do this!
   API_KEY = 'abc123xyz'

   # Good - Use environment variables
   import os
   API_KEY = os.getenv('BROKER_API_KEY')
   ```
2. **Validate all inputs at system boundaries**

   ```python
   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')
   ```
3. **Use parameterized queries (SQLAlchemy ORM)**

   ```python
   # 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()
   ```
4. **Follow OWASP guidelines**
   * Enable CSRF protection (already configured)
   * Use HTTPS in production
   * Rate limiting is configured per endpoint
   * Sanitize user inputs

#### Performance

1. **Optimize database queries**

   ```python
   # 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()
   ```
2. **Use caching**

   ```python
   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
   ```
3. **Minimize API calls — use batch endpoints**

   ```python
   # Bad - Multiple API calls
   for symbol in symbols:
       quote = broker.get_quote(symbol)

   # Good - Batch API call
   quotes = broker.get_quotes_batch(symbols)
   ```

#### Code Quality

1. **Write self-documenting code**

   ```python
   # 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
   ```
2. **Keep functions small and focused**
3. **Return consistent JSON responses from API endpoints**

   ```python
   return {
       'status': 'success' | 'error',
       'message': 'Human-readable message',
       'data': {...}  # Optional payload
   }
   ```

***

### Troubleshooting

#### Common Issues

**Frontend Build Errors**

```bash
# 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
```

**Python Dependency Issues**

```bash
# Sync dependencies with uv
uv sync

# If issues persist, recreate the environment
rm -rf .venv
uv sync
```

**WebSocket Connection Issues**

```bash
# 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
```

**Database Locked Errors**

```bash
# SQLite doesn't handle high concurrency well
# Close all connections and restart the app
uv run app.py
```

***

### Getting Help

#### Support Channels

* **Discord**: Join our [Discord server](https://discord.com/invite/UPh7QPsNhP) for real-time help
* **GitHub Discussions**: Ask questions in [GitHub Discussions](https://github.com/marketcalls/openalgo/discussions)
* **Documentation**: Check [docs.openalgo.in](https://docs.openalgo.in)
* **GitHub Issues**: Report bugs in [Issues](https://github.com/marketcalls/openalgo/issues)

#### 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)

#### 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

***

### 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

***

### 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

#### 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

***

### Quick Reference Links

* **Repository**: [github.com/marketcalls/openalgo](https://github.com/marketcalls/openalgo)
* **Issue Tracker**: [github.com/marketcalls/openalgo/issues](https://github.com/marketcalls/openalgo/issues)
* **Documentation**: [docs.openalgo.in](https://docs.openalgo.in)
* **Discord**: [discord.com/invite/UPh7QPsNhP](https://discord.com/invite/UPh7QPsNhP)
* **PyPI Package**: [pypi.org/project/openalgo](https://pypi.org/project/openalgo)
* **YouTube**: [youtube.com/@openalgoHQ](https://youtube.com/@openalgoHQ)
* **Twitter/X**: [@openalgoHQ](https://twitter.com/openalgoHQ)

***

### 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.

***

### 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.*


# Monetization

**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:

<br>

**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.

<br>

**How OpenAlgo Should Not Be Monetized:**

<br>

**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.

<br>


# Brokers

OpenAlgo currently includes **35 broker plugin directories**. This section lists the 34 securities-broker integrations; [Delta Exchange](/crypto/exchanges/delta-exchange) is documented separately under Crypto.

1. 5paisa
2. 5paisa (XTS)
3. Aliceblue
4. AngelOne
5. Arrow
6. Compositedge (XTS)
7. Definedge Securities
8. Dhan
9. Dhan(Sandbox)
10. Firstock
11. Flattrade
12. Fyers
13. Groww
14. HDFC Sky
15. IIFL (XTS)
16. IIFL Capital
17. IndiaBulls
18. IndMoney
19. JainamXTS
20. Kotak Securities
21. Motilal Oswal
22. Mstock
23. Nubra
24. Paytm
25. Pocketful
26. Samco
27. Shoonya
28. Rmoney (XTS)
29. Tradejini
30. TradeSmart
31. Upstox
32. Wisdom Capital (XTS)
33. Zebu
34. Zerodha


# 5Paisa

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 generate APIs, and set up your environment for a smooth trading experience.

### **Generate APIs**

**Login to 5Paisa Website:**

* Navigate to the <https://login.5paisa.com/> and log in with your credentials.

<figure><img src="/files/NCvmyoCSRexj4CI8wJd7" alt=""><figcaption></figcaption></figure>

**Access API Key Generation:**

<figure><img src="/files/wU2t4n5kQdRpWyaiAbDc" alt=""><figcaption></figcaption></figure>

* Click on the profile dropdown on the top right next to your name.
* Go to **Xstream API** and click on **Get API Keys**.

<figure><img src="/files/26sHg94JldvqbaHGkcJV" alt=""><figcaption></figcaption></figure>

Keep this page open and navigate to the Dashboard - Create New App.

<figure><img src="/files/j9L3mDgEMxRmcaZylAIp" alt=""><figcaption></figcaption></figure>

### **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.

<figure><img src="/files/lsNKTzzQSz7YaJR1tEzO" alt=""><figcaption></figcaption></figure>

click on the profile dropdown on the top right corner to know your client code

<figure><img src="/files/YGTsqvCYP4nGNkZyctX1" alt=""><figcaption></figcaption></figure>

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:

```
BROKER_API_KEY = 'API_Key:::User_ID:::client_code'
BROKER_API_SECRET = 'Encryption_Key'
REDIRECT_URL = 'http://127.0.0.1:5000/fivepaisa/callback'
```

#### 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!


# 5paisa (XTS)

## 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

***

***

### Step 1: Create API Applications

Login to [XTS Developer Portal](https://xtsmum.5paisa.com/dashboard#!/app).

Once logged in:

1. Go to `My App` > `Create New Application`

<figure><img src="/files/NRd5ovzXHvxed05NWDO6" alt=""><figcaption></figcaption></figure>

1. Create two separate apps:
   * **Interactive Order API**
   * **Market Data API**

<figure><img src="/files/UQh8PbFrGZ2YENqy0r4b" alt=""><figcaption></figcaption></figure>

#### 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).

<figure><img src="/files/m56VnYFxPVt3bAJhIHd1" alt=""><figcaption></figcaption></figure>

Once submitted, wait for approval from the broker. After approval, the status will turn **Active**.

***

### Step 2: Setup Environment Variables

Refer to the `.sample.env` file in your OpenAlgo folder and prepare your `.env` as follows:

```bash
# 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'
```

Replace the values with actual credentials shown on your developer dashboard once approved.

***

### 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!


# AliceBlue

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.

{% embed url="<https://www.youtube.com/watch?v=Nam65PrfZvk>" %}

### 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.

### Steps to Create the AliceBlue API Secret Key

<figure><img src="/files/GoMjMxs05ImjKe3cdRwJ" alt=""><figcaption></figcaption></figure>

1. **To register as a Individual trader/Vendor,**
   * Navigate to the <https://a3.aliceblueonline.com/>
   * Select **Login as Individual Trader**
   * Enter your credentials to log in.

<figure><img src="/files/tkzGBorN1QaaE4xRMg1l" alt=""><figcaption></figcaption></figure>

2. **Access My Apps**

* On the top right corner, click on **Create App**.

<figure><img src="/files/heokxoZrQfVd1naaFEEv" alt=""><figcaption></figcaption></figure>

* Fill up the Mandatory Fields.
* Save it

<figure><img src="/files/AHOm17BMwqEL6Ymq8pO9" alt=""><figcaption></figcaption></figure>

* Fill up the Ip address , select the IP Type from the drop down and submit it.

<figure><img src="/files/EfaVbL4MhVX08CYCe0qK" alt=""><figcaption></figcaption></figure>

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.

### Configuring the `.env` File

The AliceBlue login user ID is used as the API key. Below is a sample configuration for the `.env` file:

```
# 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'

```

Replace `your_client_id` with your AliceBlue login user ID and `your_api_secret_here` with the generated API secret key.

#### 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.


# AngelOne

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.

### **What is 2-factor authentication (2-FA)?** <a href="#what-is-2-factor-authentication-2-fa-3" id="what-is-2-factor-authentication-2-fa-3"></a>

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.

### Manual TOTP Generation Process using Google Authenticator

Step 1 – Visit [smartapi.angelbroking.com/enable-totp](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.

<figure><img src="/files/68iEQldklnPSfZUz5JyB" alt=""><figcaption><p>Enable TOTP</p></figcaption></figure>

\
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

<figure><img src="/files/ggJt7BrUWJJpjLVcFD7j" alt=""><figcaption><p>Google Authenticator</p></figcaption></figure>

<figure><img src="/files/l4EXdaWPhnTZ9SUFA142" alt=""><figcaption></figcaption></figure>

**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 Portal](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 variable](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:

```
BROKER_API_KEY = 'your_api_key_here'
BROKER_API_SECRET = 'your_api_secret_here'
REDIRECT_URL = 'http://127.0.0.1:5000/angel/callback'
```

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.


# Arrow

## Arrow

Arrow ([arrow.trade](https://app.arrow.trade/)) is an ultra-low latency, speed-first retail brokerage and API platform built by **iRage Broking** (one of India's leading algorithmic and High-Frequency Trading firms). It provides ultra-fast APIs, zero intraday/F\&O brokerage, and institutional-grade tools to retail investors, regulated by NSE, BSE, and MCX. This API, used in the context of OpenAlgo integration, enables automated trading strategies, real-time market data access, order management, and more.

The integration process involves creating an app in the Trading API section, capturing the generated credentials, and configuring them in OpenAlgo's environmental variables.

#### Prerequisites

Before proceeding with authentication, please make sure you have:

1\)Valid Arrow user credentials

2\)Registered your redirect URL in the developer apps section (click on the profile icon and then click on **Trading API's** on the dropdown menu) of the main [Trading App](https://app.arrow.trade/)

<figure><img src="/files/y2sHPRC1LZDG6RvyNbHU" alt=""><figcaption></figcaption></figure>

3\)Filled in the form with the required data (static IP is now mandatory as per the latest SEBI Circular)

4\)Your application credentials, `appID` and `appSecret`, handy (click on the **+Create New** button in the Trading API section)

#### App Registration

Goto the main [Trading App](https://app.arrow.trade/) and login with your credentials. Sign up if you are a new user.

Step 1: Click on the profile icon and select **Trading API's** from the dropdown menu.

Step 2: Click the **+Create New** button to open the **Create Trading API** form.

Step 3: Fill in the form with the required details.

<figure><img src="/files/cVUuFfuCo4R3mgfv78ea" alt=""><figcaption></figcaption></figure>

* **App name**: a name to identify your app, for example `openalgo`
* **App Icon**: an optional icon for your app
* **Redirect URL**: `http://127.0.0.1:5000/arrow/callback`
* **Postback URL**: a valid URL for order postback notifications (a dummy url such as `https://google.com` can be used)
* **Description**: a short description of your app, for example `openalgo`
* **Static IP Address**: your static IP, now mandatory as per the SEBI circular, for example `103.227.96.122`

Step 4: Click **Create key**.

Step 5: On the **App Created Successfully!** screen you will see your **App ID** and **App Secret**. Copy both and keep the App Secret secure.

<figure><img src="/files/B5PRcum49lOC7JjHEtg8" alt=""><figcaption></figcaption></figure>

Save the generated `appID` and `appSecret`. Later we will be adding them in the [environmental variable](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:

```
BROKER_API_KEY = 'your_app_id_here'
BROKER_API_SECRET = 'your_app_secret_here'
REDIRECT_URL = 'http://127.0.0.1:5000/arrow/callback'
```

Integrating OpenAlgo with Arrow's Trading API opens up possibilities for automated trading strategies, providing a powerful tool for traders and developers to act on market opportunities efficiently. It's essential to follow best practices for API integration, including handling rate limits, managing credentials securely, and ensuring robust error handling and logging mechanisms are in place.


# Compositedge

## 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.

***

### Step 1: Enable TOTP (Two-Factor Authentication)

1. Login to [Compositedge XTS](https://xts.compositedge.com/#!/app).

<figure><img src="/files/MQdBAx7C8ogaQmvLtfDl" alt=""><figcaption></figcaption></figure>

Go to `My Profile` from the top-right menu.

<figure><img src="/files/eruG2IKgznTzx0LHQ52X" alt=""><figcaption></figcaption></figure>

Scan the **QR Code** shown using Google Authenticator.

<figure><img src="/files/fhAtNjYqlCiJUGrm7EUZ" alt=""><figcaption></figcaption></figure>

Save the **Secret Key** and enable **TOTP**.

> This is required for secure API login during authentication.

***

### Step 2: Create API Applications

Login to [XTS Developer Portal](https://xts.compositedge.com/dashboard#!/login).

Once logged in:

1. Go to `My App` > `Create New Application`

<figure><img src="/files/9yNp58g1cUN9s8r3iLxe" alt=""><figcaption></figcaption></figure>

1. Create two separate apps:
   * **Interactive Order API**
   * **Market Data API**

<figure><img src="/files/xn4vcI2fQiumuu8xWGtc" alt=""><figcaption></figcaption></figure>

#### 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).

<figure><img src="/files/nQRRO1JGy162hRH9IR1h" alt=""><figcaption></figcaption></figure>

Once submitted, wait for approval from the broker. After approval, the status will turn **Active**.

***

### Step 3: Setup Environment Variables

Refer to the `.sample.env` file in your OpenAlgo folder and prepare your `.env` as follows:

```bash
# 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'
```

Replace the values with actual credentials shown on your developer dashboard once approved.

***

### 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.


# Definedge

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 Portal](https://myaccount.definedgesecurities.com/).
* OpenAlgo installed and configured on your local machine.

### Steps to Create the Definedge API Secret Key

#### 1. Login to Definedge Securities Portal

* Navigate to <https://myaccount.definedgesecurities.com/>.
* Enter your **UCC (Account ID)** and **password**.

<figure><img src="/files/NoXnKixdCTfAD5H2EDnW" alt=""><figcaption></figcaption></figure>

* Complete with OTP authentication send to your registered mobile and email ID.

<figure><img src="/files/j65xgmHPqVXCp3TLx3jG" alt=""><figcaption></figcaption></figure>

* This will take you to your dashboard.

#### 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**.

<figure><img src="/files/YAKqQYHkwYkMI1KxZppv" alt=""><figcaption></figcaption></figure>

**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

```
# 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' 
```

**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.


# Dhan

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.

{% embed url="<https://www.youtube.com/watch?v=Gs657PKGgcE>" %}

***

### 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) |

***

### Steps for Integration

#### **Step 1: Log in to Dhan Web Portal**

Visit [web.dhan.co](https://web.dhan.co/) and sign in to your Dhan account.

***

#### **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

<figure><img src="/files/J1pz94RrFsMiM3A1Vpac" alt=""><figcaption></figcaption></figure>

***

#### **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**.

<figure><img src="/files/YUaL6e2ubkxvSgZOv2OW" alt=""><figcaption></figcaption></figure>

***

#### **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**

<figure><img src="/files/QaG2L4sMnhGMQccKaUCU" alt=""><figcaption></figcaption></figure>

***

#### **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.

<figure><img src="/files/o6o2dqkw4HVXl4Yu75WR" alt=""><figcaption></figcaption></figure>

***

#### **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.

***

#### **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.

<figure><img src="/files/fHtPdZoISNaHiMGhHHzM" alt=""><figcaption></figcaption></figure>

***

### Environment Configuration

Once your credentials are generated, configure them in your `.env` file:

```env
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'
```

***

### 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) |

***

### 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.

***


# Dhan(Sandbox)

**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:

#### 1. **Visit DhanHQ DevPortal**

You’ll land on a login screen where you can enter your email or mobile number.

<figure><img src="/files/BMkFMcSm7DhNIZuKRUxe" alt=""><figcaption></figcaption></figure>

***

#### 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.

<figure><img src="/files/FIAgNl9pLyHAwQ1GJigl" alt=""><figcaption></figcaption></figure>

***

#### 3. **OTP Verification**

You will receive two OTPs:

* One on your **email**
* One on your **mobile**

Enter both to complete verification.

<figure><img src="/files/2r8Gkapqpf9zrkZLrbZO" alt=""><figcaption></figcaption></figure>

***

#### 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

<figure><img src="/files/sMvvctDgIXAUZxBQllbl" alt=""><figcaption></figcaption></figure>

These credentials are what you will use inside OpenAlgo’s configuration or `.env` file to test trading orders programmatically.

***

#### 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.

#### Configuration for OpenAlgo

Inside your OpenAlgo project (or any backend using Dhan APIs), create or update the `.env` file with the following keys:

```bash
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'
```

**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.


# Firstock

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.

## 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.com>.

• Enter your Firstock login credentials.

2\. Generate API Credentials:

<figure><img src="/files/WEOl13IzxOREjbfLBTCu" alt=""><figcaption></figcaption></figure>

• 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.

<figure><img src="/files/UPpoLLvLBrJCyXgfZ9op" alt=""><figcaption></figcaption></figure>

3\. Configure OpenAlgo:

• In your OpenAlgo .env file, set the following variables:

```bash
BROKER_API_KEY = 'Your Vendor Code'
BROKER_API_SECRET = 'Your API Key'
REDIRECT_URL = 'http://127.0.0.1:5000/firstock/callback'
```


# FlatTrade

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.

## 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.in](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”.

<figure><img src="/files/BGZi1Q19MreKckPo9sEk" alt=""><figcaption></figcaption></figure>

3.Click on Create the New API Key, select Order Volume :

<figure><img src="/files/3s8I0CpOf04S76UFOJMx" alt=""><figcaption></figcaption></figure>

4.Enter your IP Configuration (Primary IP is required, Secondary is optional) → Click Next

<figure><img src="/files/sLybdKjWCsf1CwQ4vsuL" alt=""><figcaption></figcaption></figure>

5.Fill out the URL Configuration

<figure><img src="/files/FP1TRfqcsxa4bF5DJOSQ" alt=""><figcaption></figcaption></figure>

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

<figure><img src="/files/JkGWqbDnbscW3jcRbcWE" alt=""><figcaption></figcaption></figure>

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:

```bash
BROKER_API_KEY = 'client_id:::api_key'
BROKER_API_SECRET = 'api_secret'
REDIRECT_URL = 'http://127.0.0.1:5000/flattrade/callback'
```


# Fyers

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.

{% embed url="<https://www.youtube.com/watch?v=lintXPX5LzE>" %}

For developers and algo traders interested in leveraging the Fyers API, the integration process typically includes the following steps:

<figure><img src="/files/JnbTduAksq2I15RmKAy5" alt=""><figcaption></figcaption></figure>

1. **Navigate to the Fyers MyAPI Dashboard**: Access the [MyAPI Dashboard](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.

<figure><img src="/files/6rqFfN9A2qmXZ7Uik2Gg" alt=""><figcaption></figcaption></figure>

Here is a sample of how the details would appear in a .env file for reference:

```bash
BROKER_API_KEY = 'your_api_key_here'
BROKER_API_SECRET = 'your_api_secret_here'
REDIRECT_URL = 'http://127.0.0.1:5000/fyers/callback'
```

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.

<br>


# Groww

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.

{% embed url="<https://www.youtube.com/watch?v=v22sneQGj1w>" %}

### How to Get Groww API Key and Secret?

<figure><img src="/files/0ht1m4xD8uCI7ulEXMg1" alt=""><figcaption></figcaption></figure>

To integrate OpenAlgo with Groww, follow the steps below to generate your API key (access token):

1. Visit the [Groww Trade API Portal](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

<figure><img src="/files/a8NRxNDfZRexbMmIx6eR" alt=""><figcaption></figcaption></figure>

Click on the **Generate API Keys** ,Enter the Token Name as "OpenAlgo" or any name of your choice and press **continue**

#### Now Generate the generated Grow API Key and API Secret from the Generate API Key

<figure><img src="/files/Uz9uBPFVQOodAKg4bQsY" alt=""><figcaption></figcaption></figure>

Click "**Add/Update Static IP**" next to Generate API Key

<figure><img src="/files/8J8oC7Nvs8YOWZm1UBLW" alt=""><figcaption></figcaption></figure>

### Important Points

* Do **not share** your access token with untrusted third-party platforms or individuals.

#### Configuration:

Here is how you would typically set up your environment variables in a .env file for Groww's API:

```bash
BROKER_API_KEY = 'your_groww_apikey_here'
BROKER_API_SECRET = 'your_groww_apisecret_here'
REDIRECT_URL = 'http://127.0.0.1:5000/groww/callback'
```

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.


# HDFC Sky

HDFC Sky (hdfcsky.com (<https://www.hdfcsky.com/>)) is the discount broking and investment platform from HDFC Securities, offering equity, F\&O, currency and commodity trading with a flat-fee brokerage model. Its Open API (developer.hdfcsky.com (<https://developer.hdfcsky.com/>)) exposes REST and WebSocket endpoints for order placement, portfolio and funds management, and market data. Regulated by NSE, BSE and MCX, this API, used in the context of OpenAlgo integration, enables automated trading strategies, real-time market data access, order management, and more.

The integration process involves logging in to the HDFC Sky Open API developer portal, creating a Trading API app, capturing the generated API Key and API Secret, and configuring them in OpenAlgo's environmental variables.

#### **Prerequisites**

Before proceeding with authentication, please make sure you have:

1\) A valid HDFC Sky trading account (Client ID / registered Email / Mobile number)

2\) Your registered mobile and email available to receive the login OTP

3\) Registered your redirect URL in the developer portal (created inside the **My Apps** section of [developer.hdfcsky.com](https://developer.hdfcsky.com/))

4\) A static IP address ready (mandatory as per the latest SEBI Circular; the app form provides Primary and Secondary Static IP fields)

5\) Your application credentials, **API Key** and **API Secret**, handy (generated after you click **Create** in the New App form)

#### **App Registration**

Goto the HDFC Sky Open API developer portal at [developer.hdfcsky.com](https://developer.hdfcsky.com/) and log in with your HDFC Sky credentials.

<figure><img src="/files/rlUtDSbEntKzdtoVObnp" alt=""><figcaption></figcaption></figure>

Step 1: On the home page, click the **Login** button in the top-right corner.

Step 2: On the Login screen, enter your **Client ID / Email ID / Mobile No.** and click **Proceed to HDFC SKY**. (New users can click **Sign Up**.)

<figure><img src="/files/VIN6Qd4MzKnldnUL542V" alt=""><figcaption></figcaption></figure>

Step 3: Enter the **4 digit OTP** sent to your registered mobile number and email ID to complete authentication.

Step 4: After login, a **My Apps** menu item appears in the top navigation bar. Click on **My Apps**.

<figure><img src="/files/SYIP3oScrGVDEblkhxT6" alt=""><figcaption></figcaption></figure>

Step 5: In the **My Apps** section, click the **+ Create** button to open the **New App** form.

Step 6: Fill in the form with the required details.

<figure><img src="/files/kg4IHfY5v9T323COtQyw" alt=""><figcaption></figcaption></figure>

* **App Name**: a name to identify your app, for example `openalgo`
* **Redirect URL**: `https://openalgo.local/hdfcsky/callback`
* **Postback URL**: an optional URL for order postback notifications (a dummy URL such as `https://google.com` can be used)
* **Primary Static IP**: your static IP, now mandatory as per the SEBI circular
* **Secondary Static IP**: an optional backup static IP address
* **Description**: a short description of your app, for example `openalgo`
* **APIs in this app**: keep **Trading API** selected (it enables placing orders and managing Stocks, Futures and Options)

Step 7: Click **Create**.

> Note: Your created app will be **deactivated by default**. Go to the **My Apps** section and activate it before using the credentials.

Step 8: In the **My Apps** list, confirm the app status shows **Active**. Reveal (eye icon) and **Copy** the **API Key** and **API Secret**.

<figure><img src="/files/UvggoBlO0VzqNHnitxdK" alt=""><figcaption></figcaption></figure>

Here is a sample of how the details would appear in a .env file for reference:

```
BROKER_API_KEY = 'your_api_key_here'
BROKER_API_SECRET = 'your_api_secret_here'
REDIRECT_URL = 'https://openalgo.local/hdfcsky/callback'
```

Integrating OpenAlgo with HDFC Sky's Open API opens up possibilities for automated trading strategies, providing a powerful tool for traders and developers to act on market opportunities efficiently. It's essential to follow best practices for API integration, including handling rate limits, managing credentials securely, and ensuring robust error handling and logging mechanisms are in place.


# IIFL (XTS)

Documentation in Progress


# IIFL Capital

OpenAlgo connects to IIFL Capital through their Markets' APIs developer portal. You'll need\
an active IIFL Capital trading account and a static public IP before you start, since IIFL whitelists the IP that's allowed to call your app.

**Prerequisites**

* An active IIFL Capital trading account (Client ID / PAN handy)
* A static public IP address — IIFL whitelists this IP and rejects API calls from anywhere else
* OpenAlgo running locally or on a host whose outbound IP matches what you'll register

**Step 1 — Visit the IIFL Markets' APIs portal**

Go to [https://markets.iiflcapital.com](https://developers.iiflcapital.com/)

Click Login / Sign Up at the top right and choose As Individual Trader.

<figure><img src="/files/jkIgtANdsB3uq5PZWJma" alt=""><figcaption></figcaption></figure>

**Step 2 — Log in to the Developer Portal**

Sign in with your IIFL credentials — Email, Mobile, Client ID, or PAN works. Use the same\
password you use for the IIFL trading platform.

<figure><img src="/files/5DtCc7P3L9Hl62L8LK5S" alt=""><figcaption></figcaption></figure>

**Step 3 — Open "My Apps"**

After login you land on the My Apps dashboard at developers.iiflcapital.com. Your IIFL\
Client ID is shown in the greeting.

If this is your first time, the apps list will be empty. Click Create App in the top-right.

<figure><img src="/files/QAbbAYBL1y02iGz96RUq" alt=""><figcaption></figcaption></figure>

**Step 4 — Create the OpenAlgo App**

Fill the Create App form

<figure><img src="/files/2TRzEf1VQEpGOyFo0MP0" alt=""><figcaption></figcaption></figure>

Click Submit.

**Important:** The Redirect URL must match <http://127.0.0.1:5000/iiflcapital/callback> exactly if you're running OpenAlgo locally on the default port. If you've changed HOST\_SERVER in your .env, replace 127.0.0.1:5000 with your actual host and port.

The Primary Static IP must match the public IP from which OpenAlgo will call IIFL. Use <https://www.whatismyip.com> to check. If your IP is dynamic (typical for home broadband), API calls will fail intermittently — you'll need a fixed-IP setup or VPS.

**Step 5 — Locate your App Key and App Secret**

After creation, your app shows up on the My Apps page with status Active. Click the\
three-dot menu (⋮) on the app row and choose View All Details.

<figure><img src="/files/G1kHNmh4lnmfXgrDtyc9" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/pS9FHRMas7fWavsNhY5i" alt=""><figcaption></figcaption></figure>

The View Details modal shows everything you need:

* App Name — friendly name only, not used in OpenAlgo
* Redirect URL — should match what you entered
* Primary Static IP — for reference
* Algo Registration Type — for reference
* App Key — this becomes BROKER\_API\_KEY
* App Secret Key — this becomes BROKER\_API\_SECRET

If you ever lose the App Secret, use Regenerate App Secret from the same ⋮ menu. Existing OpenAlgo sessions will need to log in again after rotation.

**Step 6 — Configure OpenAlgo**

Open your OpenAlgo .env file and set:

```
BROKER_API_KEY = 'your_app_key_here'
BROKER_API_SECRET = 'your_app_secret_key_here'
REDIRECT_URL = 'http://127.0.0.1:5000/iiflcapital/callback'
```

Save and restart OpenAlgo.

Integrating OpenAlgo with IIFL Capital'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.


# IndMoney (INDstocks)

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.

### Steps for Integration

IndMoney uses a simple **Bearer Token** authentication model.

To generate a token:

Visit [**https://www.indstocks.com/app/api-trading**](https://www.indstocks.com/app/api-trading)

<figure><img src="/files/XvqACTBIuIkI4FA42gmh" alt=""><figcaption></figcaption></figure>

1. Enter your registered mobile number and login with the help of OTP

<figure><img src="/files/WQvEf9zX6NglGgpdP6UL" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/qwNZVpQR78NdBLKP9QeN" alt=""><figcaption></figcaption></figure>

2. Open the **Algo Trading** above the chart view

<figure><img src="/files/dtp0SSfB5n3w8pHt4yvt" alt=""><figcaption></figcaption></figure>

3. Configure Static IP

<figure><img src="/files/pAfQMKDU1OXUK16k8yvv" alt=""><figcaption></figcaption></figure>

4. Setting up TOTP

TOTP setup is a **one-time** step done on the INDstocks website. You need your phone with an authenticator app (Google Authenticator, Microsoft Authenticator, Authy, 2FAS or Ente Auth).

Step 1 — Open the Access Tokens page

Find the **Setup TOTP** card at the bottom of the page and click **Setup Now**.

<figure><img src="/files/iwIsWNgkMWh3Ml7jBkwo" alt=""><figcaption></figcaption></figure>

Step 2 — Start the setup

A panel opens explaining the three steps. Click **Setup TOTP** at the bottom.

<figure><img src="/files/PXkJkoXF93Ax1wMozYZK" alt=""><figcaption></figcaption></figure>

Step 3 — Scan the QR code

Scan the QR code with your authenticator app, or copy the setup code beneath it and enter it manually.

<figure><img src="/files/2ozOubq8E5j3epyJtLaP" alt=""><figcaption></figcaption></figure>

**Save the setup key somewhere safe before continuing.** It is shown only once and cannot be recovered. If you lose it you must disable TOTP and enrol again.

Click **Continue**

Step 4 — Confirm with a code

Enter the current 6-digit code from your authenticator app and click **Enable Login**

You have **5 minutes** to complete this step. If it expires, start again from Step 1.

<figure><img src="/files/5NGhewACWDxa3S6pn5CB" alt=""><figcaption></figcaption></figure>

Step 5 — Copy your Client ID

TOTP is now enabled. Copy the **Client ID** shown — this is what OpenAlgo needs

<figure><img src="/files/En08DItXub9kzeUkynM5" alt=""><figcaption></figcaption></figure>

This generated clientId will be used in OpenAlgo API Key for all authenticated API requests.

### Environment Configuration

The generated client ID is used as the API Key and keep as blank for API SECRET. Below is a sample configuration for the `.env` file:

```
# Indmoney Broker Configuration
BROKER_API_KEY = 'generated_client_id_after_TOTP_setup' 
BROKER_API_SECRET = '' #Keep it blank intentionally
REDIRECT_URL = 'http://127.0.0.1:5000/indmoney/callback'
```

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.


# IndiaBulls Securities

Work in Progress


# JainamXTS

### **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

#### **Step 1: Create API Applications**

Login to <https://jtrade.jainam.in:5000/dashboard#!/login>

<figure><img src="/files/6Lo0u8YtYY3dxCDyIvO7" alt=""><figcaption></figcaption></figure>

Once logged in:

1. Go to `My App` > `Create New Application`
2. Create two separate apps:

* **Interactive Order API**
* **Market Data API**

<figure><img src="/files/ngaWXOmj1iMzx0VAOgG8" alt=""><figcaption></figcaption></figure>

**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).

<figure><img src="/files/nEz0HcgcJh50rNAMfRkn" alt=""><figcaption></figcaption></figure>

Once submitted, wait for approval from the broker. After approval, the status will turn **Active**.

#### Step 2: Setup Environment Variables <a href="#step-2-setup-environment-variables" id="step-2-setup-environment-variables"></a>

Refer to the `.sample.env` file in your OpenAlgo folder and prepare your `.env` as follows:

```
# 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'
```

Replace the values with actual credentials shown on your developer dashboard once approved.

#### **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!


# Kotak Securities

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.

{% embed url="<https://www.youtube.com/watch?v=AtCCU4I1xSk>" %}

For developers and algo traders looking to use the Kotak API, the integration process generally involves the following steps:

### Step-by-Step Integration

#### Step 1: Prepare Your Trading Credentials

Ensure you have your Kotak Securities Trading User ID and Password ready.

#### Step 2: Register for API Access

1. Navigate to the [Kotak Securities API registration page.](https://neo.kotaksecurities.com/) login with your trading credentials
2. Navigate to: More

<figure><img src="/files/wTWZON6IHyQyJCbUamcC" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/Zzqg996GNhJ4qoTEzdBU" alt=""><figcaption></figcaption></figure>

1. Click "Create Application"
2. Copy the token shown after creation

**Token format example**: ec6a746c-e44b-455e-abf2-c13352b2fc45

#### **Step 3: Register TOTP Authentication**

Register for TOTP from the Menu Section

<figure><img src="/files/04yLcsppfZpNmYJvqY7m" alt=""><figcaption></figcaption></figure>

**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

<figure><img src="/files/gSuCwkqeoMlzpharbREM" alt=""><figcaption></figcaption></figure>

2. 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.

<figure><img src="/files/rSN9EajOfYn4gT9Hf8Zv" alt=""><figcaption></figcaption></figure>

#### 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")

<figure><img src="/files/JytCXZpigAD8QjajEssb" alt=""><figcaption></figcaption></figure>

#### 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

#### 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

### Configuration:

Set up your environment variables in a `.env` file for Kotak's API:

```
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'
```

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.


# Motilal Oswal

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.

### **Getting API Credentials**

#### **Step 1: Access the API Portal**

Visit the Motilal Oswal OpenAPI registration portal:

<https://invest.motilaloswal.com/moAPI/>

#### **Step 2: Register Your Application**

1. Log in with your Motilal Oswal trading credentials

<figure><img src="/files/QAUGL3DojwcANDQ15fAo" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/xTFQuhahXRJYAQa2w0uZ" alt=""><figcaption></figcaption></figure>

2. Navigate to **My APIs**

<figure><img src="/files/ZVjsq4RWAgNhMqbku5Un" alt=""><figcaption></figcaption></figure>

3. Set Up TOTP - Copy the 32-character secret key and Add this key to your preferred authenticator app
4. Click on **Create on API Key**

<figure><img src="/files/bB005jbnTimLh9b1xdcN" alt=""><figcaption></figcaption></figure>

5. Fill in the required details:

* **App Name:** Your application name (e.g., "OpenAlgo Trading")
* **Redirect URL:** `http://127.0.0.1:5000/motilal/callback`

6. Submit the registration

#### **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

#### **Configuration**

Set up your environment variables in a `.env` file for motilal's :

```
# 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
```

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.


# Mstock

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:

### **Step-by-Step Integration**

#### **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.

#### **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**](https://www.mstock.com/trading-api)

<figure><img src="/files/3RMAweuHkPY2PaVxesGM" alt=""><figcaption></figcaption></figure>

* Log in using your trading account credentials.
* **Open Menu** - Click on the hamburger menu icon located at the top-left corner of the screen.

<figure><img src="/files/hWNxqLiDuK1PniX6EY8b" alt=""><figcaption></figcaption></figure>

* **Navigate to Trading APIs** - In the menu, go to **Products** - Then click on **Trading APIs**

<figure><img src="/files/yQ2PHBeQYDpK1tRHCbeh" alt=""><figcaption></figcaption></figure>

* Click **Generate New API Key** and give API Type as Type B.

<figure><img src="/files/5GudenzYYoDSQO2VBMYu" alt=""><figcaption></figcaption></figure>

* **Enable TOTP** - You will see an option labeled "Generate TOTP" - Click on it to begin the TOTP setup process
* Copy your API Key.

#### **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

#### Configuration: <a href="#configuration" id="configuration"></a>

Set up your environment variables in a `.env` file for mstock's API:

```
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'
```

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.


# Nubra

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/> Open Demat

<figure><img src="/files/A0IWsSHxYcn2dricr1Nb" alt=""><figcaption></figcaption></figure>

2. All REST requests require:
   1. **API Key (client\_id)**
   2. **MPIN-based session (MPIN → session token)**

<figure><img src="/files/6X9kGlAgXXkhFJBAlCOZ" alt=""><figcaption></figcaption></figure>

3. Click on the **Profile** icon located at the top-right corner of the page

<figure><img src="/files/uDp9gQaYdbexRlVevAjt" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/0bRa51TcuN9lMCDXAjUn" alt=""><figcaption></figcaption></figure>

3. To Register the static IP ,scroll down the left panel. Select **Resources-Update Static IP- Update - Validate**.

<figure><img src="/files/tXXKrwm7BhaT0sfQVNHE" alt=""><figcaption></figcaption></figure>

### **Environment Configuration**

Once your credentials are generated, configure them in your `.env` file:

```
BROKER_API_KEY = 'your_nubra_clientid'
BROKER_API_SECRET = 'your_nubra_mpin'
REDIRECT_URL = 'http://127.0.0.1:5000/nubra/callback'
```

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.


# Paytm

**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.

***

### Step 1: Create App

1. Go to [Paytm Developer Portal](https://developer.paytmmoney.com/)
2. Click on **Create New App**
3. Choose the following APIs:

   * ✅ **Trading API**
   * ✅ **Live Broadcast API** (optional, but recommended for real-time data)

   <figure><img src="/files/4QqxLoWuv04jTlwbcYPm" alt=""><figcaption></figcaption></figure>
4. Click **Proceed**

<figure><img src="/files/dacck1qRr5mghjZI7B5D" alt=""><figcaption></figcaption></figure>

***

### 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)

<figure><img src="/files/fGdTCzCLmwmyqCp8bR2O" alt=""><figcaption></figcaption></figure>

Click **Create App**

***

### 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**

<figure><img src="/files/4QqxLoWuv04jTlwbcYPm" alt=""><figcaption></figcaption></figure>

Use these credentials in your OpenAlgo broker configuration.

***

### Configuration

Once you have the credentials, add them to your OpenAlgo configuration:

```json
BROKER_API_KEY = 'your_api_key_here'
BROKER_API_SECRET = 'your_api_secret_here'
REDIRECT_URL = 'http://127.0.0.1:5000/paytm/callback'
```

Make sure your local server is running and accessible at the callback URL you defined earlier.

***

#### 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.

***


# 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 portal](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.

***

#### 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.in](https://api.pocketful.in/) and log in with your registered email ID or client ID.

<figure><img src="/files/OYJZ5SZoHKI4ejelleXS" alt=""><figcaption></figcaption></figure>

**Step 2 – Navigate to 'Apps' and Create a New App**\
Click on “+ Create App”.

<figure><img src="/files/kwPMsVbW4YnCYR4s2k0s" alt=""><figcaption></figcaption></figure>

**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**

<figure><img src="/files/52wveVqioK3od1pJN7y7" alt=""><figcaption></figcaption></figure>

Once created, the following credentials will be generated:

* App ID → use as `API_KEY`
* App Secret → use as `API_SECRET`

<figure><img src="/files/z9t25c3rptxnhKo2Htxt" alt=""><figcaption></figcaption></figure>

***

#### 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:

```env
BROKER_API_KEY = 'your_app_id_here'
BROKER_API_SECRET = 'your_app_secret_here'
REDIRECT_URL = 'http://127.0.0.1:5000/pocketful/callback'
```

***

#### Connecting Pocketful to OpenAlgo

Once your `.env` file is populated with the credentials, OpenAlgo can initiate the login flow. This can be triggered locally:

```
http://127.0.0.1:5000/pocketful/login
```

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.

***


# Samco

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.

### **Steps for Integration**

#### **Step 1: Login to Samco website**

Visit <https://web.samco.in/> and login with your client ID/Mobile number.

<figure><img src="/files/VXuxS1o5Nj8iqO2XN7k6" alt=""><figcaption></figcaption></figure>

**Step 2: Navigate to Login to Back Office**

From the dashboard, navigate to the profile dropdown and then to Login to Back Office

<figure><img src="/files/Gb3tdNGnaqNbP6eYX5Sd" alt=""><figcaption></figcaption></figure>

#### **Step 3: Activate Trade API**

Navigate to subscription menu , Samco Trade API

<figure><img src="/files/MNvq3Pu0TBaAS9W5CU6E" alt=""><figcaption></figcaption></figure>

Now activate your subscription

<figure><img src="/files/2GjphzSXa4dTVdGzq4O4" alt=""><figcaption></figcaption></figure>

#### **Step 4 :** **Environment Configuration**

After activating Samco Trade API , configure your samco login crdentials in .env file

```
BROKER_API_KEY = 'your_samco_clientid'
BROKER_API_SECRET = 'your_samco_password'
REDIRECT_URL = 'http://127.0.0.1:5000/sao/callback'
```

#### 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:

<figure><img src="/files/c4Nevc6Lmk4vtrBNcXe3" alt=""><figcaption></figcaption></figure>

**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 :**&#x49;f 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**

<figure><img src="/files/vPDFBtrTEWTKNeNiJS3m" alt=""><figcaption></figcaption></figure>

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

<figure><img src="/files/DerimmVj0XmVBexgwhYC" alt=""><figcaption></figcaption></figure>

**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**

<figure><img src="/files/mRKLSXR5qXAMREKhL2O3" alt=""><figcaption></figcaption></figure>

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**

<figure><img src="/files/BtIWhkZ8u6JhwQ7cabgf" alt=""><figcaption></figcaption></figure>

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.


# Shoonya

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.

## 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/>.

• Enter your Shoonya login credentials.

2\. Generate API Credentials:

<figure><img src="/files/INtupowKEkTZfmE102PT" alt=""><figcaption></figcaption></figure>

• After logging in, navigate to the API Key section in your profile dropdown.

<figure><img src="/files/W8zZNR18STzyCf2Xc6nJ" alt=""><figcaption></figcaption></figure>

• Click on API Key.

<figure><img src="/files/rwisfACzz1hxwgxKFHm5" alt=""><figcaption></figcaption></figure>

• Your client ID and Secret code will be displayed.

3\. Configure OpenAlgo:

• In your OpenAlgo .env file, set the following variables:

```bash
BROKER_API_KEY = 'your_userid_here:::your_ClientId_here'
BROKER_API_SECRET = 'your_Secretcode_here'
REDIRECT_URL = 'https://openalgo.local/shoonya/callback'
```


# RMoney (XTS)

### 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.

#### **Step 1: Create API Applications**

Login to <https://xts.rmoneyindia.co.in:3000/dashboard#!/login>

<figure><img src="/files/Rq25AJIx3qutPq0HC238" alt=""><figcaption></figcaption></figure>

Once logged in:

1. Go to `My App` > `Create New Application`
2. Create two separate apps:

* **Interactive Order API**
* **Market Data API**

<figure><img src="/files/rvFV2HHTmBPa33sIU7nM" alt=""><figcaption></figcaption></figure>

**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).

<figure><img src="/files/5ZsOlFztxd4qV9Skmnm3" alt=""><figcaption></figcaption></figure>

#### Step 2: Setup Environment Variables

Refer to the `.sample.env` file in your OpenAlgo folder and prepare your `.env` as follows:

```
# 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'
```

Replace the values with actual credentials shown on your developer dashboard once approved.

#### **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.


# Tradejini

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.

### Steps for Integration:

#### 1. Log in to the TradeJini Developer Portal

Start by accessing the CubePlus Developer Portal at\
<https://api.tradejini.com/developer-portal/main>

<figure><img src="/files/TMHJqcodeWZzihWgW6HC" alt=""><figcaption></figcaption></figure>

* Click on **Login**.
* You can log in using either:

  * Your **email address and password**, or
  * By clicking the **TradeJini** logo for broker login.

  <figure><img src="/files/ksylb7Ctk7n099bJrfcO" alt=""><figcaption></figcaption></figure>

#### 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

<figure><img src="/files/7fpvZibk1axhWnD3Izo3" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/0VqJRgOoeshqkgfQveYK" alt=""><figcaption></figcaption></figure>

#### 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`.

<figure><img src="/files/OriaZrOSGowNy0bLFfe8" alt=""><figcaption></figcaption></figure>

### Configuration:

Here is how you would typically set up your environment variables in a `.env` file for TradeJini:

```bash
BROKER_API_KEY = 'your_tradejini_clientcode_here'
BROKER_API_SECRET = 'your_tradejini_apikey_here'
REDIRECT_URL = 'http://127.0.0.1:5000/tradejini/callback'
```

These credentials will be used by OpenAlgo to authenticate, fetch session tokens, and access market feeds or place orders.

### 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.


# TradeSmart

TradeSmart is an Indian discount broker known for its flat-fee brokerage model that keeps trading costs low across equity, derivatives, and commodities. The platform offers fast order execution, real-time data, and a clean web and mobile experience. For automation, TradeSmart exposes a secure REST API built on the Noren v2 stack, letting you integrate it with OpenAlgo using a generated App ID and Secret Key.

### Getting API Credentials

To integrate TradeSmart with OpenAlgo, follow these steps to obtain your App ID and Secret Key:

1. Log in to TradeSmart Web • Open <https://web.tradesmartonline.in/login> •\
   Enter your TradeSmart login credentials and your OTP/TOTP.
2. From the top right, open your Profile menu, expand **Tools**, and click **API**.

<figure><img src="/files/CIc8QDWyVdYS87DjPRwS" alt=""><figcaption></figcaption></figure>

3. On the API Dashboard, if you have not set up TOTP yet, click **Add/Setup TOTP** at the top and complete the setup first. API access requires TOTP to be enabled.
4. In the **Generate New API Key** panel, fill out the form:<br>

   • **Name**: a label for the app, for example `Openalgo`\
   • **Primary IP Address**: your static IP (required)\
   • **Secondary IP Address**: optional\
   • **Redirect URL**: `http://127.0.0.1:5000/tradesmart/callback`\
   \
   Tick **I acknowledge the API Terms & Conditions** and click **Generate API Key**.

<figure><img src="/files/6eorUMDAEICfwjj2zbRz" alt=""><figcaption></figcaption></figure>

5. Your new credential now appears under **Active Credentials**. Toggle **Show Credentials** to reveal the **App ID** and **Secret Key**, then copy both and start building!
6. Configure OpenAlgo: • In your OpenAlgo .env file, set the following variables:

```bash
BROKER_API_KEY = 'client_id:::api_key'
BROKER_API_SECRET = 'secret_key'
REDIRECT_URL = 'http://127.0.0.1:5000/tradesmart/callback'
```

Where: • `client_id` is your TradeSmart login/client id (for example `YTNR739`) • `api_key` is the **App ID** generated on the dashboard • `secret_key` is the **Secret Key** revealed via the eye / Show Credentials toggle

> The Redirect URL in your .env must match the Redirect URL configured on the TradeSmart API Dashboard exactly, and your login IP must match the Primary Static IP you registered.


# Upstox

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.

{% embed url="<https://www.youtube.com/watch?v=dMXAmgJ5nUg>" %}

Initiating integration with Upstox's API generally involves several key steps:

### 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 Apps](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

<figure><img src="/files/Nf2A1nNtpwCraOft5A1m" alt=""><figcaption></figcaption></figure>

API Key and API Secret Key generated for the app OpenAlgo

<figure><img src="/files/NIWDf0nooQbrQoqUIQxX" alt=""><figcaption></figcaption></figure>

Save the generated apikey and apisecret. Later we will be adding the apikey in the [environmental variable](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:

```
BROKER_API_KEY = 'your_api_key_here'
BROKER_API_SECRET = 'your_api_secret_here'
REDIRECT_URL = 'http://127.0.0.1:5000/upstox/callback'
```

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.


# Wisdom Capital

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.

***

### Step 1: Create API Applications

Login to the [Wisdom Capital Developer Portal](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**

<figure><img src="/files/rz8J1S2uzJyoUNX9Sy6D" alt=""><figcaption></figcaption></figure>

#### 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.

<figure><img src="/files/p6TPvy7bj0KOSdEG17ns" alt=""><figcaption></figcaption></figure>

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.

<figure><img src="/files/QBdiqwR7YHKQX75TxKdN" alt=""><figcaption></figcaption></figure>

***

### Step 2: Setup Environment Variables

Refer to the `.sample.env` file in OpenAlgo and prepare your `.env` with the following structure:

```env
# 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'
```

Replace placeholder values with actual credentials obtained after app approval.

***

### 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.

***

### 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.


# Zebu

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.<br>

To integrate Zebu’s API, follow the steps below:

### 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/login> and log in with your Zebu credentials.

<figure><img src="/files/DQIc1aXiOJDSBV0YY1kB" alt=""><figcaption></figcaption></figure>

2\. Access API Key Generation

Navigate to Profile ,click on the Client Code at the top right corner and select setting.

<figure><img src="/files/SghI5ImaHf36BWSo3hVF" alt=""><figcaption></figcaption></figure>

click the OAuth Key button and fill in the details and Update.

<figure><img src="/files/yT19g3TZhPf8JopGzwHC" alt=""><figcaption></figcaption></figure>

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:

```
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'
```

Make sure to store your API credentials securely and handle them with care to prevent unauthorized access.

### 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.

<br>

For further assistance or troubleshooting, refer to [Zebu API Documentation](https://zebumyntapi.web.app).


# Zerodha

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.

{% embed url="<https://www.youtube.com/watch?v=uZ6PD6UDxrg>" %}

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.

<figure><img src="/files/62hG8zlksc201t03WP9J" alt=""><figcaption></figcaption></figure>

#### 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.

<figure><img src="/files/W8yVWWh9yFMMajx727Lz" alt=""><figcaption></figcaption></figure>

Here is how you would typically store these details in a `.env` file:

```
BROKER_API_KEY = 'your_api_key_here'
BROKER_API_SECRET = 'your_api_secret_here'
REDIRECT_URL = 'http://127.0.0.1:5000/zerodha/callback'
```

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.


# Exchanges

Delta Exchange


# Delta Exchange

OpenAlgo's `deltaexchange` plugin is the repository's crypto-derivatives adapter. Its `plugin.json` declares broker type `crypto`, exchange `CRYPTO`, and leverage configuration support. The adapter maps supported Delta Exchange order, account, data, and streaming operations into OpenAlgo's normalized interfaces.

Product availability, fees, settlement, API-key requirements, and account eligibility are controlled by Delta Exchange and can change. OpenAlgo does not provide legal or tax classification; verify current exchange documentation and the rules that apply to your location before trading.

### 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.

#### Step 1 – Log in to Delta Exchange India

Visit [delta.exchange](https://delta.exchange) and log in to your account using your Gmail and password

<figure><img src="/files/jwee2L3nYujp8BQYPcmW" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/r3IPRMtJbYgiTubCm8UZ" alt=""><figcaption></figcaption></figure>

#### Step 2 – Navigate to AlgoHub → APIs

<figure><img src="/files/mhwyx9jl8v0Zgc5LzCC3" alt=""><figcaption></figcaption></figure>

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.

#### Step 3 – Create a New API Key

<figure><img src="/files/RTf0faPa8LqUhPOey2Lu" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/6Rt1jp0Wuzho5AjO0UM9" alt=""><figcaption></figcaption></figure>

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

#### 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:

```
BROKER_API_KEY = 'your_api_key_here'
BROKER_API_SECRET = 'your_api_secret_here'
REDIRECT_URL = 'http://127.0.0.1:5000/deltaexchange/callback'
```

The Delta Exchange plugin supports automated crypto-derivatives workflows where the connected account and instrument are available. Protect API credentials, use the exchange's current network controls, handle API failures explicitly, and test with the exchange's test environment before live use. Users remain responsible for verifying the legal, tax, and account rules that apply to their location and activity.


# Getting Started

This Sections help users to install openalgo

* [Windows Desktop](/installation-guidelines/getting-started/windows-installation)
* [Windows Server](/installation-guidelines/getting-started/windows-server-installation)
* [Mac OS Installation](/installation-guidelines/getting-started/mac-os-installation)
* [Amazon Elastic Beanstalk](/installation-guidelines/getting-started/amazon-elastic-beanstalk)
* [Ubuntu Linux Server (No Custom Domain)](/installation-guidelines/getting-started/ubuntu-no-custom-domain)
* [Ubuntu Server with Custom Domain](/installation-guidelines/getting-started/ubuntu-server-installation)
* [Docker Developement](/installation-guidelines/getting-started/docker-development)
* [Testing OpenAlgo in the Cloud (Github Codespace / Google Colab)](/installation-guidelines/getting-started/testing-openalgo-in-cloud)
* [SMTP Settings](/installation-guidelines/getting-started/smtp-settings)
* [TOTP Configuration](/installation-guidelines/getting-started/totp-configuration)
* [Forgot Password](/installation-guidelines/getting-started/forgot-password)
* [Upgrade](/installation-guidelines/getting-started/upgrade)


# Windows Installation

This section provides OpenAlgo Installation Guideline for Windows Users

{% embed url="<https://www.youtube.com/watch?v=Qg-QDc9CczY>" %}

## How to Configure Ngrok for OpenAlgo to Automate Tradingview Strategies

<br>

{% embed url="<https://www.youtube.com/watch?v=nYZGXx3WKhM>" %}

## How to Upgrade OpenAlgo to Latest Version

{% embed url="<https://www.youtube.com/watch?v=GlbvnljYxGE>" %}


# Pre-Requesites

#### 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/downloads>).


# 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`](https://github.com/marketcalls/openalgo)

<figure><img src="/files/vPZwYhIk3NXuEknZUCfJ" alt=""><figcaption></figcaption></figure>


# Install Dependencies

Windows users Navigate to the directory where OpenAlgo is cloned and execute:

`pip install -r requirements.txt`

<figure><img src="/files/spKjDYPoRgumWGW8BmK7" alt=""><figcaption></figcaption></figure>


# Ngrok Config

##

{% embed url="<https://www.youtube.com/watch?v=p9eRs9qK_io>" %}

## Download Ngrok

1. Visit the [Ngrok ](https://ngrok.com/)website and sign up or log in.
2. Navigate to the [download section](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

<figure><img src="/files/J7Cleygi6lyYblOhBeAI" alt=""><figcaption></figcaption></figure>

## 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.

## 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.

<figure><img src="/files/Gd94igmucejsfD4H3nph" alt=""><figcaption></figcaption></figure>

Now, `ngrok` can be run from the command line regardless of the current directory.

## Setting up the Ngrok Free Custom Domain

Go to the **Ngrok portal**, navigate to **Domains -> New Domain**, and create your free domain.

<figure><img src="/files/cDNABEFA5pmH7nDeKgMN" alt=""><figcaption></figcaption></figure>

## 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:

```markup
version: "3"
tunnels:
    flask:
        proto: http
        hostname: <your-ngrok-free-domain>.ngrok-free.app
        addr: 127.0.0.1:5000
agent:
    authtoken: <your-ngrok-auth-token>
```

Replace `<Your Auth Token>` with your actual Ngrok authentication token and `<your-chosen-hostname>` with the hostname you’ve set up.

####

## 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.


# Environmental Variables

OpenAlgo reads configuration from `.env` in the application directory. Create it from the `.sample.env` shipped with the same OpenAlgo release:

```powershell
Copy-Item .sample.env .env
```

Do not copy an old environment block from documentation or another server. The checked-out `.sample.env` is the authoritative list; the current application template contains 108 keys and declares `ENV_CONFIG_VERSION = '1.0.8'`.

## Required Setup

At minimum, review these groups before starting OpenAlgo:

### Broker Credentials

```dotenv
BROKER_API_KEY = 'YOUR_BROKER_API_KEY'
BROKER_API_SECRET = 'YOUR_BROKER_API_SECRET'
BROKER_API_KEY_MARKET = 'YOUR_XTS_MARKET_API_KEY_IF_REQUIRED'
BROKER_API_SECRET_MARKET = 'YOUR_XTS_MARKET_API_SECRET_IF_REQUIRED'
REDIRECT_URL = 'http://127.0.0.1:5000/<broker>/callback'
```

The market-data credentials are used only by broker integrations that require a separate XTS market-data login. Replace `<broker>` in `REDIRECT_URL` with the active plugin's callback path and use the public HTTPS host for remote deployments.

### Security Secrets

```dotenv
APP_KEY = 'GENERATE_A_RANDOM_VALUE'
API_KEY_PEPPER = 'GENERATE_A_DIFFERENT_RANDOM_VALUE'
FERNET_SALT = 'GENERATE_A_RANDOM_SALT'
```

Never reuse values copied from examples, `.sample.env`, another installation, or a public repository. The maintained installers generate per-install secrets. If configuring manually, generate strong independent random values and keep `.env` private.

### Application and Realtime URLs

```dotenv
HOST_SERVER = 'http://127.0.0.1:5000'
FLASK_HOST_IP = '127.0.0.1'
FLASK_PORT = '5000'
WEBSOCKET_HOST = '127.0.0.1'
WEBSOCKET_PORT = '8765'
WEBSOCKET_URL = 'ws://127.0.0.1:8765'
ZMQ_HOST = '127.0.0.1'
ZMQ_PORT = '5555'
```

For a public deployment, terminate TLS at the supported reverse proxy, set `HOST_SERVER` to the public `https://` URL, and expose the raw WebSocket proxy through the documented `/ws` route. Keep ZeroMQ on loopback; it is not an authenticated public protocol.

### Database Paths

```dotenv
DATABASE_URL = 'sqlite:///db/openalgo.db'
LATENCY_DATABASE_URL = 'sqlite:///db/latency.db'
LOGS_DATABASE_URL = 'sqlite:///db/logs.db'
HEALTH_DATABASE_URL = 'sqlite:///db/health.db'
SANDBOX_DATABASE_URL = 'sqlite:///db/sandbox.db'
HISTORIFY_DATABASE_PATH = 'db/historify.duckdb'
```

Historify uses `HISTORIFY_DATABASE_PATH`. The obsolete `HISTORIFY_DATABASE_URL` spelling is not an alias and should be replaced in older `.env` files.

## Broker Allowlist

`VALID_BROKERS` is a comma-separated list of enabled plugin keys. The release template contains all 35 installed plugins:

```dotenv
VALID_BROKERS = 'aliceblue,angel,arrow,compositedge,definedge,deltaexchange,dhan,dhan_sandbox,firstock,fivepaisa,fivepaisaxts,flattrade,fyers,groww,hdfcsky,ibulls,iifl,iiflcapital,indmoney,jainamxts,kotak,motilal,mstock,nubra,paytm,pocketful,rmoney,samco,shoonya,tradejini,tradesmart,upstox,wisdom,zebu,zerodha'
```

Broker presence does not guarantee every optional exchange, GTT, historical-data, or streaming capability. See [Brokers](/connect-brokers/brokers).

## Updating an Existing Installation

1. Back up `.env` securely.
2. Compare its `ENV_CONFIG_VERSION` with the new `.sample.env`.
3. Add new keys and review changed defaults; do not overwrite working broker credentials or generated secrets.
4. Replace obsolete names such as `HISTORIFY_DATABASE_URL` with their current counterparts.
5. Restart OpenAlgo and read startup validation errors before enabling automation.

Do not commit `.env`, paste it into an issue, or include it in a screenshot. It contains broker credentials, application secrets, and deployment policy.


# Start OpenAlgo

From the `openalgo` directory, start the Flask application with the command:

`python app.py`

<figure><img src="/files/d02DeLBuF5mkwhMbyYOm" alt=""><figcaption></figcaption></figure>


# SSL Verification Failed

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”.

<figure><img src="/files/99MomXd0UASz1IrR6Q9A" alt=""><figcaption></figcaption></figure>

2\. **Generate Root Certificates File**: Run the following command to generate the root certificates file.

```bash
certutil -generateSSTFromWU roots.sst
```

\
3\. **Install Root Certificates**: Once the roots.sst file is generated, run the following command to install the certificates.

```bash
certutil -addstore -f root roots.sst
```

**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 GitHub](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!


# Accessing OpenAlgo

After starting the openalgo application, access the OpenAlgo platform by navigating to [http://127.0.0.1:5000](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:5000](http://127.0.0.1:5000/) in your web browser. setup the account using <http://127.0.0.1:5000/setup>

Login into openalgo with the credentials and start using OpenAlgo for Automation.


# Windows Server Installation

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.

{% embed url="<https://www.youtube.com/watch?v=ZkXZ5yoQkUQ>" %}

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:

## Start OpenAlgo using uv on Windows Server 2022

$OpenAlgoPath = "C:\openalgo"

Write-Host "Starting OpenAlgo..." Write-Host "Folder: $OpenAlgoPath"

## Go to OpenAlgo folder

Set-Location $OpenAlgoPath

## 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 }

## Run OpenAlgo

uv run app.py

2. Save the file to your Desktop as StartOpenAlgo.ps1.
3. To start OpenAlgo, Right-click the file and select "Run with PowerShell".


# Windows with Caddy

## Setting Up HTTPS for OpenAlgo on Windows with Caddy

Run OpenAlgo locally on `https://openalgo.local` with a valid SSL certificate, no browser warnings, and zero changes to `app.py`.

<figure><img src="/files/sdlEpfP2pR2U8b9Sj48P" alt=""><figcaption></figcaption></figure>

### Why this setup?

OAuth flows for brokers like shoonya,hdfcsky often require HTTPS redirect URLs. Running OpenAlgo on plain `http://127.0.0.1:5000` works for testing, but production-like local development needs:

* A proper hostname (`openalgo.local` instead of `127.0.0.1`)
* HTTPS with a trusted certificate (no `Not Secure` warnings)
* No code changes to OpenAlgo itself

Caddy handles all of this in front of your Flask app as a reverse proxy.

{% embed url="<https://www.youtube.com/watch?v=ZUFeqixMbp4>" %}

### Prerequisites

* Windows 10 or 11
* OpenAlgo already cloned and running locally
* Administrator access for two one-time setup steps (hosts file edit, certificate trust)

### Step 1: Download Caddy

Go to <https://caddyserver.com/download>

Select:

* **Platform:** Windows
* **Architecture:** amd64

Click **Download**. You'll get a file named something like `caddy_windows_amd64_custom.exe`.

### Step 2: Place and rename the binary

Create a folder to hold Caddy:

```powershell
mkdir C:\caddy
```

Move the downloaded file into `C:\caddy\` and rename it to `caddy.exe`.

In PowerShell:

```powershell
cd C:\caddy
Rename-Item caddy_windows_amd64.exe caddy.exe
```

Verify it works:

```powershell
.\caddy.exe version
```

You should see something like:

```
v2.11.2 h1:iOlpsSiSKqEW+SIXrcZsZ/NO74SzB/ycqqvAIEfIm64=
```

#### Tip: Show file extensions in Windows

If you see `caddy.exe.exe` after renaming, Windows is hiding extensions. Open File Explorer, click **View > Show > File name extensions**, then rename again.

### Step 3: Edit the hosts file

This maps `openalgo.local` to your local machine.

1. Press the Windows key, type **Notepad**
2. Right-click Notepad and select **Run as administrator**
3. In Notepad: **File > Open**
4. Navigate to: `C:\Windows\System32\drivers\etc\`
5. Change the file type dropdown (bottom right) from `Text Documents (*.txt)` to `All Files`
6. Open `hosts`

Add this line:

```
127.0.0.1    openalgo.local
```

A typical hosts file will look like this after editing:

```
# localhost name resolution is handled within DNS itself.
#	127.0.0.1       localhost
#	::1             localhost

# Added by Docker Desktop
192.168.1.6 host.docker.internal
192.168.1.6 gateway.docker.internal

# To allow the same kube context to work on the host and the container:
127.0.0.1 kubernetes.docker.internal
127.0.0.1 openalgo.local
# End of section
```

Save and close.

**Verify the entry works:**

```powershell
ping openalgo.local
```

You should see replies from `127.0.0.1`. If you see `could not find host`, the hosts file did not save correctly. Reopen Notepad as Administrator and try again.

### Step 4: Create the Caddyfile

OpenAlgo ships with a default `Caddyfile` in the project root. If yours is missing, create it.

Navigate to your OpenAlgo project folder:

```powershell
cd D:\openalgo-remote\openalgo
notepad Caddyfile
```

When Notepad asks if you want to create the file, click **Yes**. Paste this:

```
openalgo.local {
    reverse_proxy localhost:5000
}
```

Save and close.

#### Note on the Caddyfile name

The file must be named exactly `Caddyfile` with no extension. If Notepad saves it as `Caddyfile.txt`, rename it:

```powershell
Rename-Item Caddyfile.txt Caddyfile
```

### Step 5: Run Caddy for the first time (Administrator)

The first run installs Caddy's local certificate authority into Windows so browsers trust the auto-generated SSL certificate.

1. Press Windows key, type **PowerShell**
2. Right-click **Windows PowerShell** and select **Run as administrator**
3. Run these commands:

```powershell
cd D:\openalgo-remote\openalgo
C:\caddy\caddy.exe run
```

Windows will show a security dialog asking permission to install a root certificate. Click **Yes**.

You should see logs like:

```
INFO    using adjacent Caddyfile
INFO    adapted config to JSON
INFO    http.auto_https enabling automatic HTTP->HTTPS redirects
INFO    serving initial configuration
```

Leave this terminal open. Caddy is now running.

### Step 6: Start OpenAlgo in a separate terminal

Open another PowerShell window (no admin needed). Navigate to the project folder and start OpenAlgo:

```powershell
cd D:\openalgo-remote\openalgo
uv run app.py
```

You should see:

```
╭─── OpenAlgo v2.0.1.0 ──────────────────────────────╮
│                                                    │
│        Your Personal Algo Trading Platform         │
│                                                    │
│ Endpoints                                          │
│ Web App    http://127.0.0.1:5000                   │
│ WebSocket  ws://127.0.0.1:8765                     │
│ Docs       https://docs.openalgo.in                │
│                                                    │
│ Status     Ready                                   │
│                                                    │
╰────────────────────────────────────────────────────╯
```

### Step 7: Open OpenAlgo in your browser

Go to: **<https://openalgo.local>**

You should see the OpenAlgo login screen with a valid lock icon next to the URL. No certificate warnings.

### Step 8: Update broker callback URLs

Now that OpenAlgo runs on HTTPS, update the redirect URL in your `.env` file:

```dotenv
REDIRECT_URL = 'https://openalgo.local/shoonya/callback'
```

Match this exactly in your broker's developer console:

* **Shoonya API Portal:** Edit your app and set the Redirect URL to `https://openalgo.local/shoonya/callback`

Restart OpenAlgo after editing `.env`.

All the brokers the procedure remains the same.

### Daily workflow after setup

Once everything is set up, your daily workflow is just two terminals:\
\
Run this from the openalgo root folder

**Terminal 1 (Caddy):**

```powershell
C:\caddy\caddy.exe run
```

**Terminal 2 (OpenAlgo):**

```powershell
uv run app.py
```

Press `Ctrl+C` in either terminal to stop. Nothing runs in the background as a service.

### Optional: Single-command launcher

Create `start.bat` in your OpenAlgo folder:

```batch
@echo off
start "Caddy" cmd /k C:\caddy\caddy.exe run
start "OpenAlgo" cmd /k uv run app.py
```

Double-click to launch both. Close both terminal windows when done.

### Troubleshooting

#### Browser shows ERR\_CONNECTION\_REFUSED

Make sure both terminals are running. Caddy must be running for HTTPS to work, and OpenAlgo must be running for Caddy to have something to proxy to.

#### Certificate warning in browser

This means Caddy's root CA is not trusted. Stop Caddy, then run as Administrator:

```powershell
C:\caddy\caddy.exe trust
```

Accept the Windows prompt. Restart Caddy.

#### Port 443 already in use

Another service is using the HTTPS port. Common culprits:

```powershell
netstat -ano | findstr :443
```

If IIS or `World Wide Web Publishing Service` is using it, stop the service. Or change Caddy to use a different port:

```
openalgo.local:8443 {
    reverse_proxy localhost:5000
}
```

Then access OpenAlgo at `https://openalgo.local:8443`.

#### Caddy says "Caddyfile input is not formatted"

Cosmetic warning only. To fix, run:

```powershell
C:\caddy\caddy.exe fmt --overwrite Caddyfile
```

#### Hosts file ping does not resolve

The most common cause is saving `hosts` as `hosts.txt`. Open `C:\Windows\System32\drivers\etc\` in File Explorer with extensions visible (View > Show > File name extensions). If you see `hosts.txt`, delete it and edit the original `hosts` file again.

### Removing the setup

If you want to undo everything:

1. Stop Caddy and OpenAlgo
2. Untrust the Caddy CA: `C:\caddy\caddy.exe untrust` (as Administrator)
3. Remove the `127.0.0.1 openalgo.local` line from `C:\Windows\System32\drivers\etc\hosts`
4. Delete `C:\caddy\`
5. Delete the `Caddyfile` from your OpenAlgo folder

### Summary

You now have OpenAlgo running on `https://openalgo.local` with a fully trusted SSL certificate. No background services, no code changes to OpenAlgo, and OAuth callbacks work cleanly with broker APIs that require HTTPS redirect URLs.


# Mac OS Installation

{% embed url="<https://www.youtube.com/watch?v=4wBi0YQRM_4>" %}


# Pre-Requesties

* **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).


# 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`](https://github.com/marketcalls/openalgo)

<figure><img src="/files/eQpXBazRx9L8YFgHTgMu" alt=""><figcaption></figcaption></figure>


# Install Dependencies

Windows users Navigate to the directory where OpenAlgo is cloned and execute:

`pip3 install -r requirements.txt`

<figure><img src="/files/Iruw2v6qWFRKNzGXEBmH" alt=""><figcaption></figcaption></figure>


# Ngrok Config

## Download Ngrok

1. Visit the [Ngrok ](https://ngrok.com/)website and sign up or log in.
2. Navigate to the [download section](https://dashboard.ngrok.com/get-started/setup/macos) and select the version for Mac OS.
3. Install Ngrok using the brew command

```
brew install ngrok/ngrok/ngrok
```

4. Copy the Auth Token and keep it separately later this will be used to set the **ngrok.yml** config file

<figure><img src="/files/8zQXkapqN1E5f7K8hEVb" alt=""><figcaption></figcaption></figure>

## Setting up the Ngrok Free Custom Domain

Go to the **Ngrok portal**, navigate to **Domains -> New Domain**, and create your free domain.

<figure><img src="/files/cDNABEFA5pmH7nDeKgMN" alt=""><figcaption></figcaption></figure>

## 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:

```markup
version: "3"
tunnels:
    flask:
        proto: http
        hostname: <your-ngrok-free-domain>.ngrok-free.app
        addr: 127.0.0.1:5000
agent:
    authtoken: <your-ngrok-auth-token>
```

Replace `<Your Auth Token>` with your actual Ngrok authentication token and `<your-chosen-hostname>` with the hostname you’ve set up.

## 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.


# Environmental Variables

Rename the `.sample.env` file located in `openalgo` folder to `.env`

Update the `.env` with your specific configurations as shown in the provided template.

### Sample Environmental File

```python
# Broker Configuration
BROKER_API_KEY = 'YOUR_BROKER_API_KEY'
BROKER_API_SECRET = 'YOUR_BROKER_API_SECRET'

REDIRECT_URL = 'http://127.0.0.1:5000/<broker>/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
```

###


# Start OpenAlgo

From the `openalgo` directory, start the Flask application with the command:

`python3 app.py`

<figure><img src="/files/GLIb50522El9gCdY6UVm" alt=""><figcaption></figcaption></figure>


# Install certifi

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:

These examples use Python 3.12, the minimum version supported by the current OpenAlgo build.

**1. Locate the Correct Path of Python Installation:**

To find the Python 3.12 executable, open Terminal and run:

```
which python3.12
```

Locate and Run the Install Certificates Script:

<figure><img src="/files/aEIqVIqobMyElSR9mViP" alt=""><figcaption></figcaption></figure>

Once you have the correct Python 3.12 path, locate the `Install Certificates.command` helper if your installer supplied it. Homebrew installations commonly use the system certificate store and `certifi` instead.

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:

2. **Install certifi:**

```
python3.12 -m pip install certifi
```

3. **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:

```
export SSL_CERT_FILE=$(python3.12 -m certifi)
```

4. **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.<br>

If a python.org installation includes `Install Certificates.command`, it is typically under `/Applications/Python 3.12/`. Run the helper for the same interpreter used by OpenAlgo.

Ensure that you are using the correct paths and commands based on how and where Python is installed on your system.


# Accessing OpenAlgo

After starting the openalgo application, access the OpenAlgo platform by navigating to [http://127.0.0.1:5000](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:5000](http://127.0.0.1:5000/) in your web browser. setup the account using <http://127.0.0.1:5000/setup>

Login into openalgo with the credentials and start using OpenAlgo for Automation.


# Amazon Elastic Beanstalk

## Hosting OpenAlgo in the Cloud using Amazon AWS Elastic Beanstalk

\
[OpenAlgo](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)

{% embed url="<https://www.youtube.com/watch?v=MWOuMUzWGgI>" %}

**Steps by Step Instruction to host OpenAlgo in Amazon Cloud with custom domain**

**Clone the OpenAlgo Repository:**

* Go to the [OpenAlgo GitHub repository](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**](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 Console](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 a Python platform branch that provides Python 3.12 or newer.
* 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.

<figure><img src="/files/posynS3AN8uqyxAYTTDM" alt=""><figcaption></figcaption></figure>

**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”.

<figure><img src="/files/E4J7M4Ha5JxjgHQjI5Dp" alt=""><figcaption></figcaption></figure>

**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.

<figure><img src="/files/wShp7vr4gIEs2GxfLy3X" alt=""><figcaption></figcaption></figure>

**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”.

<figure><img src="/files/nrmzyBae4xWuBj03eXJs" alt=""><figcaption></figcaption></figure>

**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”.

<figure><img src="/files/Tqq7wskixEJrtSVZNyfM" alt=""><figcaption></figcaption></figure>

**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.

<figure><img src="/files/ZbhoNyEwQ4bTsZVzv3Qg" alt=""><figcaption></figcaption></figure>

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.

<figure><img src="https://i0.wp.com/www.marketcalls.in/wp-content/uploads/2024/06/image-17-1024x466.png?resize=1024%2C466&#x26;ssl=1" alt="" height="466" width="1024"><figcaption></figcaption></figure>

**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.

<figure><img src="https://i0.wp.com/www.marketcalls.in/wp-content/uploads/2024/06/image-18-1024x524.png?resize=1024%2C524&#x26;ssl=1" alt="" height="524" width="1024"><figcaption></figcaption></figure>

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.


# BellGlobal

Deploy OpenAlgo on a BellGlobal Open Algo VPS in less than 5 minutes.

{% embed url="<https://www.youtube.com/watch?v=xLMFDZfzo1k>" %}

This video walks through the complete setup process, from provisioning the VPS to launching your OpenAlgo dashboard. The BellGlobal Open Algo VPS is preconfigured so you can get started quickly without spending time on server setup.

OpenAlgo is a free and open source algorithmic trading platform that supports more than 33 Indian brokers and integrates with TradingView, Amibroker, Python, Excel, and other popular trading tools.

In this video, you will learn:

• How to choose and activate a BellGlobal Open Algo VPS\
• How to connect to the VPS using Remote Desktop\
• How to configure your broker API credentials\
• How to identify your static IP address for broker whitelisting\
• How to launch OpenAlgo and access your trading dashboard

Useful Links

BellGlobal Open Algo VPS\
<https://bellglobal.in/open-algo-vps>


# HouseOfFoss

One-Click OpenAlgo Installation with House Of FOSS

***

## 🧩 Installing OpenAlgo in the Cloud with House of FOSS

### 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**](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.

{% embed url="<https://www.youtube.com/watch?v=GgPPwX3M2FM>" %}

***

### 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.

***

### 2. Getting Started

1. Visit [**houseoffoss.com**](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.

***

### 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**.

***

### 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.

***

### 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             |

***

### 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**.

***

### 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.

***

#### 🔗 Useful Links

* 🌐 [House of FOSS](https://www.houseoffoss.com/)
* 💻 [OpenAlgo GitHub](https://github.com/marketcalls/openalgo)
* 💬 [Join Discord Community](https://openalgo.in/discord)


# Ubuntu (No Custom Domain)

OpenAlgo can be installed on an Ubuntu desktop or laptop by preparing the system, downloading the source code, configuring broker credentials, and launching the application locally.

For traders using an Indian broker, static IP configuration is now mandatory for retail algo trading under SEBI regulations. This must be completed before using transactional broker APIs for live order placement.

{% embed url="<https://www.youtube.com/watch?v=gqlAefDwAtw>" %}

### System Requirements

Make sure the following are available on your Ubuntu system before you begin.

Python 3

Git

UV package manager

Visual Studio Code or any code editor

Internet connection

Broker API credentials

For Indian brokers, a static IPv4 address

### Step 1 Create a Project Folder

Create a new folder on your Ubuntu desktop or laptop for the OpenAlgo project. The folder name can be anything you prefer.

Open this folder in your code editor.

### Step 2 Check Required Software

Open the terminal inside the project folder and confirm that Python 3, Git, and UV are installed on your system.

These are the core requirements needed to run OpenAlgo.

### Step 3 Download the OpenAlgo Source Code

Go to the OpenAlgo portal and copy the GitHub repository URL.

Download the OpenAlgo source code into your project folder.

This gives you the full local project needed for installation and configuration.

### Step 4 Create the Environment File

Inside the downloaded project, locate the sample environment file.

Create a copy of this sample file and rename it as the main environment file.

This file is used to store your broker related settings and credentials.

### Step 5 Configure Broker Credentials

Open the environment file and update the required values.

You will typically need to enter the following details.

Broker name

Redirect URL

Broker API key

Broker API secret

The exact values and process depend on the broker you use.

### Step 6 Generate API Credentials from Your Broker

Log in to your broker’s developer portal and create an app for API access.

Depending on the broker, you may need to provide an app name, redirect URL, and other broker specific information.

After the app is created, copy the API key and API secret and paste them into the environment file.

### Step 7 Configure Static IP for Indian Brokers

If you are using an Indian broker, static IP setup is mandatory for retail algo trading under SEBI regulations.

Your broker must whitelist the fixed IP address from which your orders originate. This applies to transactional APIs used for placing, modifying, cancelling, basket, or split orders.

Important points to note

Orders must originate from a whitelisted static IP

This requirement applies from 1 April 2026 for retail algo traders using broker APIs

Most brokers provide primary and secondary IP slots

IP changes are generally allowed only once per week

Home internet connections often use dynamic IPs and are not reliable for this purpose

A static IPv4 address is required because brokers do not generally support IPv6 whitelisting

For desktop users, one option is to request a static IP from the internet service provider. Another option is to use a VPS, which usually includes a static IP by default.

More details are available on the OpenAlgo static IP page.

### Step 8 Save Changes Properly

After updating the environment file, save it carefully.

Whenever you change the API key, API secret, or related broker settings, save the file and restart the application so the changes take effect.

### Step 9 Start OpenAlgo

Launch OpenAlgo from the project directory.

On the first run, the application will create its environment, install required libraries, and start the local service.

The first launch may take longer than later launches.

OpenAlgo runs locally on port 5000, and you can access it through your browser after startup.

### Step 10 Complete First Time Account Setup

When OpenAlgo opens for the first time, you will be taken to the setup screen.

Create your account using the required details.

Username

Email address

Password

Password confirmation

Use a strong password that meets the platform requirements.

### Step 11 Log In to OpenAlgo

After the initial account setup, log in using your OpenAlgo credentials.

This is your application login and is separate from your broker authentication.

### Step 12 Connect Your Broker Account

After logging in, connect your broker account from within OpenAlgo.

Broker login is usually a manual step. In the workflow described, the broker session remains active until the next day at 3:00 AM, after which you must log in again.

### Step 13 Wait for Platform Initialization

After connecting the broker, OpenAlgo opens the main dashboard.

At this stage, the platform may begin downloading the master contract. Wait until this process finishes completely.

You should only proceed when the dashboard shows that the system is ready.

Do not start automation until the platform indicates readiness.

### Common Mistakes to Avoid

Do not forget to save the environment file after editing credentials

Do not forget to restart the application after changing broker settings

Do not use a dynamic home IP for Indian broker transactional APIs

Do not begin automation before the dashboard is fully ready

Do not assume the same credential setup process applies to every broker

### Conclusion

Installing OpenAlgo on Ubuntu Desktop involves preparing the system, downloading the project, configuring the environment file, adding broker credentials, setting up static IP when required, launching the application, and completing the first time login flow.

For Indian brokers, static IP compliance is now an essential part of setup and must be completed before live API based trading.


# Ubuntu Server Installation

###

{% embed url="<https://www.youtube.com/watch?v=Po7bxFsUPyQ>" %}

#### Prerequisites

**System Requirements**

* Ubuntu Server (22.04 LTS or later recommended)
* Minimum 2 GB RAM (or 0.5 GB + 2 GB swap — the installer auto-creates the swap file if needed)
* 1 GB free disk
* 1 vCPU
* Clean installation recommended

OpenAlgo runs on Ubuntu, Debian, Raspbian, RHEL, Rocky, AlmaLinux, Amazon Linux, Fedora, and Arch - the installation script auto-detects the distro and uses the right package manager. The flow below uses Ubuntu as the example.

**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

     ```
     Type: A
     Name: yourdomain.com
     Content: YOUR_SERVER_IP
     Proxy status: Proxied
     ```
   * Add a CNAME record for `www` (optional — not required for `sub.yourdomain.com`)

     ```
     Type: CNAME
     Name: www
     Content: yourdomain.com
     Proxy status: Proxied
     ```
3. **SSL/TLS Configuration in Cloudflare**
   * Go to SSL/TLS section
   * Set encryption mode to **Full (strict)**

**Broker Setup (Required)**

* Obtain your broker's API credentials per the OpenAlgo documentation:
  * API Key
  * API Secret
* Prepare the redirect URL based on your domain and broker name:

```
# Example - root domain yourdomain.com with Zerodha
https://yourdomain.com/zerodha/callback

# Example - subdomain sub.yourdomain.com with Angel
https://sub.yourdomain.com/angel/callback
```

#### Login to the Ubuntu Server

```bash
# Connect to your Ubuntu server via SSH
# Example: ssh root@134.56.76.23

ssh user@your_server_ip
```

#### Installation Steps

**1. Download the Installation Script**

```bash
mkdir -p ~/openalgo-install
cd ~/openalgo-install

wget https://raw.githubusercontent.com/marketcalls/openalgo/main/install/install.sh
chmod +x install.sh
```

**2. Run the Installation Script**

```bash
sudo ./install.sh
```

The script will interactively prompt you for:

* Your domain name (root domains and subdomains both supported)
* Broker selection from the 35 installed plugins
* Broker API credentials (Key + Secret)
* For XTS-based brokers (5paisa XTS, Compositedge, IIFL, etc.): additional market-data API key/secret
* **Enable Remote MCP?** (y/N) — opt-in to expose `/mcp` and `/oauth/*` for hosted AI clients (Claude.ai, ChatGPT) at the same domain. You can also enable this later from the admin UI

The installer will:

* Detect your distro (Ubuntu / Debian / RHEL / Fedora / Arch / Amazon Linux) and use the right package manager
* Install required packages, including Chromium (used for Telegram /chart rendering — non-fatal if unavailable)
* Install the `uv` package manager (via snap on Ubuntu, or the Astral standalone installer on PEP 668 systems like Ubuntu 24.04+)
* Configure Nginx with HTTPS via Let's Encrypt (Certbot)
* Set up the OpenAlgo application under `/var/python/openalgo`
* Create the systemd unit `openalgo.service`
* Generate timestamped installation logs in `~/openalgo-install/logs/`

**Default Layout (single deployment)**

After a successful run, the install lives at:

```
/var/python/openalgo/                  cloned repo
/var/python/openalgo/.venv/            uv-managed Python virtual environment
/var/python/openalgo/.env              configuration
/var/python/openalgo/openalgo.sock     Gunicorn Unix socket
/etc/systemd/system/openalgo.service   systemd unit
/etc/nginx/sites-available/openalgo.conf   Nginx vhost (stable name across domain changes)
```

The Nginx vhost name `openalgo.conf` is intentionally fixed — `install/change-domain.sh` updates `server_name` in place rather than renaming the file.

**Multi-Domain Deployment (Optional)**

The default `install.sh` is single-deploy per server. If you need 2+ OpenAlgo instances side by side (different broker per instance, etc.), use the dedicated multi-deploy installer:

```bash
wget https://raw.githubusercontent.com/marketcalls/openalgo/main/install/install-multi.sh
chmod +x install-multi.sh
sudo ./install-multi.sh
```

Multi-deploy installs use a per-deployment layout:

```
/var/python/openalgo-flask/<domain-broker>/openalgo/
/var/python/openalgo-flask/<domain-broker>/venv/
openalgo-<domain-broker>.service
```

Each deployment gets its own service, configuration, virtual environment, SSL certificate, and log file. The single-deploy `update.sh` and `change-domain.sh` scripts also handle this layout transparently — they detect the simple path first and fall back to scanning `/var/python/openalgo-flask/`.

**3. Verify the Installation**

1. **Check service status**

   ```bash
   sudo systemctl status openalgo
   ```
2. **Test the Nginx configuration**

   ```bash
   sudo nginx -t
   ls -l /etc/nginx/sites-enabled/openalgo.conf
   ```
3. **Open the dashboard** at `https://yourdomain.com`
4. **View installation log**

   ```bash
   ls -l ~/openalgo-install/logs/
   cat ~/openalgo-install/logs/install_YYYYMMDD_HHMMSS.log
   ```

#### Remote MCP

Remote MCP exposes `/mcp` and `/oauth/*` so hosted AI clients (claude.ai, chatgpt.com) can connect to your OpenAlgo install over HTTPS. Local stdio MCP (Claude Desktop, Cursor, Windsurf) is unaffected — it works regardless of this setting.

You can enable Remote MCP two ways:

1. **At install time** — answer `y` when `install.sh` prompts. The installer sets `MCP_HTTP_ENABLED='True'` and `MCP_PUBLIC_URL='https://yourdomain.com'` in `.env` for you.
2. **From the admin UI** — visit `https://yourdomain.com/admin/remote-mcp`. The settings card at the top of the page lets you flip Remote MCP on or off, edit the public HTTPS origin, and adjust the OAuth posture toggles. Saving writes the new values to `.env`; a yellow banner then prompts you to restart the service:

   ```bash
   sudo systemctl restart openalgo
   ```

   The banner clears automatically once the running process picks up the new values.

**Available Toggles**

| Toggle                      | `.env` key                      | Default                   |
| --------------------------- | ------------------------------- | ------------------------- |
| Remote MCP enabled          | `MCP_HTTP_ENABLED`              | `False`                   |
| Auto-approve hosted clients | `MCP_OAUTH_REQUIRE_APPROVAL`    | `False` (auto-approve ON) |
| Allow order placement       | `MCP_OAUTH_WRITE_SCOPE_ENABLED` | `True`                    |

The MCP URL to give your AI client is the same as your dashboard URL with `/mcp` appended — e.g. `https://yourdomain.com/mcp`. The admin page displays it with a copy button when MCP is configured.

#### Troubleshooting

**Common Issues**

1. **SSL certificate issues**

   ```bash
   sudo journalctl -u certbot

   # Re-run Certbot manually
   sudo certbot --nginx -d yourdomain.com
   ```
2. **Application not starting**

   ```bash
   # View live logs
   sudo journalctl -fu openalgo

   # Last 100 lines
   sudo journalctl -n 100 -u openalgo

   # Restart
   sudo systemctl restart openalgo
   ```
3. **Nginx issues**

   ```bash
   # Test config
   sudo nginx -t

   # Error log
   sudo tail -f /var/log/nginx/error.log

   # Access log
   sudo tail -f /var/log/nginx/access.log

   # Reload after config changes
   sudo systemctl reload nginx
   ```
4. **Installation logs**

   ```bash
   ls -l ~/openalgo-install/logs/
   cat ~/openalgo-install/logs/$(ls -t ~/openalgo-install/logs/ | head -1)
   ```
5. **`uv` install failed with `externally-managed-environment`**

   This is PEP 668 enforcement on Ubuntu 24.04+ / Debian 12+. The current `install.sh` falls through to the Astral standalone installer automatically; if you're on an older copy, refresh the script and re-run:

   ```bash
   cd ~/openalgo-install
   rm -f install.sh
   wget https://raw.githubusercontent.com/marketcalls/openalgo/main/install/install.sh
   chmod +x install.sh
   sudo ./install.sh
   ```
6. **Inspect the install directly**

   ```bash
   # Repo
   ls /var/python/openalgo

   # Effective configuration
   sudo cat /var/python/openalgo/.env

   # Application logs
   sudo tail -f /var/python/openalgo/log/openalgo_$(date +%F).log

   # JSON-formatted error log (always-on)
   sudo tail -f /var/python/openalgo/log/errors.jsonl
   ```

**Multi-Domain Deployment Notes**

If you ran `install-multi.sh` (per-deployment layout), substitute the deployment-specific names everywhere:

```bash
# List all OpenAlgo services on this host
systemctl list-units 'openalgo*'

# Manage a specific deployment (example: trading1.yourdomain.com + Fyers)
sudo systemctl status openalgo-trading1-yourdomain-com-fyers
sudo journalctl -fu openalgo-trading1-yourdomain-com-fyers

# Per-deployment install directories
ls /var/python/openalgo-flask/
```

#### Updating

```bash
cd ~/openalgo-install
wget https://raw.githubusercontent.com/marketcalls/openalgo/main/install/update.sh
chmod +x update.sh
sudo ./update.sh
```

The update script detects both layouts (single-deploy at `/var/python/openalgo` and legacy multi-deploy under `/var/python/openalgo-flask/`) and asks which to update if multiple are present. It runs `git pull`, `uv sync`, and restarts the service.

#### Changing the Domain

```bash
cd ~/openalgo-install
wget https://raw.githubusercontent.com/marketcalls/openalgo/main/install/change-domain.sh
chmod +x change-domain.sh
sudo ./change-domain.sh
```

The script updates `.env` (`HOST_SERVER`, `WEBSOCKET_URL`), the Nginx vhost's `server_name`, requests a new Let's Encrypt certificate for the new domain, and restarts the service.

#### Security Notes

1. **Firewall**

   The installer configures UFW to allow only SSH, HTTP, and HTTPS. Open additional ports as needed:

   ```bash
   sudo ufw allow <port_number>
   ```
2. **SSL/TLS**
   * Certificates are auto-renewed by Certbot
   * The Nginx vhost uses TLS 1.2/1.3, modern ciphers, OCSP stapling, and HSTS
   * Keep the system patched:

     ```bash
     sudo apt update && sudo apt upgrade -y
     ```
3. **`.env` file**

   Contains `APP_KEY`, `API_KEY_PEPPER`, and broker credentials. The installer sets `chmod 600` on it and ownership to the service user (`www-data` on Ubuntu/Debian, `nginx` on RHEL, `http` on Arch). Never commit this file or expose it via Nginx.
4. **Auto-logout**

   Indian broker tokens expire daily at \~3:00 AM IST and the app forces a re-login at that time. For 24/7 crypto brokers (Delta Exchange), the installer detects this and disables the auto-logout.
5. **Single user per deployment**

   OpenAlgo is designed for one trader per server. There is no multi-user model — server access equals full control of the broker session. Don't share the host.

#### Post-Installation

1. Configure your broker login on the dashboard
2. Set up monitoring and Telegram alerts if desired
3. Periodically review `log/errors.jsonl` for issues
4. Apply security updates regularly

#### Support

* GitHub: [github.com/marketcalls/openalgo](https://github.com/marketcalls/openalgo)
* Documentation: [docs.openalgo.in](https://docs.openalgo.in)
* Discord: [openalgo.in/discord](https://www.openalgo.in/discord)

Remember to:

* Regularly back up your `.env` file and the `db/` directory
* Monitor system resources
* Keep the system updated
* Review security best practices

***


# Docker + Custom Domain

## OpenAlgo Docker Installation Script

### Quick Start

This script provides a simplified, automated installation of OpenAlgo using Docker on Ubuntu/Debian systems with custom domain and SSL.

#### One-Line Installation

```bash
wget https://raw.githubusercontent.com/marketcalls/openalgo/refs/heads/main/install/install-docker.sh && chmod +x install-docker.sh && ./install-docker.sh
```

#### Prerequisites

* Fresh Ubuntu 20.04+ or Debian 11+ server
* Root access OR non-root user with sudo privileges
* Domain name pointed to your server IP
* Server with at least 1GB RAM (2GB recommended)

{% embed url="<https://www.youtube.com/watch?v=cpD_QRKlq9o>" %}

#### Installation Steps

**Option 1: As Non-Root User (Recommended)**

```bash
# If you're logged in as root, create a non-root user first
adduser openalgo
usermod -aG sudo openalgo
su - openalgo

# Download and run the script
wget https://raw.githubusercontent.com/marketcalls/openalgo/refs/heads/main/install/install-docker.sh
chmod +x install-docker.sh
./install-docker.sh
```

**Option 2: As Root User**

```bash
# Download and run directly
wget https://raw.githubusercontent.com/marketcalls/openalgo/refs/heads/main/install/install-docker.sh
chmod +x install-docker.sh
./install-docker.sh
# (Confirm when prompted to proceed as root)
```

**Note:** While the script works as root, using a non-root user is recommended for better security in production environments.

#### Follow the Prompts

The script will ask you for:

* Domain name (e.g., demo.openalgo.in)
* Broker name from the supported list
* Broker API credentials (key and secret)
* Market data credentials (for XTS brokers only)
* Email for SSL certificate notifications
* Confirmation to proceed

#### What the Script Does

1. ✅ Updates system packages
2. ✅ Installs Docker & Docker Compose
3. ✅ Installs Nginx web server
4. ✅ Installs Certbot for SSL
5. ✅ Clones OpenAlgo repository to `/opt/openalgo`
6. ✅ Configures environment variables
7. ✅ Sets up firewall (UFW)
8. ✅ Obtains SSL certificate from Let's Encrypt
9. ✅ Configures Nginx with SSL and WebSocket support
10. ✅ Builds and starts Docker container
11. ✅ Creates management helper scripts

**Installation typically takes 5-10 minutes.**

#### After Installation

1. Visit `https://yourdomain.com` in your browser
2. Create your admin account
3. Login to OpenAlgo
4. Complete broker authentication using OAuth

#### Management Commands

The installation creates these helper commands:

```bash
# View application status
openalgo-status

# View live logs (follow mode)
openalgo-logs

# Restart application
openalgo-restart

# Create backup
openalgo-backup
```

#### Docker Commands

```bash
# Navigate to installation directory
cd /opt/openalgo

# Restart container
sudo docker compose restart

# Stop container
sudo docker compose stop

# Start container
sudo docker compose start

# View logs
sudo docker compose logs -f

# Rebuild from scratch
sudo docker compose down
sudo docker compose build --no-cache
sudo docker compose up -d
```

#### File Locations

| Item             | Location                                    |
| ---------------- | ------------------------------------------- |
| Installation     | `/opt/openalgo`                             |
| Configuration    | `/opt/openalgo/.env`                        |
| Database         | Docker volume `openalgo_db`                 |
| Application Logs | `/opt/openalgo/log`                         |
| Broker Logs      | `/opt/openalgo/logs`                        |
| Nginx Config     | `/etc/nginx/sites-available/yourdomain.com` |
| SSL Certificates | `/etc/letsencrypt/live/yourdomain.com/`     |
| Backups          | `/opt/openalgo-backups/`                    |

#### Updating OpenAlgo

```bash
cd /opt/openalgo

# Create backup first
openalgo-backup

# Stop container
sudo docker compose down

# Pull latest code
sudo git pull origin main

# Rebuild and restart
sudo docker compose build --no-cache
sudo docker compose up -d

# Verify
openalgo-status
```

#### Troubleshooting

**Container not starting:**

```bash
# Check container status
sudo docker ps -a

# View detailed logs
sudo docker compose logs -f

# Check container health
sudo docker inspect openalgo-web --format='{{.State.Health.Status}}'
```

**Permission errors with logs:**

```bash
# Fix log directory permissions
cd /opt/openalgo
sudo chown -R 1000:1000 log logs
sudo docker compose restart
```

**WebSocket connection issues:**

```bash
# Check if ports are listening
sudo netstat -tlnp | grep -E ':(5000|8765)'

# Test WebSocket connection
curl -i -N \
  -H "Connection: Upgrade" \
  -H "Upgrade: websocket" \
  https://yourdomain.com/ws
```

**Nginx issues:**

```bash
# Test configuration
sudo nginx -t

# View error logs
sudo tail -f /var/log/nginx/yourdomain.com_error.log

# Restart Nginx
sudo systemctl restart nginx
```

**SSL certificate issues:**

```bash
# Test renewal
sudo certbot renew --dry-run

# Force renewal
sudo certbot renew --force-renewal

# Check certificate status
sudo certbot certificates
```

**Docker issues:**

```bash
# Check Docker status
sudo systemctl status docker

# Restart Docker
sudo systemctl restart docker

# View Docker logs
sudo journalctl -u docker -f
```

#### Firewall Configuration

The script automatically configures UFW:

* **Port 22** (SSH) - Open
* **Port 80** (HTTP) - Open (for SSL renewal)
* **Port 443** (HTTPS) - Open
* **Ports 5000, 8765** - Only accessible via localhost (Docker ports)

#### Security Best Practices

1. **Change default credentials** immediately after first login
2. **Keep system updated**:

   ```bash
   sudo apt update && sudo apt upgrade -y
   ```
3. **Monitor logs regularly**:

   ```bash
   openalgo-logs
   ```
4. **Setup automated backups**: Create a cron job

   ```bash
   # Backup daily at 2 AM
   crontab -e
   # Add: 0 2 * * * /usr/local/bin/openalgo-backup
   ```
5. **Use strong passwords** for your OpenAlgo account
6. **Never share broker credentials** with anyone
7. **Review firewall rules periodically**:

   ```bash
   sudo ufw status
   ```

#### Cloudflare Setup (Optional)

For additional security and CDN benefits:

1. **Add domain to Cloudflare**
   * Sign up at cloudflare.com
   * Add your domain
2. **Update DNS**
   * In Cloudflare DNS settings:
   * Create A record pointing to your server IP
   * Enable proxy (orange cloud icon)
3. **Configure SSL/TLS**
   * Go to SSL/TLS settings
   * Set mode to **"Full (strict)"**
   * Enable "Always Use HTTPS"
4. **Enable WebSockets**
   * Go to Network settings
   * Enable "WebSockets"
   * Enable "HTTP/2"
5. **Security Settings** (Optional)
   * Enable "Under Attack Mode" if needed
   * Set up Page Rules for caching
   * Configure Firewall Rules

#### Backup and Restore

**Create Backup:**

```bash
openalgo-backup
```

Backups are stored in `/opt/openalgo-backups/` and include:

* Database
* Configuration (.env file)
* Strategy files
* Last 7 backups are kept automatically

**Restore from Backup:**

```bash
# Stop container
cd /opt/openalgo
sudo docker compose stop

# Extract backup (replace TIMESTAMP with actual value)
sudo tar -xzf /opt/openalgo-backups/openalgo_backup_TIMESTAMP.tar.gz -C /opt/openalgo

# Fix permissions
sudo chown -R 1000:1000 log logs

# Start container
sudo docker compose start

# Verify
openalgo-status
```

#### Complete Uninstallation

```bash
# Stop and remove container
cd /opt/openalgo
sudo docker compose down -v

# Remove installation directory
sudo rm -rf /opt/openalgo

# Remove backups (optional)
sudo rm -rf /opt/openalgo-backups

# Remove Nginx configuration
sudo rm /etc/nginx/sites-available/yourdomain.com
sudo rm /etc/nginx/sites-enabled/yourdomain.com
sudo systemctl reload nginx

# Remove SSL certificate
sudo certbot delete --cert-name yourdomain.com

# Remove management scripts
sudo rm /usr/local/bin/openalgo-*

# Optional: Remove Docker (if not needed for other apps)
sudo apt remove -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
sudo rm -rf /var/lib/docker
```

#### Getting Help

* **Documentation**: <https://docs.openalgo.in>
* **Discord Community**: <https://discord.com/invite/UPh7QPsNhP>
* **GitHub Issues**: <https://github.com/marketcalls/openalgo/issues>
* **YouTube Tutorials**: <https://youtube.com/@openalgoHQ>
* **Website**: <https://openalgo.in>

#### Supported Brokers

| Broker         | Code           | XTS API |
| -------------- | -------------- | ------- |
| 5paisa         | `fivepaisa`    | No      |
| 5paisa XTS     | `fivepaisaxts` | Yes     |
| AliceBlue      | `aliceblue`    | No      |
| Angel One      | `angel`        | No      |
| Compositedge   | `compositedge` | Yes     |
| Definedge      | `definedge`    | No      |
| Dhan           | `dhan`         | No      |
| Dhan Sandbox   | `dhan_sandbox` | No      |
| Firstock       | `firstock`     | No      |
| Flattrade      | `flattrade`    | No      |
| Fyers          | `fyers`        | No      |
| Groww          | `groww`        | No      |
| IBulls         | `ibulls`       | Yes     |
| IIFL           | `iifl`         | Yes     |
| IndMoney       | `indmoney`     | No      |
| Kotak          | `kotak`        | No      |
| Motilal Oswal  | `motilal`      | No      |
| Paytm Money    | `paytm`        | No      |
| Pocketful      | `pocketful`    | No      |
| Shoonya        | `shoonya`      | No      |
| Tradejini      | `tradejini`    | No      |
| Upstox         | `upstox`       | No      |
| Wisdom Capital | `wisdom`       | Yes     |
| Zebu           | `zebu`         | No      |
| Zerodha        | `zerodha`      | No      |

**Note:** XTS API brokers require additional market data API credentials during installation.

#### System Requirements

**Minimum:**

* 1 vCPU
* 1GB RAM
* 10GB disk space
* Ubuntu 20.04+ or Debian 11+
* Internet connection

**Recommended:**

* 2 vCPU
* 2GB RAM
* 20GB SSD storage
* Ubuntu 22.04 LTS
* Stable internet connection

#### Architecture

```
┌─────────────────┐
│   Internet      │
└────────┬────────┘
         │ HTTPS (443)
         │
┌────────▼────────┐
│   Nginx         │ ← SSL/TLS, Rate Limiting
│   Reverse Proxy │
└────────┬────────┘
         │
    ┌────┴────┐
    │         │
    ▼         ▼
┌───────┐ ┌──────────┐
│ Flask │ │WebSocket │ ← Docker Container
│ :5000 │ │  :8765   │   (openalgo-web)
└───────┘ └──────────┘
    │
    ▼
┌──────────┐
│ SQLite   │ ← Docker Volume
│ Database │   (openalgo_db)
└──────────┘
```

#### FAQ

**Q: Can I use this on a server with existing Nginx?** A: Yes, but you may need to manually merge configurations to avoid conflicts.

**Q: Can I use a different port instead of 443?** A: Yes, but you'll need to modify the Nginx configuration manually.

**Q: Will this work with a subdomain?** A: Yes, the script supports both root domains and subdomains.

**Q: Can I run multiple OpenAlgo instances?** A: Not with this script. Each installation assumes it's the only instance.

**Q: How do I change my broker after installation?** A: Edit `/opt/openalgo/.env`, update broker credentials, then run `sudo docker compose restart`.

**Q: Is my broker data secure?** A: Yes, all data is encrypted in transit (HTTPS/WSS) and stored locally on your server.

**Q: Can I use this in production?** A: Yes, this script is designed for production use with SSL, security headers, and proper firewall configuration.

**Q: What if my domain doesn't have an A record yet?** A: Wait for DNS propagation (usually 5-60 minutes) before running the script.

#### Changelog

**Version 1.1.0** (October 19, 2024)

* Added support for running as root user (with warning)
* Fixed permission issues with docker-compose.yaml creation
* Improved error handling
* Enhanced management scripts

**Version 1.0.0** (Initial Release)

* Complete automated installation
* SSL certificate automation
* Docker containerization
* Management helper scripts

#### License

OpenAlgo is released under the **AGPL V3.0 License**.

#### Contributing

Contributions are welcome! Please see our Contributing Guide.

***

**Note**: This script is designed for fresh server installations. If you have an existing OpenAlgo installation or other applications on the server, please review the script and make necessary adjustments to avoid conflicts.

For production deployments, we strongly recommend:

1. Using a non-root user
2. Setting up automated backups
3. Monitoring logs regularly
4. Keeping the system updated
5. Using Cloudflare or similar CDN/DDoS protection


# Docker Development

This guide focuses on setting up a development environment for OpenAlgo using Docker.

{% embed url="<https://www.youtube.com/watch?v=ixIJypG9oeg>" %}

### Prerequisites

* Docker Engine
* Docker Compose
* Git

## Essential .env Changes for Docker Setup

### 1. Flask Host Configuration

```bash
# Change from 127.0.0.1 to 0.0.0.0 to allow external connections
FLASK_HOST_IP='0.0.0.0'  # Required for Docker
FLASK_PORT='5000'
```

### 2. WebSocket Configuration

```bash
# WebSocket server must bind to 0.0.0.0 inside Docker
WEBSOCKET_HOST='0.0.0.0'  # Required for Docker
WEBSOCKET_PORT='8765'
WEBSOCKET_URL='ws://localhost:8765'  # URL for clients connecting from host
```

### 3. ZeroMQ Configuration

```bash
# ZMQ must also bind to 0.0.0.0 for internal communication
ZMQ_HOST='0.0.0.0'  # Required for Docker
ZMQ_PORT='5555'
```

### Summary of Changes

#### From (Local Development):

```bash
FLASK_HOST_IP='127.0.0.1'
WEBSOCKET_HOST='127.0.0.1'
ZMQ_HOST='127.0.0.1'
```

#### To (Docker):

```bash
FLASK_HOST_IP='0.0.0.0'
WEBSOCKET_HOST='0.0.0.0'
ZMQ_HOST='0.0.0.0'
```

### Why These Changes?

1. **0.0.0.0 vs 127.0.0.1**:
   * `127.0.0.1` only allows connections from within the container
   * `0.0.0.0` allows connections from outside the container (host machine)
2. **WEBSOCKET\_URL**:
   * Remains as `ws://localhost:8765` because this is the URL clients use from the host machine
   * Docker maps the container's port to the host's localhost
3. **No other changes needed**:
   * All other settings (API keys, database URLs, etc.) remain the same
   * The docker-compose.yaml already maps the ports correctly

###

### Files Required

**1. Dockerfile**

```bash
FROM python:3.11-slim

WORKDIR /app

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# Install system dependencies
RUN apt-get update \
    && apt-get install -y --no-install-recommends gcc python3-dev libpq-dev \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

# Install Python dependencies
COPY requirements-nginx.txt .
RUN pip install --no-cache-dir -r requirements-nginx.txt
RUN pip install gunicorn eventlet>=0.24.1


# Copy project files
COPY . .

# Create directories and set permissions
RUN mkdir -p db logs && \
    chmod -R 777 db logs

# Command to run the application
CMD ["gunicorn", \
     "--bind", "0.0.0.0:5000", \
     "--worker-class", "eventlet", \
     "--workers", "1", \
     "--reload", \
     "--log-level", "debug", \
     "--access-logfile", "-", \
     "--error-logfile", "-", \
     "app:app"]
```

**2. docker-compose.yml**

```yaml
version: '3.8'

services:
  web:
    build: .
    ports:
      - "5000:5000"
    volumes:
      - .:/app
      - ./db:/app/db
    env_file:
      - .env
    environment:
      - FLASK_DEBUG=True
      - FLASK_ENV=development
      - DATABASE_URL=sqlite:///db/openalgo.db
    restart: unless-stopped
```

**3. .dockerignore**

```
**/__pycache__
**/*.pyc
**/*.pyo
**/*.pyd
.Python
env/
venv/
.env*
!.env.example
*.sqlite
.git
.gitignore
.docker
Dockerfile
README.md
*.sock
```

### Quick Start

1. **Create Environment File:**

   Copy `.sample.env` to `.env`:

   ```bash
   cp .sample.env .env
   ```
2. **Build and Start:**

   ```bash
   docker-compose up --build
   ```
3. **View Logs:**

   ```bash
   docker-compose logs -f
   ```

### Development Features

* Hot reload enabled (code changes reflect immediately)
* Debug mode active
* Console logging
* Port 5000 exposed
* Volume mounting for live code updates

### Common Commands

```bash
# Start development server
docker-compose up

# Start in detached mode
docker-compose up -d

# View logs
docker-compose logs -f

# Stop containers
docker-compose down

# Rebuild after dependency changes
docker-compose up --build

# Enter container shell
docker-compose exec web bash

# Check container status
docker-compose ps
```

### Directory Structure

```
openalgo/
├── Dockerfile
├── docker-compose.yml
├── .dockerignore
├── .env
├── app.py
├── requirements-nginx.txt
└── db/
    └── openalgo.db
```

### Development Tips

1. **Live Reload:**
   * Code changes will automatically reload
   * Check logs for errors after changes
2. **Database Access:**
   * SQLite database persists in ./db directory
   * Can be accessed from both host and container
3. **Debugging:**
   * Logs are printed to console
   * Debug mode enables detailed error pages
4. **Dependencies:**
   * Add new packages to requirements-nginx.txt
   * Rebuild container after adding dependencies:

     ```bash
     docker-compose up --build
     ```

### Troubleshooting

1. **Port Already In Use:**

   ```bash
   # Check what's using port 5000
   sudo lsof -i :5000

   # Stop the container and restart
   docker-compose down
   docker-compose up
   ```
2. **Database Issues:**

   ```bash
   # Fix permissions if needed
   chmod -R 777 db/
   ```
3. **Container Won't Start:**

   ```bash
   # Check logs
   docker-compose logs

   # Remove container and try again
   docker-compose down
   docker-compose up --build
   ```
4. **Package Installation Issues:**

   ```bash
   # Rebuild without cache
   docker-compose build --no-cache
   docker-compose up
   ```

### Note

This configuration is optimized for development. For production deployment, additional security measures and optimizations would be necessary.


# Devtunnels

**What Are Dev Tunnels?**

Dev Tunnels is a feature built into [Visual Studio Code (VS Code)](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.

{% embed url="<https://www.youtube.com/watch?v=XWoycY_El1o>" %}

#### 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.

### 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.

### Step-by-Step Setup Guide

#### 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/dashboard>) to verify that the service is up and running.

#### 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.

#### 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.

#### 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.

#### 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.\
  \&#xNAN;*Example:*\
  `https://h03ml9j.5000.inc1.devtunnels.ms/api/v1/placeorder`

#### 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.

<figure><img src="/files/VpjQEvg7mt7tJYPLi6vy" alt=""><figcaption></figcaption></figure>

#### 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**](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.

#### 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.

<figure><img src="https://i0.wp.com/www.marketcalls.in/wp-content/uploads/2025/02/image-8.png?resize=854%2C637&#x26;ssl=1" alt="" height="637" width="854"><figcaption></figcaption></figure>

***

### 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!


# Cloudflared with Custom Domain

This documentation outlines how to set up a **Cloudflare Tunnel (`cloudflared`)** with **OpenAlgo** to receive TradingView alerts securely on your local machine

### 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.

{% embed url="<https://www.youtube.com/watch?v=Lld-TgysQp8>" %}

***

### 2. Installation

To follow the video tutorial, install `cloudflared` on your Windows machine using PowerShell:

```powershell
# Install via Winget (Windows Package Manager)
winget install Cloudflare.cloudflared
```

*Note: After installation, restart your terminal to ensure the command is recognized.*

***

### 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:

   ```env
   HOST_SERVER="https://demo.openalgo.in"
   ```
4. Save the file and start OpenAlgo: `python app.py` (running on port 5000).

***

### 4. Setting Up the Tunnel (Two Options)

#### Option A: Custom Domain (Recommended for Production)

This keeps your Webhook URL permanent.

1. **Login to Cloudflare:**

   ```powershell
   cloudflared tunnel login
   ```

   *A browser window will open. Select your domain to authorize.*
2. **Create the Tunnel:**

   ```powershell
   cloudflared tunnel create openalgo
   ```

   *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:

   ```yaml
   tunnel: <YOUR-TUNNEL-ID>
   credentials-file: C:\Users\<Name>\.cloudflared\<TUNNEL-ID>.json

   ingress:
     - hostname: demo.openalgo.in
       service: http://127.0.0.1:5000
     - service: http_status:404
   ```
4. **Route DNS:**

   ```powershell
   cloudflared tunnel route dns openalgo demo.openalgo.in
   ```
5. **Run the Tunnel:**

   ```powershell
   cloudflared tunnel --config .\.cloudflared\config.yml run openalgo
   ```

***

#### 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:**

   ```powershell
   cloudflared tunnel --url http://127.0.0.1:5000
   ```
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.

***

### 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.

***

### 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.

***

### 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.


# Raspberry Pi

## OpenAlgo on Raspberry Pi — Setup Guide

**This guide helps you install and configure OpenAlgo on Raspberry Pi models 3, 4, or 5 (4GB+ RAM), preferably running Ubuntu 24.04+ server edition.**

<figure><img src="/files/4nWTUI0zUmI8wLbQ6H1a" alt=""><figcaption></figcaption></figure>

### Hardware & OS Recommendations

* **Raspberry Pi Model**: 3, 4, or 5 (minimum 4GB RAM)
* **SD Card**: Recommended 128GB; minimum 64GB
* **Operating System**: Ubuntu 24.04+ Server edition (preferred)
* **RPi official power adapter**: Recommended to buy for stable power supply and avoid RPi abrupt shutdowns and restarts. [Get Ubuntu images for Raspberry Pi](https://ubuntu.com/download/raspberry-pi)

<figure><img src="/files/tIGJ8Q8IREC1YGDh57Ha" alt=""><figcaption></figcaption></figure>

### Initial System Preparation

#### 1. Flash OS to SD Card

* Use [Raspberry Pi Imager](https://www.raspberrypi.com/software/) to prepare your SD card.
* Configure initial user, password, Wi-Fi details, etc.

#### 2. First Boot & Access

* Insert SD card, power on Raspberry Pi.
* Connect HDMI to monitor/TV and USB keyboard **or** get the private IP from your router/AP and SSH to RPi instance :

  ```
  ssh <username>@<raspberry-pi-ip>
  ```
* [Official Raspberry Pi SSH guide](https://www.raspberrypi.com/documentation/computers/getting-started.html)

#### 3. Setup Swap

* Recommend swap size: **max 4GB, min 2GB**

  ```
  sudo fallocate -l 4G /swapfile
  sudo chmod 600 /swapfile
  sudo mkswap /swapfile
  sudo swapon /swapfile
  echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
  ```

### OpenAlgo Installation

#### Option 1: Using Official Install Script

* **Visit**: [Install Instructions](https://docs.openalgo.in/installation-guidelines/getting-started)
* **Follow the script prompts.**\
  (Typically involves downloading, running the script, and entering your details.)

#### Option 2: Docker-Based Setup (Recommended for advanced users)

**1. Install Docker (Ubuntu/ARM)**

[Docker Ubuntu install guide](https://docs.docker.com/engine/install/ubuntu/)

```
sudo apt-get update
sudo apt-get install ca-certificates curl gnupg
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
```

**2. Install Docker Buildx for ARM**

`docker buildx version`

If not present, follow: <https://docs.docker.com/buildx/working-with-buildx/#install-buildx>

**3. Get nginx Docker Image (reverse proxy)**

`docker pull nginx:latest`

**4. Clone the OpenAlgo Repo**

```
git clone https://github.com/marketcalls/openalgo
cd openalgo
```

**5. Build OpenAlgo Docker Image**

`docker build -t openalgo:latest .`

**6. Configure Environment**

* Copy `.sample.env` as `.env` and fill in **broker API key, secret, and client ID**

  ```
  cp .sample.env .env
  vi .env
  ```

**7. Use docker-compose.yaml**

* Edit/verify `docker-compose.yaml` inside `/openalgo`
* If you have build the docker image in previous step, you can comment the build and its nested tags (using #) in `docker-compose.yaml` file.
* Launch services:

  ```
  docker-compose up -d
  ```

**8. Configure Nginx Reverse Proxy**

* Reference: [Install Multi-Script Example](https://github.com/marketcalls/openalgo/blob/main/install/install-multi.sh)
* Typical location blocks for nginx:

  ```
  location / {
      proxy_pass http://localhost:<openalgo-port>;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
  }
  ```
* Adapt your domain/server settings accordingly.

### Persistent Storage (Recommended Practice)

I prefer to separate out the runtime files and folders from the github cloned folder and keep them separate. So if you build the docker image as in above step #5, you can very well take the docker-compose.yaml in a separate working folder structure and have your own versions of .env file.

* Create and mount volumes under `/work` for logs, keys, strategies, etc.

  ```
  /work
    /storage
       /openalgo
           docker-compose.yaml
           .env
           applogs/
           logs/
           keys/
           strategies/
           db/
  ```
* Update `docker-compose.yaml` [example](https://github.com/marketcalls/openalgo/blob/main/docker-compose.yaml):

  ```
  volumes:
    - /work/storage/openalgo/keys:/openalgo/keys
    - /work/storage/openalgo/strategies:/openalgo/strategies
    # Add other mounts as required
  ```

### Securing your setup

#### A. Basic Server Protection (iptables, fail2ban)

**1. Install iptables**

```
sudo apt-get update
sudo apt-get install iptables
```

* Example: Allow SSH and HTTP(S), block others:

  ```
  sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
  sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
  sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
  sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
  sudo iptables -A INPUT -j DROP
  sudo iptables-save | sudo tee /etc/iptables/rules.v4
  ```
* [iptables guide](https://help.ubuntu.com/community/IptablesHowTo)

**2. Install fail2ban**

```
sudo apt-get install fail2ban
```

* Enable default jails for SSH, edit `/etc/fail2ban/jail.local` for customization.
* Start and enable service:

  ```
  sudo systemctl enable fail2ban
  sudo systemctl start fail2ban
  ```
* [fail2ban documentation](https://www.fail2ban.org/wiki/index.php/Main_Page)
* [Example setup](https://linuxize.com/post/how-to-install-fail2ban-on-ubuntu-20-04/)

#### B. Using Cloudflare for Reverse Proxy & Security

* **Register at** [**Cloudflare**](https://www.cloudflare.com/)**.**
* **Add Your Domain:**
  * Point your domain's DNS to Cloudflare's nameservers.
  * Set up [proxy status](https://developers.cloudflare.com/dns/add-domain/) for your domain so Cloudflare sits between users and your Pi.
* **HTTPS and SSL:**
  * Use Cloudflare’s “Flexible SSL” or, for end-to-end encryption, generate origin certificates on Cloudflare and install them behind Nginx.
* **Firewall Rules & Monitoring:**
  * Enable Cloudflare Web Application Firewall (WAF).
  * Set up custom routes, rate limiting, and security rules.
  * [Cloudflare dashboard security settings](https://developers.cloudflare.com/waf/)
* **Analytics & DDoS Protection:**
  * Monitor connection health and traffic patterns through Cloudflare Analytics.
* [Cloudflare Nginx integration guide](https://developers.cloudflare.com/ssl/origin-configuration/ssl/nginx/)

***

### Useful References

* [OpenAlgo GitHub](https://github.com/marketcalls/openalgo)
* [OpenAlgo Documentation](https://docs.openalgo.in)
* [Docker Install Ubuntu](https://docs.docker.com/engine/install/ubuntu/)
* [Nginx Reverse Proxy Setup](https://github.com/marketcalls/openalgo/blob/main/install/install-multi.sh)
* [Persistent Volumes Example](https://github.com/marketcalls/openalgo/blob/main/docker-compose.yaml)
* [IPTables Guide](https://help.ubuntu.com/community/IptablesHowTo)
* [fail2ban documentation](https://www.fail2ban.org/wiki/index.php/Main_Page)
* [Cloudflare dashboard security settings](https://developers.cloudflare.com/waf/)
* [Cloudflare Nginx integration guide](https://developers.cloudflare.com/ssl/origin-configuration/ssl/nginx/)

**OpenAlgo is now ready on your Raspberry Pi! Start building and deploying your trading strategies.**


# Testing OpenAlgo in Cloud

### Testing OpenAlgo in the Github Codespaces

{% embed url="<https://www.youtube.com/watch?v=bB3S0t4K2xU>" %}

### Test OpenAlgo in Google Colab

{% embed url="<https://www.youtube.com/watch?t=6s&v=26p42_Ku1ok>" %}


# SMTP Settings

## SMTP Email Setup for OpenAlgo

### Gmail Configuration Options

Choose the configuration that matches your Gmail setup:

{% embed url="<https://www.youtube.com/watch?v=-wDDMycJ7AM>" %}

#### Personal Gmail (Recommended)

After migration, go to **Profile → SMTP Configuration** and use:

```
SMTP Server: smtp.gmail.com
SMTP Port: 587
Username: your-email@gmail.com
Password: [App Password - see below]
Use TLS/SSL: ✓ (checked)
From Email: your-email@gmail.com
HELO Hostname: smtp.gmail.com
```

<figure><img src="/files/BvA60mYXtH8wKj2ROydm" alt=""><figcaption></figcaption></figure>

#### Google Workspace (Business Gmail)

For business domains (e.g., <user@yourcompany.com>):

**Option 1: SMTP Relay (Recommended for Businesses)**

**Requirements:**

* Google Workspace Admin access
* Server IP registration in Google Admin Console

**Configuration:**

```
SMTP Server: smtp-relay.gmail.com
SMTP Port: 465
Username: your-email@yourcompany.com
Password: [App Password - see below]
Use TLS/SSL: ✓ (checked)
From Email: your-email@yourcompany.com
HELO Hostname: smtp.gmail.com
```

**Setup Steps:**

1. **Admin Console Setup:**
   * Go to [Google Admin Console](https://admin.google.com)
   * Navigate to **Apps → Google Workspace → Gmail → SMTP relay service**
   * Click **Add another** to create new relay
   * Configure these settings:

     ```
     Allowed senders: Only addresses in my domains
     Authentication: Require SMTP Authentication
     Encryption: Require TLS encryption
     ```
   * **Add your server IP address** to allowed IP ranges
   * Save the configuration
2. **Find Your Server IP:**

   ```bash
   # From your OpenAlgo server, run:
   curl -4 ifconfig.me
   # Or visit: https://whatismyipaddress.com/
   ```
3. **Register IP in Admin Console:**
   * In SMTP relay settings, add your server IP to **IP addresses**
   * Format: `YOUR.SERVER.IP.ADDRESS/32` (e.g., `203.0.113.15/32`)

**Option 2: Personal Gmail Settings (Alternative)**

If SMTP relay setup is complex, use personal Gmail settings:

```
SMTP Server: smtp.gmail.com
SMTP Port: 587
Username: your-email@yourcompany.com
Password: [App Password]
Use TLS/SSL: ✓ (checked)
From Email: your-email@yourcompany.com
HELO Hostname: smtp.gmail.com
```

### App Password Setup (Required for Both)

<figure><img src="/files/yVyBzsTwuBRj9vnG6zFS" alt=""><figcaption></figcaption></figure>

#### For Personal Gmail:

1. Go to [Google Account Settings](https://myaccount.google.com/apppasswords)
2. Enable 2-Factor Authentication (if not enabled)
3. Select **App passwords**
4. Choose **Mail** from dropdown
5. Generate password and copy the 16-character code
6. Use this password in OpenAlgo (NOT your regular password)

<figure><img src="/files/uzQthavG9JgDdT7ogqNf" alt=""><figcaption></figcaption></figure>

#### For Google Workspace:

1. Go to [Google Account Settings](https://myaccount.google.com/apppasswords)
2. **Admin may need to enable App Passwords:**
   * Admin Console → Security → API controls → App passwords
   * Enable "Allow users to manage their app passwords"
3. Follow same steps as personal Gmail above
4. If App Passwords unavailable, ask your IT administrator

### Advanced Google Workspace Configuration

#### Admin Console SMTP Relay Settings

For enterprise deployments, configure these advanced settings:

1. **Security Settings:**

   ```
   Require TLS encryption: Yes
   Require SMTP Authentication: Yes
   Only accept mail from specified IP addresses: Yes
   ```
2. **Rate Limiting:**

   ```
   Per-user rate limit: 10,000 messages/day
   Per-domain rate limit: 1,000,000 messages/day
   ```
3. **Routing Settings:**

   ```
   Also deliver to Gmail mailbox: Optional
   Store and forward: Recommended for reliability
   ```

#### Multiple Domain Support

If you have multiple domains in Workspace:

1. **Primary Domain Configuration:**

   ```
   SMTP Server: smtp-relay.gmail.com
   From Email: noreply@primarydomain.com
   ```
2. **Additional Domains:**
   * Add all domains to Admin Console → Domains
   * Enable SMTP relay for each domain
   * Use same SMTP settings with appropriate From Email

#### Troubleshooting Google Workspace

**Common Error: "Mail relay denied"**

**Solution 1 - IP Registration:**

```bash
# Check your current IP
curl -4 ifconfig.me

# Add this IP to Google Admin Console:
# Apps → Gmail → SMTP relay service → IP addresses
```

**Solution 2 - Authentication:**

* Verify App Password is correctly generated
* Ensure 2FA is enabled on the account
* Check username format (full email address)

**Solution 3 - Fallback to Personal Settings:**

```
SMTP Server: smtp.gmail.com (instead of smtp-relay.gmail.com)
SMTP Port: 587 (instead of 465)
```

**Error: "Authentication failed"**

1. **Check App Password:**
   * Must be 16 characters without spaces
   * Generated specifically for "Mail"
   * Account must have 2FA enabled
2. **Admin Policy Check:**

   ```
   Admin Console → Security → Less secure app access
   Should be: "Allow users to manage their access to less secure apps"
   ```
3. **Account Verification:**
   * Ensure account is not suspended
   * Check for recent password changes

### Testing Your Configuration

#### Step-by-Step Testing

1. **Save SMTP Settings** in Profile → SMTP Configuration
2. **Click "Debug"** to test connection and view detailed diagnostics
3. **Click "Send Test"** to send test email to yourself
4. **Check your inbox** (and spam folder)
5. **Try Password Reset** to test end-to-end functionality

<figure><img src="/files/WY2P22a3wsXHDGTXW7Rf" alt=""><figcaption></figcaption></figure>

#### Expected Test Results

**Debug Output (Success):**

```
✓ SMTP connection successful
✓ Authentication passed
✓ TLS encryption enabled
✓ Server ready to accept messages
```

**Debug Output (Common Issues):**

```
✗ Mail relay denied → Check IP registration in Admin Console
✗ Authentication failed → Verify App Password
✗ Connection timeout → Check firewall/network settings
```

#### Testing Different Scenarios

1. **Test from Different IPs:** If using multiple servers
2. **Test Different From Addresses:** Verify domain permissions
3. **Test High Volume:** Check rate limiting behavior
4. **Test Failed Authentication:** Verify error handling

### Production Deployment Best Practices

#### Security Recommendations

1. **Use Dedicated Service Account:**

   ```
   Create: noreply@yourcompany.com
   Purpose: SMTP authentication only
   Permissions: Minimal (just send email)
   ```
2. **IP Whitelist Management:**
   * Use static IP addresses for production servers
   * Document all registered IPs
   * Regular audit of IP permissions
3. **Monitor Email Logs:**
   * Track successful/failed send attempts
   * Monitor for suspicious activity
   * Set up alerts for authentication failures

#### Performance Optimization

1. **Connection Pooling:** Use persistent SMTP connections when possible
2. **Rate Limiting:** Respect Google's sending limits
3. **Retry Logic:** Implement exponential backoff for failures
4. **Queue Management:** Handle high-volume email sending

### Common Issues & Solutions

#### Personal Gmail Issues

* **Authentication Failed**: Use App Password, not regular password
* **Connection Failed**: Try port 587 instead of 465
* **2FA Required**: Enable 2-Factor Authentication first

#### Google Workspace Issues

* **Mail relay denied**:
  * Register server IP in Admin Console
  * Verify SMTP relay service is enabled
  * Check authentication credentials
* **Admin restrictions**:
  * App passwords may be disabled by admin
  * Less secure app access may be blocked
  * Contact IT administrator for policy changes
* **Domain verification**:
  * Ensure domain is verified in Workspace
  * Check MX records are properly configured
  * Verify user account is active

#### Network & Firewall Issues

* **Port blocking**: Ensure ports 587/465 are open outbound
* **Proxy servers**: Configure SMTP through corporate proxy if needed
* **DNS resolution**: Verify smtp.gmail.com resolves correctly

### Alternative Email Providers

#### Microsoft 365 / Outlook

**Business (Exchange Online):**

```
SMTP Server: smtp.office365.com
SMTP Port: 587
Username: your-email@yourcompany.com
Password: [Account Password or App Password]
Use TLS/SSL: ✓ (checked)
From Email: your-email@yourcompany.com
HELO Hostname: smtp.office365.com
```

**Personal Outlook/Hotmail:**

```
SMTP Server: smtp-mail.outlook.com
SMTP Port: 587
Username: your-email@outlook.com
Password: [Account Password]
Use TLS/SSL: ✓ (checked)
From Email: your-email@outlook.com
HELO Hostname: smtp-mail.outlook.com
```

#### Yahoo Mail

```
SMTP Server: smtp.mail.yahoo.com
SMTP Port: 587
Username: your-email@yahoo.com
Password: [App Password from Yahoo Account Security]
Use TLS/SSL: ✓ (checked)
From Email: your-email@yahoo.com
HELO Hostname: smtp.mail.yahoo.com
```

#### Custom SMTP Providers

**SendGrid:**

```
SMTP Server: smtp.sendgrid.net
SMTP Port: 587
Username: apikey
Password: [SendGrid API Key]
```

**Mailgun:**

```
SMTP Server: smtp.mailgun.org
SMTP Port: 587
Username: [Mailgun SMTP Username]
Password: [Mailgun SMTP Password]
```

### Enterprise Integration

#### Load Balancing

For high-availability setups:

1. Configure multiple SMTP servers
2. Implement failover logic
3. Monitor server health
4. Balance email load across servers

#### Compliance & Logging

1. **Audit Requirements:**
   * Log all email send attempts
   * Track recipient information (hashed)
   * Monitor for compliance violations
2. **Data Retention:**
   * Configure log retention periods
   * Implement secure log storage
   * Regular compliance audits

#### Monitoring & Alerting

Set up monitoring for:

* SMTP connection failures
* Authentication errors
* Rate limit violations
* Unusual sending patterns

### Support & Resources

#### Google Support Links

* [Google Workspace SMTP Relay](https://support.google.com/a/answer/2956491) - General SMTP relay documentation
* [App Passwords Setup](https://support.google.com/accounts/answer/185833) - How to generate App Passwords
* [Admin Console Guide](https://support.google.com/a/answer/2956491) - SMTP relay service configuration

#### OpenAlgo Resources

* **Built-in Debug**: Use SMTP Debug function in profile
* **Log Files**: Check OpenAlgo logs for detailed error messages
* **GitHub Issues**: Report SMTP-specific problems
* **Documentation**: `/docs/PASSWORD_RESET.md` for complete system overview

***

**That's it!** Your OpenAlgo can now send emails for password resets and notifications using your preferred email provider. Choose the configuration that best fits your organization's setup and security requirements.


# TOTP Configuration

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](/installation-guidelines/getting-started/smtp-settings)

### 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

<figure><img src="/files/ePOestvargvwIThOYFcC" alt=""><figcaption></figcaption></figure>

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

<figure><img src="/files/LSJI5t55CGgknKtKhomQ" alt=""><figcaption></figcaption></figure>

3\)select the verification method as Authenticator App (TOTP)

<figure><img src="/files/yOuzZKx9Uztq2gnVyVEc" alt=""><figcaption></figcaption></figure>

4\)Enter the 6 digit TOTP from your Authenticator App

<figure><img src="/files/bwDvCtNyrOPvw4qlVLIt" alt=""><figcaption></figcaption></figure>

5\)reset with the new password

<figure><img src="/files/C3GLDLXXHHRS286HCDJd" alt=""><figcaption></figcaption></figure>

6\)now login with your newer credentials and start using openalgo


# Forgot Password

## OpenAlgo Password Reset System

### Overview

OpenAlgo provides a comprehensive dual-mode password reset system that allows users to recover their accounts through either:

1. **TOTP (Time-based One-Time Password)** authentication
2. **Email verification** (requires SMTP configuration)

This system is designed with security best practices and provides fallback options for different scenarios.

### Table of Contents

* System Architecture
* Authentication Methods
* Setup Requirements
* User Flow
* Configuration Guide
* Security Features
* Troubleshooting
* API Endpoints
* Rate Limiting

### System Architecture

The password reset system follows a secure token-based approach with multiple verification methods:

```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   User Request  │    │  Method Selection │    │  Verification   │
│                 │───▶│                  │───▶│                 │
│ Enter Email     │    │ TOTP or Email    │    │ Code/Link Check │
└─────────────────┘    └──────────────────┘    └─────────────────┘
                                                          │
                       ┌─────────────────┐               │
                       │  Password Reset │◀──────────────┘
                       │                 │
                       │ New Password    │
                       └─────────────────┘
```

### Authentication Methods

#### 1. TOTP Authentication (Recommended)

**Advantages:**

* Works offline
* No external dependencies
* Immediate verification
* Always available

**Requirements:**

* User must have TOTP configured
* Authenticator app (Google Authenticator, Authy, etc.)

**Flow:**

1. User enters email address
2. User selects "TOTP Authentication"
3. User enters TOTP code from authenticator app
4. System validates code and allows password reset

#### 2. Email Verification

**Advantages:**

* User-friendly
* No additional app required
* Secure email delivery

**Requirements:**

* SMTP configuration must be completed
* User has access to their email

**Flow:**

1. User enters email address
2. User selects "Email Verification"
3. System sends reset link to user's email
4. User clicks link and resets password

### Setup Requirements

#### TOTP Setup (Always Available)

TOTP is automatically configured during account creation. Each user gets:

* Unique TOTP secret key
* QR code for easy setup
* Backup secret for manual entry

#### SMTP Configuration (Required for Email Reset)

**Personal Gmail Configuration:**

```
SMTP Server: smtp.gmail.com
Port: 587 (STARTTLS) or 465 (SSL/TLS)
Username: your-email@gmail.com
Password: [App Password - NOT regular password]
HELO Hostname: smtp.gmail.com
Use TLS: Yes
```

**Gmail Workspace Configuration:**

```
SMTP Server: smtp-relay.gmail.com
Port: 465 (SSL/TLS)
Username: your-email@yourdomain.com
Password: [App Password]
HELO Hostname: smtp.gmail.com
Use TLS: Yes
```

**App Password Setup for Gmail:**

1. Go to Google Account Settings
2. Navigate to Security → 2-Step Verification
3. Select "App passwords"
4. Generate a new app password for "Mail"
5. Use this password in SMTP configuration

### User Flow

#### Password Reset Process

1. **Initial Request**
   * User visits `/auth/reset-password`
   * Enters email address
   * System validates email format (client-side and server-side)
2. **Method Selection**
   * System presents two verification options:
     * TOTP Authentication (always available)
     * Email Verification (if SMTP configured)
   * User selects preferred method
3. **TOTP Verification Path**
   * User enters TOTP code from authenticator app
   * System validates code against user's TOTP secret
   * If valid, generates secure reset token
   * User proceeds to password reset form
4. **Email Verification Path**
   * System generates secure reset token
   * Sends password reset email with secure link
   * User clicks link in email
   * System validates token and shows password reset form
5. **Password Reset**
   * User enters new password
   * System validates password meets requirements:
     * 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 (@#$%^&\*)
   * Password is hashed and stored securely
   * All reset tokens are invalidated

### Configuration Guide

#### SMTP Configuration

Access SMTP settings at `/auth/change` → "SMTP Configuration" tab:

1. **Server Settings**
   * Enter SMTP server hostname
   * Set appropriate port (587 for STARTTLS, 465 for SSL/TLS)
   * Configure HELO hostname
2. **Authentication**
   * Enter username (usually email address)
   * Enter App Password (not regular password for Gmail)
   * Set from email address
3. **Security**
   * Enable TLS/SSL encryption
   * Test configuration before saving
4. **Testing**
   * Use "Send Test" to verify configuration
   * Use "Debug" for detailed connection diagnostics

#### TOTP Configuration

Access TOTP settings at `/auth/change` → "TOTP Authentication" tab:

1. **QR Code Setup**
   * Scan QR code with authenticator app
   * Or manually enter the secret key
2. **Supported Apps**
   * Google Authenticator
   * Authy
   * Microsoft Authenticator
   * 1Password
   * Bitwarden
3. **Backup**
   * Save secret key in secure location
   * Test TOTP generation before relying on it

### Security Features

#### Token Security

* **Cryptographically secure tokens**: 32-byte URL-safe tokens
* **Session-based validation**: Tokens stored in server-side sessions
* **Single-use tokens**: Tokens invalidated after successful use
* **Time-limited validity**: Email tokens expire with session
* **Secure transmission**: HTTPS-only token delivery

#### Anti-Enumeration Protection

* **Consistent responses**: Same response regardless of email existence
* **Information leakage prevention**: No indication if email is registered
* **Rate limiting**: Prevents brute force attacks

#### Additional Security Measures

* **CSRF protection**: All forms protected with CSRF tokens
* **Input validation**: Email format and password strength validation
* **Secure password hashing**: Bcrypt with proper salt rounds
* **Session security**: Secure session cookie configuration

### Troubleshooting

#### Common SMTP Issues

**Gmail Authentication Failed**

```
Error: SMTP Authentication failed
Solution: Use App Password instead of regular password
Steps: Google Account → Security → 2-Step Verification → App passwords
```

**Gmail Workspace Relay Denied**

```
Error: Mail relay denied
Solution 1: Register server IP in Google Admin Console
Solution 2: Switch to personal Gmail settings (smtp.gmail.com:587)
```

**Connection Timeout**

```
Error: Connection timeout
Check: Firewall blocking SMTP ports (587, 465)
Check: Network connectivity to SMTP server
```

**SSL/TLS Errors**

```
Error: SSL handshake failed
Solution: Verify port configuration (587=STARTTLS, 465=SSL/TLS)
Check: Certificate validation settings
```

#### Common TOTP Issues

**Invalid TOTP Code**

```
Issue: Code not accepted
Check: Time synchronization on device
Check: Code not expired (30-second window)
Solution: Manually sync time in authenticator app
```

**Lost Authenticator Device**

```
Issue: Cannot generate TOTP codes
Solution: Use backup secret key to reconfigure
Fallback: Contact administrator for manual reset
```

#### Email Delivery Issues

**Email Not Received**

```
Check: Spam/junk folder
Check: Email address typos
Check: SMTP server logs
Verify: Test email functionality works
```

**Reset Link Expired**

```
Issue: "Invalid or expired reset link"
Cause: Session expired or link already used
Solution: Request new password reset
```

### ⚠️ Nuclear Option: Complete Database Reset

#### When All Else Fails

If you cannot access your OpenAlgo account through any method (TOTP broken, email not working, lost credentials),\
\
1\)stop openalgo application\
2\)Locate the file openalgo.db from the db folder\
3\)delete the openalgo.db database file form the /db folder\
4\)restart the openalgo application\
5\)Start signup with openalgo fresh\
6\)Ensure Gmail SMTP Settings or TOTP Authenticator is Configured

<figure><img src="/files/md9RDi6T8y979db2aO5f" alt=""><figcaption></figcaption></figure>

#### What You Will Lose

⚠️ **WARNING: This action is irreversible and will permanently delete:**

* **User accounts and passwords**
* **All trading logs and history**
* **API access logs and analytics**
* **Strategy configurations and backtests**
* **SMTP/email settings**
* **Rate limiting history**
* **System settings and preferences**
* **Custom configurations**

#### Prevention for Future

To avoid needing database reset:

1. **Save TOTP Secret Key**: Store authenticator backup codes securely
2. **Configure SMTP Early**: Set up email recovery before you need it
3. **Document Credentials**: Keep encrypted record of important settings
4. **Regular Backups**: Schedule automatic database backups
5. **Test Recovery**: Periodically test password reset functionality

#### Alternative Recovery Methods

Before resorting to database reset, try these:

1. **TOTP Secret Recovery**: If you saved the original secret key, re-add to authenticator
2. **Database Editing**: Advanced users can directly edit SQLite database to reset passwords
3. **Python Script Recovery**: Create custom script to reset user password in database
4. **Backup Restoration**: If you have recent database backup, restore it instead

### Rate Limiting

The password reset system implements rate limiting to prevent abuse:

#### Configuration

```env
# Login rate limits (applied to reset password as well)
LOGIN_RATE_LIMIT_MIN=5 per minute
LOGIN_RATE_LIMIT_HOUR=25 per hour

# Password reset specific limit
RESET_RATE_LIMIT=15 per hour
```

#### Limits Applied

* **Password reset requests**: 15 per hour per IP
* **SMTP test requests**: Inherits from login limits
* **Failed authentication attempts**: Tracked separately

#### Rate Limit Headers

When rate limited, responses include:

* `X-RateLimit-Limit`: Maximum requests allowed
* `X-RateLimit-Remaining`: Requests remaining in window
* `X-RateLimit-Reset`: Time when limit resets

### Best Practices

#### For Users

1. **TOTP Setup**: Always configure TOTP as primary recovery method
2. **Backup Codes**: Save TOTP secret key securely
3. **Email Security**: Use secure email provider with 2FA
4. **Strong Passwords**: Follow password requirements strictly

####


# Upgrade

Follow the steps for **your installation method**. The procedure differs depending on how you installed OpenAlgo.

{% hint style="danger" %}
**Never run `cp .sample.env .env` on an existing installation.** It erases your broker keys and replaces your `API_KEY_PEPPER` — which permanently invalidates every stored password hash and encrypted broker token. Your `.env` is not tracked by git, so `git pull` always preserves it. When an update introduces new environment variables, copy **only those new lines** from `.sample.env` into your existing `.env` (see "Handling new environment variables" below).
{% endhint %}

***

### Option 1: Ubuntu Server (installed via install.sh)

Your installation lives at `/var/python/openalgo` and runs as the systemd service `openalgo`. Use the bundled update script — it performs the entire upgrade safely in one command:

```bash
cd /var/python/openalgo
sudo bash install/update.sh
```

The script automatically:

1. Stops the `openalgo` service
2. **Backs up all databases** (openalgo, logs, latency, sandbox, historify) to a timestamped `db/backup_<timestamp>/` folder
3. Pulls the latest code (`git pull`)
4. Compares your `.env` against `.sample.env` and **lists any new variables** you should add (it never overwrites your `.env`)
5. Updates Python dependencies
6. Runs all database migrations
7. Restarts the service

Legacy multi-deployment installs (`/var/python/openalgo-flask/<name>/`) are detected automatically and the correct `openalgo-<name>` service is updated.

***

### Pre-built images on Docker Hub

CI publishes a multi-architecture image (amd64 and arm64) on every push to `main`:

* [`marketcalls/openalgo`](https://hub.docker.com/r/marketcalls/openalgo) on Docker Hub
* `marketcalls/openalgo:latest` — the current `main`
* `marketcalls/openalgo:<commit-sha>` — every build, so you can pin or roll back to an exact version

**Which upgrade path applies to you depends on how you installed:**

| Install method                       | Image source                        | Upgrade                                               |
| ------------------------------------ | ----------------------------------- | ----------------------------------------------------- |
| `docker-run.sh` (Desktop)            | Pulls `marketcalls/openalgo:latest` | `./docker-run.sh pull` then `./docker-run.sh restart` |
| `install-docker.sh` (custom domain)  | **Builds locally** from the repo    | `git pull` then rebuild — Option 2a                   |
| `install-docker-multi-custom-ssl.sh` | **Builds locally** per instance     | Re-run the installer in update mode — Option 2b       |
| Manual clone                         | **Builds locally**                  | Option 2                                              |

The server install scripts build locally rather than pulling, so a `docker pull` alone will not update them. If you would rather pull than build — it is much faster, since no build step runs — see "Using the pre-built image instead of building" below.

***

### Option 2: Docker — manual clone (no custom domain)

Use this if you cloned OpenAlgo yourself and run it with `docker compose`.

```bash
# From the folder where you cloned openalgo
cd ~/openalgo

# Pull the latest code (includes the pre-built frontend)
git pull

# Rebuild and restart the container
sudo docker compose down
sudo docker compose build --no-cache
sudo docker compose up -d

# Watch startup logs
sudo docker compose logs -f
```

Your `.env` file and the named volumes persist across the rebuild — no reconfiguration needed. Database migrations run automatically on container startup.

{% hint style="warning" %}
**If you installed with `install-docker.sh` or `install-docker-multi-custom-ssl.sh`, your installation is NOT in `~/openalgo`.** It is under `/opt/openalgo`. Use Option 2a or 2b below instead.
{% endhint %}

***

### Option 2a: Docker + Custom Domain (single instance)

For installations created with **`install-docker.sh`**, which sets up nginx, a Let's Encrypt certificate and your domain.

**Your installation lives at `/opt/openalgo`.**

```bash
cd /opt/openalgo

# 1. Back up the database volume first (see "Backing up" below)

# 2. Pull the latest code
sudo git pull

# 3. Rebuild and restart
sudo docker compose down
sudo docker compose build --no-cache
sudo docker compose up -d

# 4. Watch it come up
sudo docker compose logs -f
```

**What is preserved automatically, and why:**

| Item                             | Location                              | Survives because                                    |
| -------------------------------- | ------------------------------------- | --------------------------------------------------- |
| Your `.env`                      | `/opt/openalgo/.env`                  | Not tracked by git, bind-mounted into the container |
| Database, logs, strategies, keys | Docker named volumes                  | Volumes are independent of the image                |
| nginx site configuration         | `/etc/nginx/sites-available/<domain>` | Outside the repository entirely                     |
| SSL certificate                  | `/etc/letsencrypt/live/<domain>/`     | Outside the repository entirely                     |

Because nginx and the certificate live outside the repo, **a Docker upgrade cannot break your domain or SSL.** You do not need to re-run certbot, and you do not need to touch nginx.

You also do **not** need to change your broker's redirect URL — it stays `https://<your-domain>/<broker>/callback`.

***

### Option 2b: Docker + Custom Domain (multi-instance)

For installations created with **`install-docker-multi-custom-ssl.sh`**, where each domain is its own instance under `/opt/openalgo/<domain>`.

**The installer doubles as the upgrade script.** Re-run it and choose update mode:

```bash
cd /opt/openalgo
sudo bash install-docker-multi-custom-ssl.sh
```

When it finds an existing instance it asks:

```
Instance for yourdomain.com already exists. Update code only? (y=update, n=skip, r=reinstall):
```

Answer **`y`**. It pulls the latest code and **preserves your existing configuration** — broker keys, API secrets and domain settings are read back out of the instance's `.env` and reused. Answer `n` to skip an instance you do not want to touch.

To upgrade a single instance by hand instead:

```bash
cd /opt/openalgo/yourdomain.com
sudo git pull
sudo docker compose down
sudo docker compose build --no-cache
sudo docker compose up -d
```

{% hint style="info" %}
Each instance has its own directory, its own `.env`, its own volumes and its own nginx site. Upgrading one does not affect the others — which is also why you must repeat the steps for each domain you want on the new version.
{% endhint %}

***

### Using the pre-built image instead of building

Optional. Building locally takes several minutes and needs build tooling on the server; pulling the published image takes seconds. The trade-off is that you give up local modifications to the source.

Edit `docker-compose.yaml` in your install directory:

```yaml
services:
  openalgo:
    image: marketcalls/openalgo:latest    # was: openalgo:latest
    # build:                              # comment out or delete this block
    #   context: .
    #   dockerfile: Dockerfile
```

Then upgrades become:

```bash
cd /opt/openalgo
sudo docker compose pull
sudo docker compose up -d
```

**Pinning to an exact version** is the main practical benefit — it makes rollback immediate and unambiguous:

```yaml
    image: marketcalls/openalgo:a1b2c3d    # a specific commit SHA
```

```bash
sudo docker compose pull && sudo docker compose up -d
```

{% hint style="info" %}
Keep `git pull` in your routine even when using the pre-built image. The repository still supplies `docker-compose.yaml`, the installer scripts and the migration files, and you want those current alongside the image.
{% endhint %}

{% hint style="warning" %}
Only `main` is published as `latest`. If you are testing a branch, you must build locally — there is no published image for it.
{% endhint %}

***

### Backing up before a Docker upgrade

Named volumes are not touched by `docker compose build`, but take a copy before any upgrade.

**The simplest method — copy straight out of the running container:**

```bash
cd /opt/openalgo
sudo docker compose cp openalgo:/app/db ./db-backup-$(date +%Y%m%d)
```

Here `openalgo` is the compose **service** name, not the container name.

**If you prefer to archive the volume itself, look up its real name first:**

```bash
sudo docker volume ls | grep db
```

Docker Compose prefixes volume names with the project name, which is taken from the directory. An install in `/opt/openalgo` produces `openalgo_openalgo_db`, while `/opt/openalgo/yourdomain.com` produces something different. Always read the name rather than assuming it:

```bash
VOL=$(sudo docker volume ls --format '{{.Name}}' | grep 'openalgo_db$' | head -1)
echo "Backing up volume: $VOL"

sudo docker run --rm \
  -v "$VOL":/data \
  -v "$(pwd)":/backup \
  alpine tar czf /backup/db-backup-$(date +%Y%m%d).tar.gz -C /data .
```

{% hint style="warning" %}
**Check that your backup is not empty.** If you pass a volume name that does not exist, Docker silently creates a new empty volume and the archive succeeds with nothing in it:

```bash
ls -lh db-backup-*.tar.gz     # a few KB means it is empty
tar tzf db-backup-*.tar.gz | head    # should list openalgo.db and friends
```

{% endhint %}

Also copy your `.env`, which is the only file that cannot be regenerated:

```bash
sudo cp /opt/openalgo/.env /opt/openalgo/.env.backup-$(date +%Y%m%d)
```

***

### Rolling back a Docker upgrade

```bash
cd /opt/openalgo

# Go back to the previous commit
sudo git log --oneline -5          # find the commit you were on
sudo git checkout <previous-commit>

sudo docker compose down
sudo docker compose build --no-cache
sudo docker compose up -d
```

Restore the database only if the upgrade actually migrated it and you need the earlier schema — migrations are forward-only, so a rollback of code without the matching database can fail to start.

***

### After a Docker + custom domain upgrade

Check these in order:

```bash
# Container healthy
sudo docker compose ps

# App answering locally
curl -I http://127.0.0.1:5000/auth/check-setup

# Domain and certificate still good
curl -I https://yourdomain.com

# Certificate expiry unchanged
sudo certbot certificates
```

Then in the browser: log in, confirm the dashboard loads, and confirm live data updates — a working page with frozen prices means the WebSocket upgrade through nginx is not working, which is the one thing worth checking specifically on a custom-domain setup.

***

### Option 3: Desktop / Local — Update Scripts (Recommended)

OpenAlgo runs cross-platform — Windows, macOS and Linux desktops all have a one-command update path using the bundled scripts.

#### Windows

```bat
cd openalgo
install\update.bat
```

#### macOS / Linux

```bash
cd openalgo
bash install/update.sh
```

Both scripts detect a local (non-server) installation automatically and perform the same safe sequence: **back up all databases** (openalgo, logs, latency, sandbox, historify) to a timestamped `db\backup_<timestamp>\` folder → `git pull` → report any new `.env` variables → update dependencies via uv → run all database migrations. Your `.env` is never touched.

After the script finishes, start OpenAlgo as usual:

```bash
uv run app.py
```

You should see the configuration check pass and all databases initialize:

```
Configuration version check passed
INFO in telegram_db: Telegram database initialized successfully
INFO in base: Scheduler started
INFO in traffic_db: Initializing Traffic Logs DB at: sqlite:///db/logs.db
INFO in latency_db: Initializing Latency DB at: sqlite:///db/latency.db
INFO in auth_db: Initializing Auth DB
INFO in symbol: Initializing Master Contract DB
```

***

### Option 4: Manual Upgrade (any platform)

If you prefer to run the steps yourself, only the backup step differs by platform — everything else is identical on Windows, macOS and Linux.

#### 1. Backup the databases

**Windows (PowerShell):**

```powershell
cd openalgo
New-Item -ItemType Directory -Force db\backup | Out-Null
Copy-Item db\*.db db\backup\
Copy-Item db\historify.duckdb db\backup\ -ErrorAction SilentlyContinue
```

**macOS / Linux:**

```bash
cd openalgo
mkdir -p db/backup
cp db/*.db db/backup/ 2>/dev/null
cp db/historify.duckdb db/backup/ 2>/dev/null
```

#### 2. Pull the latest application code

```bash
git pull
```

#### 3. Update dependencies

```bash
uv sync
```

(Legacy pip setups: `pip install -r requirements.txt` inside your virtual environment.)

#### 4. Run the migration script

Migrations are idempotent — safe to run on every upgrade:

```bash
uv run upgrade/migrate_all.py
```

#### 5. Start OpenAlgo

```bash
uv run app.py
```

***

### Handling new environment variables

Newer releases often introduce new environment variables that OpenAlgo needs to function. **Do not recreate your `.env` from the sample** — merge instead:

1. Open `.sample.env` and check `ENV_CONFIG_VERSION` at the top. If it is newer than the version in your `.env`, new variables were added.
2. On startup, OpenAlgo's configuration check reports exactly which variables are missing.
3. Copy **only the missing lines** from `.sample.env` into your `.env` and set appropriate values, keeping all your existing settings (broker keys, `APP_KEY`, `API_KEY_PEPPER`, domain configuration) untouched.

The update scripts (`install/update.sh` on Linux/macOS, `install\update.bat` on Windows) print this comparison for you automatically.

{% hint style="warning" %}
**Never copy `APP_KEY` or `API_KEY_PEPPER` values from documentation or `.sample.env` into a real installation.** Generate your own:

```bash
python -c "import secrets; print(secrets.token_hex(32))"
```

And never change `API_KEY_PEPPER` on an installation that already has users or broker logins — it is used to hash passwords and encrypt broker tokens, and rotating it makes that data unrecoverable. If you genuinely need to rotate it, use the dedicated migration: `uv run python upgrade/rotate_pepper.py`.
{% endhint %}

***

### Post-Upgrade Checklist

* Configuration version check passes on startup (no missing variable warnings)
* All databases initialize correctly
* Scheduler, WebSocket proxy (port 8765) and ZeroMQ services are running
* Broker login works and the master contract downloads
* API requests and strategies function normally

If anything fails after an upgrade, check `log/errors.jsonl` first — it contains structured error details including full tracebacks.

***

### Optional: testing the gthread worker

OpenAlgo currently runs on Gunicorn's **eventlet** worker, which is retired software — Gunicorn 26 removes it entirely. An experimental migration to the threaded **gthread** worker is available for testing.

It is **opt-in and not the default**: a normal upgrade leaves you on eventlet with no change in behaviour.

If you would like to help test it, see [Migrating to gthread (Experimental)](/installation-guidelines/getting-started/gthread-migration).

####


# Migrating to gthread (Experimental)

OpenAlgo is moving off the **eventlet** worker and onto Gunicorn's threaded **gthread** worker. This page explains why, what changes, how to opt in, how to verify it, and how to go back.

{% hint style="warning" %}
**This is experimental and opt-in. It is not the default.**

If you upgrade and do nothing, OpenAlgo continues to run on eventlet exactly as before. Only set the variable described below if you are willing to test and report results.
{% endhint %}

**Branch:** [github.com/marketcalls/openalgo/tree/gthread](https://github.com/marketcalls/openalgo/tree/gthread) **Discussion and reports:** [issue #1722](https://github.com/marketcalls/openalgo/issues/1722)

***

### Why this migration is necessary

OpenAlgo has always run as `gunicorn --worker-class eventlet -w 1`.

**Eventlet is retired software, and Gunicorn 26 removed the eventlet worker entirely.** That pins OpenAlgo to `gunicorn>=25.0,<26` permanently — a version that will stop receiving fixes, with no upgrade path.

This is not a performance project. It is about not being stranded on a dead dependency.

Two options were evaluated and rejected before settling on gthread:

| Option             | Verdict                                                                                                                   |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------- |
| **Granian**        | Rejected. Its WSGI mode cannot provide the socket that `simple_websocket` needs, so Socket.IO WebSocket transport breaks. |
| **uvicorn / ASGI** | Deferred. Would require converting Flask to an ASGI application — a far larger change than the problem justifies today.   |
| **gthread**        | Chosen. Supported by Flask-SocketIO, keeps Flask and WSGI, and changes one launch flag rather than the framework.         |

***

### What actually changes

This is the single sentence that governs the whole migration:

> Under eventlet, code that does not yield is atomic relative to other greenlets. Under gthread it is not.

**Eventlet** uses cooperative green threads. Your code runs uninterrupted until it chooses to yield (on I/O, or an explicit sleep). Two requests never interleave in the middle of a calculation.

**gthread** uses real operating system threads. The OS can suspend a thread **anywhere** — between two lines, or between reading a dictionary and writing it back.

The practical consequence is that code which was *accidentally* safe under eventlet is genuinely racy under real threads. This matters most on a server that runs all day, places real orders, and is never restarted.

#### What this found

These were reproduced, not theorised:

* Order cancellation releasing blocked margin **twice**
* Expired-contract settlement releasing margin twice — triggerable by leaving two browser tabs open
* The symbol lookup going **blank during its daily refresh**, so a valid symbol briefly looks like it does not exist
* MCP quota admitting 7 and 8 concurrent requests against a configured limit of 5
* Sandbox catch-up and square-off sweeps each running twice
* A Python strategy launch path that could **deadlock before the strategy started**

{% hint style="info" %}
**If you run OpenAlgo on Windows or macOS with `uv run app.py`, you have never been on eventlet.** The development server uses standard threading. Every one of the issues above has been reachable on your setup all along.

The migration did not introduce them. It found them.
{% endhint %}

***

### What we gain from this

#### Strategic — the actual reason

* **Unblocks Gunicorn 26 and beyond.** Eventlet's removal currently pins OpenAlgo to `gunicorn<26` permanently.
* **Removes a retired dependency** that no longer has active maintenance.
* **Keeps Flask and WSGI.** No framework rewrite, unlike the ASGI route.
* **One launch flag changes**, not the architecture.

#### Correctness — the unexpected payoff

* Forced a full concurrency audit that surfaced **real money-path defects**: margin released twice on cancellation, the symbol cache blanking mid-refresh, duplicate sandbox sweeps.
* Those defects were **already live for every Windows and macOS user**, whose development server has always used real threads.
* Locking and lifecycle rules are now **documented and enforced by tests** rather than holding by accident.

#### Operational

* An **explicit, tunable thread budget** instead of an unbounded pool of green threads.
* Real OS threads are **visible to standard tooling** — `top`, `py-spy` and thread dumps all work normally, where green threads are invisible to them.
* Diagnostics report the **live worker class, thread count and open stream counts**.
* **No dependency change to adopt.** Gunicorn 25.3 already ships both workers.

#### Risk profile

* **Opt-in behind a single `.env` line**; the default is unchanged.
* **Rollback is deleting that line and restarting** — no rebuild, no dependency change.

{% hint style="info" %}
**This is not a performance improvement.** Expect broadly similar throughput. The value is being able to move to a supported Gunicorn, plus the correctness work the migration forced. Treat any claim that gthread makes OpenAlgo faster with suspicion.
{% endhint %}

***

### Who is affected by the switch itself

| How you run OpenAlgo                             | Uses eventlet today?      | Affected by this switch |
| ------------------------------------------------ | ------------------------- | ----------------------- |
| Docker                                           | Yes                       | **Yes**                 |
| Ubuntu server via `install.sh` (systemd + nginx) | Yes                       | **Yes**                 |
| Ubuntu multi-instance via `install-multi.sh`     | Yes                       | **Yes**                 |
| Windows / macOS desktop (`uv run app.py`)        | No — already real threads | No change               |

Windows and macOS desktop users do not run Gunicorn at all, so there is nothing to opt into. The concurrency fixes on the branch still benefit you.

***

### Current status

Being direct about readiness:

* **122 files changed, 41 commits**
* **Roughly 64% of tracked migration items complete** (70 of 109 actionable)
* Several known issues remain open and are recorded on the branch
* Three independent audits have already found cases where an earlier fix was itself wrong

Progress notes live in `docs/progress/gthread/` on the branch, and every item is tracked in `docs/plans/2026-08-01-gthread-migration-tracker.csv`.

**Do not run this on a production trading account you cannot afford to babysit.**

***

### Step 1 — Get the branch

The opt-in variable does nothing on code built from `main`. The worker-resolution logic only exists on the `gthread` branch, so you must switch the checkout first.

{% hint style="danger" %}
Take a backup before switching branches. On Ubuntu, `install/update.sh` backs up your databases automatically; for Docker, copy your `.env` and back up the `db/` volume yourself.
{% endhint %}

```bash
cd /opt/openalgo          # or wherever you cloned OpenAlgo
git fetch origin gthread
git checkout gthread
git pull origin gthread
```

Your `.env` is not tracked by git and is preserved.

***

### Step 2 — Opt in

Add **one line** to your `.env`:

```bash
OPENALGO_WORKER_CLASS = 'gthread'
```

That is sufficient. A safe thread count is chosen for you.

{% hint style="warning" %}
**Do not set the thread count on its own.** `OPENALGO_GUNICORN_THREADS` does nothing without the worker class, and Gunicorn's own default of one thread would let a single live strategy log or MCP stream block the entire server.
{% endhint %}

There is no dependency change. Gunicorn 25.3 — the version already pinned in OpenAlgo — ships **both** the eventlet and gthread workers.

***

### Step 3 — Apply it

#### Docker

```bash
cd /opt/openalgo
docker compose build
docker compose up -d
docker compose logs -f
```

`.env` is bind-mounted into the container, so the setting **survives `docker pull`** and does not require regenerating `docker-compose.yaml`.

#### Ubuntu server (systemd)

```bash
cd /var/python/openalgo
sudo bash install/update.sh
```

The updater rewrites `ExecStart` in your systemd unit, **backs up the previous unit first**, verifies the new one before touching dependencies, and **restores the backup automatically if the service fails to start**.

#### Ubuntu multi-instance

Each instance has its own `.env`. Set the variable per instance and re-run the updater for that instance.

{% hint style="warning" %}
Threads are per instance, so the host cost is `threads x instances`. With the default of 64 threads and 4 instances that is 256 request threads on one box. `install-multi.sh` prints the total; divide a per-host budget with `OPENALGO_GUNICORN_THREADS` if that is too high for your VPS.
{% endhint %}

***

### Step 4 — Verify it is actually running

Do not trust the `.env` file alone. Confirm the running process.

**Docker:**

```bash
docker logs openalgo-web 2>&1 | grep "Starting application"
# [OpenAlgo] Starting application on port 5000 with gthread (64 threads)...

docker top openalgo-web | grep worker-class
# ... gunicorn --worker-class gthread --threads 64 --workers 1 ...
```

**Ubuntu:**

```bash
systemctl cat openalgo | grep worker-class
ps -eo args | grep "[g]unicorn"
```

**In the web UI:** the admin runtime panel reports the live worker class, configured thread count, active thread count and open stream counts. Use it to see the real numbers under load rather than guessing.

***

### Tuning the thread count

The default is **64**, chosen because OpenAlgo holds a request thread for the entire life of certain connections:

```
required threads >=
    active Socket.IO clients x 2       (polling holds a GET and a POST)
  + live Python Strategy log streams   (each holds a thread until closed)
  + live MCP streams                   (same)
  + internal loopback reserve          (MCP, Telegram and WhatsApp re-enter the API)
  + requests parked in broker rate limiters
  + peak ordinary HTTP concurrency
  + failure and reconnect headroom
```

To override:

```bash
OPENALGO_GUNICORN_THREADS = '96'
```

| Behaviour                        | Value                                  |
| -------------------------------- | -------------------------------------- |
| Default when gthread is selected | 64                                     |
| Values below 16                  | raised to 16, with a warning           |
| Values above 512                 | permitted, with a warning about memory |
| Non-numeric                      | falls back to 64, with a warning       |

{% hint style="info" %}
**Market data does not consume Gunicorn threads.** The options tools, charting and scalping terminals stream over a direct WebSocket to the proxy on port 8765, and all tabs share a single connection. Opening the entire tools suite adds zero request threads.
{% endhint %}

***

### Rolling back

Removing the line and restarting is the entire rollback. No rebuild is needed.

**Docker:**

```bash
sed -i "/OPENALGO_WORKER_CLASS/d;/OPENALGO_GUNICORN_THREADS/d" .env
docker compose up -d
```

**Ubuntu:**

```bash
sudo sed -i "/OPENALGO_WORKER_CLASS/d;/OPENALGO_GUNICORN_THREADS/d" /var/python/openalgo/.env
cd /var/python/openalgo && sudo bash install/update.sh
```

To leave the branch entirely, `git checkout main` and rebuild or re-run the updater.

***

### Troubleshooting

**The log still says eventlet.** The image or unit was not rebuilt, or you are still on `main`. Confirm with `git rev-parse --abbrev-ref HEAD`, then rebuild.

**A warning names an unknown worker class.** The value is misspelled. Only `eventlet` and `gthread` are accepted; anything else falls back to eventlet **and warns**, so a typo cannot silently leave you thinking you are testing gthread.

**The service will not start after `update.sh`.** The updater restores the previous unit automatically. Check `install/logs/` for the run log, and `journalctl -u openalgo -n 50`.

**The server becomes unresponsive when a strategy is running.** Report it on issue #1722 with your thread count. This is exactly the failure mode the thread budget exists to prevent.

**"database is locked" errors.** Real threads make SQLite writers genuinely collide where green threads did not. A 15-second busy timeout and a retry for stale-snapshot conflicts are already in place — please report the full entry from `log/errors.jsonl`.

***

### What to test and report

Starting up is not evidence. What is genuinely useful:

* **Your broker, through a full trading day** — login, order placement, positions, and the roughly 3:00 AM IST token rollover
* **Live WebSocket streaming** — `/websocket/test` and the option chain tools under real market data
* **Python strategies** — especially multi-file strategies and scheduled start/stop
* **Sandbox mode** — order fills, square-off, expiry settlement
* **Telegram alerts, scalping and charting terminals**
* **Thread and stream counts from the admin runtime panel under real load** — these numbers are what will justify the final thread budget

Report on [issue #1722](https://github.com/marketcalls/openalgo/issues/1722) with your **broker, operating system, deployment method and thread count**. Negative results are as valuable as positive ones.

***

### When does this become the default

When it has been through real trading days, on real brokers, on both Docker and Ubuntu, without surprises. **There is no target date.**

OpenAlgo is self-hosted, so there is no central rollback: once a change is on `main`, it reaches your machine whenever you choose to update, and it cannot be recalled. That is precisely why this ships opt-in first and why the default will not change until the evidence supports it.

***

### FAQ

**Will this speed up OpenAlgo?** That is not the goal. Expect broadly similar throughput. The point is being able to move to a supported Gunicorn.

**Do I need to change my strategies?** No. Strategies run as isolated subprocesses, not inside the web worker.

**Does this affect the WebSocket proxy or ZeroMQ?** No. The proxy runs as its own process on port 8765, and the ZeroMQ bus is unchanged.

**Do I need Node.js or a frontend rebuild?** No. The branch carries a built frontend, as `main` does.

**Can I run one instance on gthread and another on eventlet?** Yes. The setting is per instance, and comparing the two on one host is a genuinely useful test.

**Is my data at risk?** The switch does not alter the database schema. Normal upgrade care still applies — take backups before switching branches.


# Static IP

### 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.

{% embed url="<https://www.youtube.com/watch?v=RhCzFg5FMmA>" %}

**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.

***


# Latency

## Overview

This document provides a comprehensive guide to understanding, measuring, and optimizing latency in OpenAlgo. After extensive performance engineering, we've reduced platform overhead by 95% (from 117ms to 5-10ms), making OpenAlgo one of the fastest retail algo trading platforms available.

<figure><img src="/files/oIrxUwG4JpO4Hhm7y6tw" alt=""><figcaption></figcaption></figure>

***

### Latency Concepts

#### Three Types of Latency

**1. Platform Latency (Internal Processing)**

**Definition:** Time spent processing within OpenAlgo, excluding broker API calls.

**Formula:**

```
Platform Latency = Total Time - Broker API Time - Network Overhead
                 = Validation + Authentication + Processing + Logging
```

**Components:**

* API key verification (cached): \~1ms
* Request validation: \~1-2ms
* Symbol lookup (cached): \~0.5ms
* Response formatting: \~1ms
* Async logging: \~1-2ms

**Target:** < 10ms **Current Performance:** 5-10ms ✅

**2. Broker API Latency (External Processing)**

**Definition:** Time spent communicating with and waiting for the broker's servers.

**Formula:**

```
Broker API Latency = Network RTT + Broker Processing
                   = (Client → Broker) + Processing + (Broker → Client)
```

**Components:**

* Network latency (one-way): \~20-40ms
* Broker order validation: \~5-10ms
* Exchange submission: \~10-20ms
* Network latency (return): \~20-40ms

**Typical Range:** 50-80ms **Cannot be optimized by OpenAlgo** (external dependency)

<figure><img src="/files/09mQlim6RNy0xpA0cDq9" alt=""><figcaption></figcaption></figure>

**3. Total Client Roundtrip (End-to-End)**

**Definition:** Complete time from client request to client receiving response.

**Formula:**

```
Total Client RTT = Network (Client → OpenAlgo) +
                   Flask Framework Overhead +
                   Platform Latency +
                   Broker API Latency +
                   Network (OpenAlgo → Client)
```

**Breakdown Example:**

```
Client → OpenAlgo network:     ~20-25ms
Flask request parsing:         ~10-15ms
Platform processing:            ~6ms
Broker API call:               ~60ms
Flask response formatting:      ~5ms
OpenAlgo → Client network:     ~20-25ms
────────────────────────────────────────
Total:                         ~125-145ms
```

***

### Measurement Methodology

#### How OpenAlgo Measures Latency

OpenAlgo uses high-precision timestamps to track latency at multiple points:

```python
# Simplified example of latency tracking
import time

# Request starts
request_start = time.time()

# Validation phase
validation_start = time.time()
validate_order_data(data)
validation_latency = (time.time() - validation_start) * 1000  # Convert to ms

# Broker API call
broker_start = time.time()
response = broker_api.place_order(data, auth_token)
broker_latency = (time.time() - broker_start) * 1000

# Response formatting
response_start = time.time()
formatted_response = format_response(response)
response_latency = (time.time() - response_start) * 1000

# Total time
total_latency = (time.time() - request_start) * 1000

# Calculate platform overhead
platform_overhead = total_latency - broker_latency
```

#### What Gets Stored in the Database

The `order_latency` table stores comprehensive metrics:

```sql
CREATE TABLE order_latency (
    id INTEGER PRIMARY KEY,
    order_id TEXT,
    broker TEXT,
    symbol TEXT,
    order_type TEXT,  -- PLACE, MODIFY, CANCEL, etc.
    rtt_ms REAL,      -- Broker API roundtrip time
    validation_latency_ms REAL,
    response_latency_ms REAL,
    overhead_ms REAL,  -- Platform processing overhead
    total_latency_ms REAL,
    status TEXT,
    timestamp DATETIME
);
```

#### Calculation Formulas Used in Code

```python
# 1. Platform Overhead
overhead_ms = validation_latency_ms + response_latency_ms + other_processing_ms

# 2. Total Latency
total_latency_ms = rtt_ms + overhead_ms

# 3. One-way Broker Latency (estimate)
one_way_latency = rtt_ms / 2

# 4. Client RTT (what Bruno/Postman measures)
client_rtt ≈ total_latency_ms + network_overhead + flask_overhead
           ≈ total_latency_ms + 35-50ms
```

***

### Performance Metrics

#### Current Performance (Post-Optimization)

**Live Mode**

```
┌─────────────────────────────────────┐
│ Metric              │ Before│ After │
├─────────────────────┼───────┼───────┤
│ API Key Verify      │ 90ms  │  1ms  │
│ Symbol Lookup       │ 10ms  │  1ms  │
│ Validation          │  5ms  │  2ms  │
│ Response Format     │  5ms  │  1ms  │
│ SocketIO Emit       │ 15ms  │  0ms* │
│ Logging             │  7ms  │  0ms* │
├─────────────────────┼───────┼───────┤
│ Platform Overhead   │ 117ms │  6ms  │
│ Broker API          │ 57ms  │ 60ms  │
├─────────────────────┼───────┼───────┤
│ Total Latency       │ 174ms │ 66ms  │
│ Bruno/Postman       │ 249ms │ 140ms │
└─────────────────────────────────────┘
* = Moved to async (non-blocking)
```

**Improvement:** 95% reduction in platform overhead

**Sandbox/Analyze Mode**

```
┌─────────────────────────────────────┐
│ Metric              │ Before│ After │
├─────────────────────┼───────┼───────┤
│ API Key Verify      │ 90ms  │  1ms  │
│ Symbol Lookup       │ 10ms  │  1ms  │
│ Position Queries    │ 30ms  │  5ms  │
│ Validation          │  5ms  │  2ms  │
├─────────────────────┼───────┼───────┤
│ Platform Overhead   │ 107ms │ 10ms  │
│ Quote API           │ 52ms  │ 55ms  │
├─────────────────────┼───────┼───────┤
│ Total Latency       │ 159ms │ 65ms  │
└─────────────────────────────────────┘
```

**Improvement:** 90% reduction in platform overhead

#### Performance by Order Type

| Order Type | Platform Overhead | Broker API | Total   |
| ---------- | ----------------- | ---------- | ------- |
| PLACE      | 5-8ms             | 50-70ms    | 60-75ms |
| MODIFY     | 5-7ms             | 40-60ms    | 50-65ms |
| CANCEL     | 4-6ms             | 30-50ms    | 40-55ms |
| SMART      | 6-9ms             | 50-70ms    | 60-80ms |
| BASKET     | 7-10ms per order  | 50-70ms    | 60-80ms |

***

### Optimization Details

#### 1. API Key Verification Caching

**Problem:** Argon2 verification taking 20-50ms per key, multiplied by number of keys.

**Solution:**

```python
# Two-tier cache system
verified_api_key_cache = TTLCache(maxsize=1024, ttl=3600)    # 1 hour for valid keys
invalid_api_key_cache = TTLCache(maxsize=512, ttl=300)       # 5 min for invalid keys

def verify_api_key(provided_api_key):
    cache_key = hashlib.sha256(provided_api_key.encode()).hexdigest()

    # Fast rejection
    if cache_key in invalid_api_key_cache:
        return None

    # Fast authentication
    if cache_key in verified_api_key_cache:
        return verified_api_key_cache[cache_key]

    # Full verification (only on cache miss)
    # ... Argon2 verification logic ...
```

**Security Maintained:**

* SHA256 hashing prevents plaintext storage
* TTL ensures credentials expire
* Cache invalidated on key changes
* Invalid keys cached separately

**Performance Gain:** 90-100ms → 1ms (99% improvement)

#### 2. Symbol Lookup Caching

**Problem:** Database query on every order for symbol validation.

**Solution:**

```python
symbol_cache = TTLCache(maxsize=10000, ttl=1800)  # 30 minutes

def get_symbol_cached(symbol, exchange):
    cache_key = f"{symbol}:{exchange}"

    if cache_key in symbol_cache:
        return symbol_cache[cache_key]

    symbol_obj = SymToken.query.filter_by(
        symbol=symbol,
        exchange=exchange
    ).first()

    symbol_cache[cache_key] = symbol_obj
    return symbol_obj
```

**Rationale:** Symbols rarely change during trading hours.

**Performance Gain:** 5-10ms → 0.5ms (90% improvement)

#### 3. Request-Level Position Caching

**Problem:** Same position queried 4-5 times in a single order flow.

**Solution:**

```python
class OrderManager:
    def __init__(self, user_id):
        self._position_cache = {}  # Request-level cache

    def _get_position_cached(self, symbol, exchange, product):
        cache_key = f"{symbol}:{exchange}:{product}"

        if cache_key in self._position_cache:
            return self._position_cache[cache_key]

        position = SandboxPositions.query.filter_by(...).first()
        self._position_cache[cache_key] = position
        return position
```

**Scope:** Cache cleared after each request.

**Performance Gain:** 20-30ms saved per order (eliminated 3-4 redundant queries)

#### 4. Asynchronous SocketIO Emissions

**Problem:** Main thread blocked while broadcasting to WebSocket clients.

**Solution:**

```python
# Before (blocking)
socketio.emit('order_event', {...})

# After (non-blocking)
socketio.start_background_task(
    socketio.emit,
    'order_event',
    {...}
)
```

**Performance Gain:** 10-20ms (main thread no longer waits)

#### 5. Async Logging and Alerts

**Problem:** Database logging and Telegram alerts blocking order response.

**Solution:**

```python
# Logging moved to thread pool
executor.submit(async_log_order, 'placeorder', request_data, response_data)

# Telegram alerts already async
telegram_alert_service.send_order_alert(...)
```

**Performance Gain:** 5-10ms (operations run in background)

***

### Monitoring and Troubleshooting

#### Using the Latency Dashboard

Navigate to `/latency` in your OpenAlgo instance:

**Features:**

1. **Real-time order latency tracking**
   * Last 100 orders with detailed breakdown
   * Color-coded performance indicators
2. **Performance metrics**
   * Average RTT (broker API time)
   * Success rate
   * SLA compliance (% orders under 150ms)
3. **Detailed breakdown modal**
   * Click any order to see full latency breakdown
   * Platform overhead vs broker API time
   * Validation, response, and overhead metrics

#### Performance Indicators

```
Green  (< 150ms):  Excellent - HFT-capable latency
Yellow (< 250ms):  Good - Suitable for scalping/arbitrage
Orange (< 400ms):  Acceptable - Fine for MFT/LFT
Red    (> 400ms):  Poor - Investigate immediately
```

#### Troubleshooting High Latency

**If Platform Overhead > 15ms:**

1. **Check cache hit rates**

   ```python
   # Add logging to see cache performance
   logger.info(f"Cache hit: {cache_key in verified_api_key_cache}")
   ```
2. **Look for database query issues**

   ```sql
   -- Check for slow queries
   EXPLAIN QUERY PLAN SELECT * FROM symtoken WHERE symbol=? AND exchange=?;
   ```
3. **Profile specific endpoints**

   ```python
   import cProfile
   cProfile.run('place_order(order_data)')
   ```

**If Broker API > 100ms:**

1. **Check server location**
   * Mumbai servers should see 50-70ms
   * Other locations may see 80-120ms
2. **Test broker connectivity**

   ```bash
   ping broker-api-endpoint.com
   traceroute broker-api-endpoint.com
   ```
3. **Check broker API status**
   * Look for broker-side slowdowns
   * Verify API rate limits not exceeded

**If Client RTT >> Total Latency:**

1. **Network issues between client and OpenAlgo**

   ```bash
   ping your-openalgo-server.com
   ```
2. **Flask server overloaded**
   * Check CPU/memory usage
   * Consider scaling up
3. **TLS/SSL handshake overhead**
   * Use keep-alive connections
   * Enable HTTP/2

***

### Best Practices

#### For Optimal Performance

1. **Host close to broker infrastructure**
   * Mumbai for Indian brokers
   * Singapore for some international brokers
2. **Use adequate server resources**
   * Minimum: 2 cores, 4GB RAM
   * Recommended: 4 cores, 8GB RAM for production
3. **Enable caching appropriately**

   ```python
   # Verify cachetools is installed
   pip install cachetools
   ```
4. **Monitor cache sizes**

   ```python
   logger.info(f"Symbol cache size: {len(symbol_cache)}")
   logger.info(f"API key cache size: {len(verified_api_key_cache)}")
   ```
5. **Use connection pooling for databases**
   * Already configured for PostgreSQL
   * SQLite uses NullPool (appropriate for file-based DB)

#### For Development

1. **Don't use ngrok for latency testing**
   * Adds 500-700ms of overhead
   * Fine for development, not performance measurement
2. **Test with realistic data**
   * Use actual symbols and exchanges
   * Test during market hours for realistic broker latency
3. **Profile before optimizing**

   ```python
   import time

   start = time.perf_counter()
   # Your code here
   duration = (time.perf_counter() - start) * 1000
   print(f"Operation took {duration:.2f}ms")
   ```
4. **Use the latency dashboard**
   * Check after each optimization
   * Compare before/after metrics

#### For Trading Strategies

1. **Know your strategy's latency requirements**
   * HFT: < 10ms (needs co-location)
   * Scalping: < 100ms (OpenAlgo is suitable ✅)
   * MFT: < 200ms (OpenAlgo is excellent ✅)
   * LFT: < 1000ms (OpenAlgo is more than sufficient ✅)
2. **Focus on strategy logic, not micro-optimization**
   * 50ms vs 60ms rarely matters for retail strategies
   * Strategy robustness matters more
3. **Test under realistic conditions**
   * Market hours have different latency than off-hours
   * High volatility affects broker processing time

***

### Formula Reference

#### Quick Reference

```
Platform Latency = Total - Broker API - Network
Broker API Latency = Network RTT + Processing
Client RTT = Network + Flask + Platform + Broker + Network

Total Latency = Platform Overhead + Broker API
Client RTT ≈ Total Latency + 40-60ms

One-way Network Latency ≈ (Client RTT - Total Latency) / 2
```

#### Estimation Formulas

```python
# Estimate broker one-way latency
broker_one_way = broker_api_latency / 2

# Estimate network overhead
network_overhead = client_rtt - total_latency

# Estimate Flask framework overhead
flask_overhead = network_overhead - (2 * avg_network_latency)

# SLA calculation
orders_under_150ms = count(total_latency < 150)
sla_percentage = (orders_under_150ms / total_orders) * 100
```

***

### Conclusion

With 95% reduction in platform overhead, OpenAlgo's latency is now limited by external factors:

1. **Broker API response time** (50-80ms) - Primary bottleneck
2. **Network latency** (20-40ms each way) - Geography-dependent
3. **Platform processing** (5-10ms) - Optimized ✅

For retail and institutional traders running MFT/LFT strategies, this performance is more than adequate. Focus on strategy development, risk management, and execution consistency rather than chasing microseconds.

**Remember:** The fastest trade isn't always the most profitable one. Strategy quality matters far more than latency for 99% of traders.

***


# Themes

OpenAlgo Themes

OpenAlgo features a sophisticated theming system powered by DaisyUI, offering 30 professionally designed themes that enhance your trading experience with beautiful, consistent, and accessible user interfaces.

<figure><img src="/files/mhVWFlePISVChxoTUoft" alt=""><figcaption></figcaption></figure>

### Overview

The OpenAlgo theming system provides:

* **30 Professional Themes**: Extensive color schemes from minimalist to vibrant
* **Mode-Specific Themes**: Visual distinction between Live and Analyze modes
* **Instant Switching**: Real-time theme changes without page reload
* **Persistent Preferences**: Your theme selection is saved across sessions
* **Responsive Design**: All themes are optimized for desktop, tablet, and mobile
* **Accessibility**: WCAG-compliant color contrasts and ARIA-friendly components

{% embed url="<https://www.youtube.com/watch?v=ZXDZ3BDKaLc>" %}

### Available Themes

OpenAlgo includes 30 carefully crafted themes to suit every preference:

#### Light Themes

* **light** - Clean, professional white interface
* **cupcake** - Soft pastels with warm tones
* **bumblebee** - Energetic yellow and black
* **emerald** - Fresh green with modern aesthetics
* **corporate** - Professional blue-gray palette
* **retro** - Nostalgic warm tones
* **valentine** - Romantic pink and red
* **garden** - Natural green and earthy colors
* **aqua** - Cool cyan and blue tones
* **lofi** - Muted, relaxed colors
* **pastel** - Gentle rainbow pastels
* **fantasy** - Whimsical purple and pink
* **wireframe** - Minimalist black and white
* **cmyk** - Vibrant print-inspired colors
* **autumn** - Warm orange and brown
* **acid** - Bright neon green and yellow
* **lemonade** - Refreshing yellow and white
* **winter** - Cool blues and whites
* **nord** - Scandinavian-inspired palette
* **sunset** - Warm orange to purple gradient

#### Dark Themes

* **dark** - Classic dark gray interface
* **synthwave** - Retro 80s neon aesthetics
* **cyberpunk** - Futuristic yellow and magenta
* **halloween** - Spooky orange and purple
* **luxury** - Elegant dark with gold accents
* **dracula** - *(Analyze Mode Only)* Deep purple vampire theme
* **business** - Professional dark blue-gray
* **coffee** - Rich brown and cream
* **night** - Deep blue-black palette
* **dim** - Muted dark gray

### Theme Usage

#### Live Mode (Production Trading)

When trading with real money in **Live Mode**, you have access to **29 themes** (all except dracula).

**Quick Theme Toggle (Navbar)**

The navbar includes a convenient theme switcher that toggles between:

* **Light Theme** - Default bright interface
* **Dark Theme** - Reduced eye strain for extended trading sessions

Simply click the sun/moon icon in the navigation bar to instantly switch.

**Full Theme Selection (Profile Page)**

For access to all 29 themes:

1. Navigate to **Settings → Profile**
2. Click the **Theme Preferences** tab
3. Browse the complete theme gallery
4. Click any theme to apply instantly
5. Your selection is automatically saved

**Note**: The dracula theme is **not available** in Live Mode as it is exclusively reserved for Analyze Mode.

#### Analyze Mode (Sandbox Environment)

The **Analyze Mode** provides a risk-free testing environment for validating strategies and API requests without executing real trades.

**Fixed Dracula Theme**

When you enter Analyze Mode:

* **Auto-Switch**: Theme automatically changes to `dracula`
* **Visual Indicator**: The distinctive purple dracula theme clearly signals you're in a safe testing environment
* **Locked Theme**: Theme switcher is disabled to prevent confusion
* **Safety Feature**: This ensures you always know when you're in test mode vs. live trading

**Why a Fixed Theme?**

The locked dracula theme in Analyze Mode serves critical purposes:

1. **Visual Confirmation**: Instantly recognize you're in test mode
2. **Prevent Confusion**: Avoid accidentally thinking you're in Live Mode
3. **Consistent Experience**: All users see the same interface in documentation and support
4. **Safety First**: Clear distinction reduces risk of accidental live trading

**Returning to Live Mode**

When you exit Analyze Mode:

* Your **previous theme is automatically restored**
* Theme switching becomes available again
* All 29 Live Mode themes are accessible

### How to Change Themes

#### Method 1: Quick Toggle (Navbar)

1. Locate the theme switcher icon in the navigation bar (sun/moon icon)
2. Click to toggle between light and dark themes
3. Change applies instantly

**Best For**: Quick switching during different times of day

#### Method 2: Full Selection (Profile Page)

1. Click **Settings** in the navigation menu
2. Select **Profile** from the dropdown
3. Navigate to the **Theme Preferences** tab
4. Browse the theme gallery showing all available themes
5. Click any theme card to preview and apply
6. Current theme is highlighted with a primary ring
7. Preview the color palette (primary, secondary, accent, success, error)

**Best For**: Exploring all themes and finding your perfect match

#### Method 3: Programmatic (Advanced)

Developers can change themes programmatically using the theme manager:

```javascript
// Set a specific theme
window.themeManager.setTheme('cyberpunk');

// Get current theme
const currentTheme = window.themeManager.getCurrentTheme();

// Check if in Analyze Mode
const isAnalyze = window.themeManager.isAnalyzeMode();

// Restore previous theme (after Analyze Mode)
window.themeManager.restorePreviousTheme();
```

### Technical Details

#### Technology Stack

OpenAlgo's theming system is built on modern web technologies:

* **DaisyUI**: `5.1.27` - Component library providing the 30 themes
* **Tailwind CSS**: `4.1.14` - Utility-first CSS framework foundation
* **PostCSS**: `8.4.49` - CSS processing and optimization
* **Autoprefixer**: `10.4.20` - Cross-browser compatibility

#### Theme Implementation

Themes are implemented using pure CSS custom properties (CSS variables):

```html
<!-- Theme is applied via data attribute -->
<html data-theme="cyberpunk">
```

This approach provides:

* **Zero Runtime JavaScript**: Themes are pure CSS, no JS overhead
* **Instant Switching**: CSS variable changes are immediate
* **Better Performance**: No JavaScript recalculation on theme change
* **SSR Compatible**: Themes work with server-side rendering

#### Storage & Persistence

Theme preferences are stored in two locations:

1. **localStorage**: Persists across browser sessions

   ```javascript
   localStorage.getItem('theme') // e.g., "dark"
   ```
2. **sessionStorage**: Maintains consistency during navigation

   ```javascript
   sessionStorage.getItem('theme') // Current session theme
   ```

#### Cross-Tab Synchronization

Theme changes automatically sync across browser tabs:

* Open multiple OpenAlgo tabs
* Change theme in one tab
* All other tabs update instantly via storage events

#### Flash Prevention

OpenAlgo prevents theme "flash" on page load using an Immediately Invoked Function Expression (IIFE):

```javascript
(function() {
    const savedTheme = localStorage.getItem('theme') || 'light';
    document.documentElement.setAttribute('data-theme', savedTheme);
})();
```

This sets the theme before the page renders, eliminating white flashes when using dark themes.

### Why We Chose DaisyUI

OpenAlgo selected **DaisyUI** as the UI component library for several strategic reasons:

#### 1. Extensive Theme Collection

DaisyUI provides 30+ professionally designed themes out of the box, allowing traders to customize their trading experience without requiring custom CSS development.

#### 2. Component-Rich Library

As the **most popular component library for Tailwind CSS**, DaisyUI offers:

* Pre-built, production-ready components
* Consistent design language across the platform
* Reduced development time for new features

#### 3. Performance Optimized

* **Zero Runtime JavaScript**: Components are pure CSS
* **Smaller Bundle Size**: No heavy JavaScript libraries
* **Faster Page Loads**: Critical for real-time trading applications

#### 4. Accessibility First

All DaisyUI components follow accessibility best practices:

* ARIA-compliant markup
* Keyboard navigation support
* Screen reader friendly
* WCAG color contrast standards

#### 5. Tailwind Integration

Seamless integration with Tailwind CSS utilities:

* Use both DaisyUI components and Tailwind utilities
* Consistent spacing, sizing, and color systems
* Full customization capability

#### 6. Mobile Responsive

Every theme and component works flawlessly across devices:

* Desktop trading stations
* Tablet interfaces
* Mobile trading on the go

#### 7. Active Development

DaisyUI is actively maintained with regular updates, bug fixes, and new features, ensuring OpenAlgo stays modern and secure.

### Customizing Themes (Advanced)

#### Tailwind Configuration

OpenAlgo's Tailwind configuration is minimal and extensible:

```javascript
// tailwind.config.mjs
import daisyui from 'daisyui';

export default {
  content: [
    "./templates/**/*.html",
    "./static/**/*.js",
  ],
  theme: {
    extend: {}
  },
  plugins: [daisyui]
}
```

#### Adding Custom Themes

Developers can add custom themes by extending the DaisyUI configuration:

```javascript
// tailwind.config.mjs
export default {
  plugins: [daisyui],
  daisyui: {
    themes: [
      "light",
      "dark",
      // ... other themes
      {
        mytheme: {
          "primary": "#0000ff",
          "secondary": "#ff00ff",
          "accent": "#00ffff",
          "neutral": "#3d4451",
          "base-100": "#ffffff",
        },
      },
    ],
  },
}
```

#### Theme Color Palette

Each DaisyUI theme includes these semantic color tokens:

| Token          | Purpose            | Examples                      |
| -------------- | ------------------ | ----------------------------- |
| `primary`      | Main brand color   | Buttons, links, active states |
| `secondary`    | Supporting color   | Secondary buttons, accents    |
| `accent`       | Highlight color    | Badges, special notifications |
| `neutral`      | Neutral elements   | Borders, dividers, disabled   |
| `base-100`     | Background color   | Page background               |
| `base-200`     | Subtle background  | Cards, containers             |
| `base-300`     | Borders & dividers | Input borders, separators     |
| `base-content` | Text color         | Body text, labels             |
| `info`         | Informational      | Info alerts, messages         |
| `success`      | Success states     | Profit, completed orders      |
| `warning`      | Warning states     | Pending, caution messages     |
| `error`        | Error states       | Loss, failed orders           |

### Browser Compatibility

OpenAlgo themes work across all modern browsers:

* ✅ Chrome/Edge 90+
* ✅ Firefox 88+
* ✅ Safari 14+
* ✅ Opera 76+
* ✅ Mobile browsers (iOS Safari, Chrome Mobile)

**Note**: Internet Explorer is not supported as it lacks CSS custom property support.

### Troubleshooting

#### Theme Not Changing

If your theme doesn't change:

1. **Clear Browser Cache**: Hard reload with `Ctrl+Shift+R` (Windows/Linux) or `Cmd+Shift+R` (Mac)
2. **Check localStorage**: Open DevTools → Application → Local Storage → verify `theme` key exists
3. **Disable Browser Extensions**: Some extensions may interfere with theme switching
4. **Try Incognito Mode**: Rules out extension conflicts

#### Theme Flashing on Page Load

If you see a white flash before the theme loads:

1. Ensure JavaScript is enabled in your browser
2. Check that the theme IIFE in `theme.js` is loading before the page renders
3. Verify no browser extensions are blocking inline scripts

#### Analyze Mode Theme Won't Change

This is **expected behavior**. The dracula theme is locked in Analyze Mode for safety. To change themes:

1. Exit Analyze Mode
2. Return to Live Mode
3. Select your preferred theme
4. Theme will be restored when you exit Analyze Mode again

#### Custom Theme Not Appearing

If you've added a custom theme:

1. Verify `tailwind.config.mjs` syntax is correct
2. Rebuild CSS: `npm run build:css`
3. Add theme name to `themes` array in `static/js/theme.js`
4. Restart the application server

### Credits & Acknowledgments

#### DaisyUI

OpenAlgo extends deep gratitude to [**Pouya Saadeghi**](https://github.com/saadeghi) and the DaisyUI team for creating an exceptional component library.

* **Project**: [github.com/saadeghi/daisyui](https://github.com/saadeghi/daisyui)
* **License**: MIT
* **Version**: 5.1.27
* **Purpose**: Powers the entire OpenAlgo user interface with beautiful, accessible components and extensive theming capabilities

#### Tailwind CSS

Thanks to [**Tailwind Labs**](https://tailwindcss.com/) for the utility-first CSS framework that forms the foundation of our design system.

* **Project**: [github.com/tailwindlabs/tailwindcss](https://github.com/tailwindlabs/tailwindcss)
* **License**: MIT
* **Version**: 4.1.14
* **Purpose**: Provides the utility classes and build system for rapid, consistent UI development

#### Community

Special thanks to the OpenAlgo community for feedback on themes, accessibility improvements, and user experience suggestions that make our platform better for everyone.

### Resources

#### Official Documentation

* **DaisyUI Themes**: [daisyui.com/docs/themes](https://daisyui.com/docs/themes/)
* **DaisyUI Components**: [daisyui.com/components](https://daisyui.com/components/)
* **Tailwind CSS**: [tailwindcss.com/docs](https://tailwindcss.com/docs)

#### OpenAlgo Documentation

* **Getting Started**: [docs.openalgo.in/getting-started](https://docs.openalgo.in/getting-started)


# V1

This directory documents the registered OpenAlgo v1 REST API and the separate WebSocket protocol. The source of truth for REST registration is `restx_api/__init__.py`; request validation is defined in `restx_api/schemas.py`, `restx_api/data_schemas.py`, and `restx_api/account_schema.py`.

## Base URLs

```
REST API:  http://127.0.0.1:5000/api/v1
WebSocket: ws://127.0.0.1:8765
```

Replace the local host with the configured HTTPS/WSS domain in a remote deployment.

## Authentication

Most POST endpoints accept the OpenAlgo API key as `apikey` in a JSON object. GET endpoints accept it as the `apikey` query parameter. Telegram and WhatsApp management endpoints may also accept `X-API-KEY`; the Telegram webhook authenticates with `X-Telegram-Bot-Api-Secret-Token` instead of an OpenAlgo key.

```json
{
  "apikey": "<your_app_apikey>"
}
```

Never put broker credentials or broker access tokens in these requests. The OpenAlgo API key resolves the active broker session server-side.

## Registered REST Inventory

The current v1 surface contains **61 method/path pairs**. A resource with both GET and POST counts as two endpoints.

### Order Management

| Method | Path                 | Documentation                                                             |
| ------ | -------------------- | ------------------------------------------------------------------------- |
| POST   | `/placeorder`        | [Place order](/api-documentation/v1/orders-api/placeorder)                |
| POST   | `/placesmartorder`   | [Place smart order](/api-documentation/v1/orders-api/placesmartorder)     |
| POST   | `/optionsorder`      | [Options order](/api-documentation/v1/orders-api/optionsorder)            |
| POST   | `/optionsmultiorder` | [Options multi-order](/api-documentation/v1/orders-api/optionsmultiorder) |
| POST   | `/basketorder`       | [Basket order](/api-documentation/v1/orders-api/basketorder)              |
| POST   | `/splitorder`        | [Split order](/api-documentation/v1/orders-api/splitorder)                |
| POST   | `/modifyorder`       | [Modify order](/api-documentation/v1/orders-api/modifyorder)              |
| POST   | `/cancelorder`       | [Cancel order](/api-documentation/v1/orders-api/cancelorder)              |
| POST   | `/cancelallorder`    | [Cancel all orders](/api-documentation/v1/orders-api/cancelallorder)      |
| POST   | `/closeposition`     | [Close positions](/api-documentation/v1/orders-api/closeposition)         |
| POST   | `/placegttorder`     | [Place GTT](/api-documentation/v1/orders-api/placegttorder)               |
| POST   | `/modifygttorder`    | [Modify GTT](/api-documentation/v1/orders-api/modifygttorder)             |
| POST   | `/cancelgttorder`    | [Cancel GTT](/api-documentation/v1/orders-api/cancelgttorder)             |
| POST   | `/gttorderbook`      | [GTT order book](/api-documentation/v1/orders-api/gttorderbook)           |

### Order And Account Information

| Method | Path            | Documentation                                                    |
| ------ | --------------- | ---------------------------------------------------------------- |
| POST   | `/orderstatus`  | [Order status](/api-documentation/v1/orders-api/orderstatus)     |
| POST   | `/openposition` | [Open position](/api-documentation/v1/orders-api/openposition)   |
| POST   | `/funds`        | [Funds](/api-documentation/v1/accounts-api/funds)                |
| POST   | `/margin`       | [Margin](/api-documentation/v1/accounts-api/margin)              |
| POST   | `/orderbook`    | [Order book](/api-documentation/v1/accounts-api/orderbook)       |
| POST   | `/tradebook`    | [Trade book](/api-documentation/v1/accounts-api/tradebook)       |
| POST   | `/positionbook` | [Position book](/api-documentation/v1/accounts-api/positionbook) |
| POST   | `/holdings`     | [Holdings](/api-documentation/v1/accounts-api/holdings)          |

### Market Data And Symbols

| Method | Path                      | Documentation                                                      |
| ------ | ------------------------- | ------------------------------------------------------------------ |
| POST   | `/quotes`                 | [Quote](/api-documentation/v1/data-api/quotes)                     |
| POST   | `/multiquotes`            | [Multiple quotes](/api-documentation/v1/data-api/multiquotes)      |
| POST   | `/depth`                  | [Market depth](/api-documentation/v1/data-api/depth)               |
| POST   | `/history`                | [Historical candles](/api-documentation/v1/data-api/history)       |
| POST   | `/intervals`              | [Supported intervals](/api-documentation/v1/data-api/intervals)    |
| GET    | `/ticker/<string:symbol>` | [Ticker-compatible history](/api-documentation/v1/data-api/ticker) |
| POST   | `/symbol`                 | [Symbol information](/api-documentation/v1/data-api/symbol)        |
| POST   | `/search`                 | [Symbol search](/api-documentation/v1/data-api/search)             |
| POST   | `/expiry`                 | [Expiry dates](/api-documentation/v1/data-api/expiry)              |
| GET    | `/instruments`            | [Instrument master](/api-documentation/v1/data-api/instruments)    |

### Options Analytics

| Method | Path                 | Documentation                                                           |
| ------ | -------------------- | ----------------------------------------------------------------------- |
| POST   | `/optionsymbol`      | [Resolve option symbol](/api-documentation/v1/data-api/optionsymbol)    |
| POST   | `/optionchain`       | [Option chain](/api-documentation/v1/data-api/option-chain)             |
| POST   | `/syntheticfuture`   | [Synthetic future](/api-documentation/v1/data-api/syntheticfuture)      |
| POST   | `/optiongreeks`      | [Option Greeks](/api-documentation/v1/data-api/optiongreeks)            |
| POST   | `/multioptiongreeks` | [Batch option Greeks](/api-documentation/v1/data-api/multioptiongreeks) |

### Calendar, Analyzer, And Preferences

| Method | Path               | Documentation                                                                    |
| ------ | ------------------ | -------------------------------------------------------------------------------- |
| POST   | `/market/holidays` | [Market holidays](/api-documentation/v1/utilities-api/holidays)                  |
| POST   | `/market/timings`  | [Market timings](/api-documentation/v1/utilities-api/timings)                    |
| POST   | `/analyzer`        | [Analyzer status](/api-documentation/v1/accounts-api/analyzer-status)            |
| POST   | `/analyzer/toggle` | [Toggle analyzer mode](/api-documentation/v1/accounts-api/analyzer-toggle)       |
| POST   | `/pnl/symbols`     | [Sandbox P\&L by symbol](/api-documentation/v1/accounts-api/pnl-symbols)         |
| GET    | `/chart`           | [Read chart preferences](/api-documentation/v1/accounts-api/chart-preferences)   |
| POST   | `/chart`           | [Update chart preferences](/api-documentation/v1/accounts-api/chart-preferences) |
| POST   | `/ping`            | [Authenticated ping](/api-documentation/v1/accounts-api/ping)                    |

There is no public `/api/v1/checkholiday` endpoint. Use `/market/timings` for a date; its response identifies holiday/closed sessions through the returned market schedule.

### Portfolio Analytics

| Method | Path                    | Documentation                                    |
| ------ | ----------------------- | ------------------------------------------------ |
| GET    | `/portfolio/benchmarks` | [Portfolio API](/api-documentation/v1/portfolio) |
| POST   | `/portfolio/backtest`   | [Portfolio API](/api-documentation/v1/portfolio) |
| POST   | `/portfolio/tearsheet`  | [Portfolio API](/api-documentation/v1/portfolio) |
| POST   | `/portfolio/holdings`   | [Portfolio API](/api-documentation/v1/portfolio) |

Portfolio endpoints are authenticated and read-only. The holdings resource reads the active broker account, but none of these resources places, modifies, or cancels an order.

### Messaging

| Method    | Path                    | Documentation                                                         |
| --------- | ----------------------- | --------------------------------------------------------------------- |
| GET, POST | `/telegram/config`      | [Telegram REST surface](/api-documentation/v1/utilities-api/telegram) |
| POST      | `/telegram/start`       | [Telegram REST surface](/api-documentation/v1/utilities-api/telegram) |
| POST      | `/telegram/stop`        | [Telegram REST surface](/api-documentation/v1/utilities-api/telegram) |
| POST      | `/telegram/webhook`     | [Telegram REST surface](/api-documentation/v1/utilities-api/telegram) |
| GET       | `/telegram/users`       | [Telegram REST surface](/api-documentation/v1/utilities-api/telegram) |
| POST      | `/telegram/broadcast`   | [Telegram REST surface](/api-documentation/v1/utilities-api/telegram) |
| POST      | `/telegram/notify`      | [Telegram REST surface](/api-documentation/v1/utilities-api/telegram) |
| GET       | `/telegram/stats`       | [Telegram REST surface](/api-documentation/v1/utilities-api/telegram) |
| GET, POST | `/telegram/preferences` | [Telegram REST surface](/api-documentation/v1/utilities-api/telegram) |
| POST      | `/whatsapp/notify`      | [WhatsApp notification](/api-documentation/v1/utilities-api/whatsapp) |

The Telegram resource contributes 11 method/path pairs. Its webhook acknowledges validated updates but does not yet dispatch them, and the REST broadcast handler currently returns zero delivery counts. Those limitations are documented on the Telegram page.

## WebSocket Protocol

WebSocket streaming is not mounted below `/api/v1`. Clients connect to the proxy on port `8765`, authenticate, and send action messages.

| Mode  | Documentation                                          |
| ----- | ------------------------------------------------------ |
| LTP   | [LTP subscription](/api-documentation/v1/websockets)   |
| Quote | [Quote subscription](/api-documentation/v1/websockets) |
| Depth | [Depth subscription](/api-documentation/v1/websockets) |

Supported actions are `authenticate`, `subscribe`, `unsubscribe`, `unsubscribe_all`, `subscribe_orders`, `unsubscribe_orders`, `get_broker_info`, `get_supported_brokers`, and `ping`.

## Order Constants

### Exchanges

`NSE`, `BSE`, `NFO`, `BFO`, `CDS`, `BCD`, `MCX`, `NCDEX`, `NCO`, `NSE_INDEX`, `BSE_INDEX`, `MCX_INDEX`, `GLOBAL_INDEX`, and `CRYPTO` are recognized by the shared validation constants. Broker capability metadata determines which subset is usable for the active broker.

### Products And Price Types

| Kind       | Values                                                   |
| ---------- | -------------------------------------------------------- |
| Product    | `MIS`, `CNC`, `NRML`                                     |
| Price type | `MARKET`, `LIMIT`, `SL`, `SL-M`                          |
| Action     | `BUY`, `SELL` (lowercase is normalized by order schemas) |

Regular order, smart-order, basket, split, and modify schemas accept numeric quantities. Fractional quantities are allowed only for `CRYPTO`; non-crypto quantities must be whole numbers. Options order quantities remain positive integers.

## Response And Status Conventions

Most JSON resources return `status: "success"` or `status: "error"`, but broker payloads are normalized only at the wrapper level and some resources intentionally return CSV, plain text, or an empty webhook acknowledgement. Treat each endpoint page as authoritative for its payload.

Common status codes are:

| Code | Meaning                                                                             |
| ---- | ----------------------------------------------------------------------------------- |
| 200  | Request handled successfully                                                        |
| 400  | Invalid JSON, schema validation failure, unsupported mode, or invalid request state |
| 401  | Missing or invalid authentication on endpoints that use 401                         |
| 403  | Invalid API key or operation blocked by mode/policy                                 |
| 404  | Broker module, symbol, order, or linked messaging user not found                    |
| 429  | Flask-Limiter rejected the request                                                  |
| 500  | Unhandled internal or broker error                                                  |

## Rate Limits

Defaults from `.sample.env` are `API_RATE_LIMIT="50 per second"`, `ORDER_RATE_LIMIT="10 per second"`, and `SMART_ORDER_RATE_LIMIT="10 per second"`. Some messaging endpoints use their own limiter. All values are deployment configuration and may contain compound semicolon-separated limits. See [rate limiting](/api-documentation/v1/rate-limiting).

## Client Libraries

The Python client is available as `openalgo` and is pinned by this application at `2.0.3`. Go and Node.js examples in `examples/` demonstrate direct REST integration; they are not declared here as separately versioned official SDK releases.




---

[Next Page](/llms-full.txt/1)

