NubraNubra API
Back to Blogs
API TradingPythonCodexTrading AutomationAlgo Trading

Build a Production-Ready EMA Crossover Algo in Minutes with Codex and the Nubra SDK

Harshvardhan Sthapak: Algo Trader & AnalystApril 5, 20267 min

Building an algo trading system usually takes more time than the strategy itself. A lot of effort gets spent understanding SDK flows, confirming method names, wiring authentication, fetching data correctly, and making sure execution code is stable enough to run continuously.

This is where the Nubra SDK matters. It gives developers a structured way to handle authentication, market data, and order execution inside one consistent interface. Instead of stitching together half-documented flows or guessing broker-specific behavior, you can build on top of a clear SDK layer and focus more on trading logic.

In this workflow, that SDK foundation was combined with Codex to generate a production-ready EMA crossover engine for the NIFTY 100 in minutes. The result was not just a sample script. It was a terminal-based system built around real authentication, real market data, real position handling, and real capital management.


The Strategy: EMA 20 Crossing EMA 50#

At the center of the system is a simple but widely used momentum framework.

The strategy uses EMA 20 as the fast moving average and EMA 50 as the slow moving average on 2-minute candles. A BUY signal is generated when the 20 EMA crosses above the 50 EMA, which suggests short-term strength is overtaking the broader recent trend. A SELL signal is generated when the 20 EMA crosses below the 50 EMA, which suggests weakening momentum.

On paper, the idea is straightforward. In production, however, the details matter. The system should not trigger repeatedly on the same condition, it should evaluate only fully closed candles, and it should maintain position state carefully so it knows when to enter, exit, or reverse. Once you scale that logic from one symbol to the full NIFTY 100 universe, strategy design quickly becomes a systems problem.


Why the SDK Was Important Here#

The Nubra SDK made this workflow practical because it removed a large amount of integration friction. Authentication, instrument resolution, historical data access, live OHLCV subscriptions, and market-order execution all had to work together inside one runtime loop. Without an SDK, a large part of the effort would have gone into reconstructing those platform-specific details manually.

Just as importantly, the full Nubra Master Docs were uploaded into Codex before any code generation began. That gave the model the latest SDK context, including the correct import path, real methods, expected data structures, and Nubra-specific runtime constraints. This was the step that reduced API guesswork and made the generated code materially more reliable.


The Process#

The workflow began by opening the Nubra documentation and downloading the complete Python SDK reference as a single Markdown file. That master document was then attached in Codex so the model had the full SDK surface in context.

Once the documentation was in place, the next step was to provide a detailed prompt that described the exact system to be built. The prompt did not stop at "create an EMA crossover strategy." It defined the full operating requirement: scan all NIFTY 100 stocks, run on 2-minute candles, authenticate through the terminal, load historical data, subscribe to live OHLCV candles, maintain rolling pandas DataFrames, calculate fresh EMA crossovers, manage capital dynamically, place market orders, handle reversals correctly, and keep the entire experience inside clean real-time terminal logs.

That combination of documentation plus a strongly defined prompt is what allowed Codex to reason about the build as a full system rather than as a disconnected collection of code snippets.


The Prompt Used#

This was the core prompt used to generate the system:

You are an expert Python quant developer tasked with building a fully automated EMA Crossover Algo Trading System using the Nubra Python SDK (nubra-sdk, import path nubra_python_sdk). The system must run entirely from the terminal, operate on 2-minute candles, and continuously scan all stocks in the NIFTY 100 universe. When started, it should authenticate through the Nubra SDK terminal flow using phone number, OTP, and MPIN input, then fetch the latest NIFTY 100 constituents, resolve all NSE stock instruments, load historical market data, subscribe to live OHLCV data, maintain rolling pandas DataFrames for each stock, and evaluate trading conditions continuously in real time without manual intervention. The strategy must use EMA 20 as the fast EMA and EMA 50 as the slow EMA, generate BUY signals when EMA 20 crosses above EMA 50 and SELL signals when EMA 20 crosses below EMA 50, act only on fresh crossovers, avoid duplicate signals on the same candle, and evaluate signals only on fully closed candles, not in-progress candles. The system must include capital management where the user enters initial capital in the terminal at startup, position sizing is calculated dynamically using a configurable per-trade allocation, capital is deducted when a position is opened and released with PnL adjustment when the position is closed, multiple concurrent positions across different stocks are supported, and capital is never over-allocated. The execution layer must use Nubra market orders, maintain per-stock position state as LONG, SHORT, or NONE, and if an opposite signal appears it must close the current position first and then open the new one. All interaction and output must remain in the terminal, with clean structured logs for startup, authentication, universe loading, historical warmup, websocket status, detected BUY or SELL signals, submitted and filled orders, open positions, available capital, and realized and unrealized PnL. The project should follow a clean modular architecture with separate modules for configuration and CLI input, Nubra SDK integration, strategy logic, capital management, execution engine, reporting, and the main runtime orchestrator. To avoid runtime errors, strictly follow Nubra-specific constraints: use nubra-sdk but import from nubra_python_sdk, batch historical API requests with a maximum of 5 symbols per request, respect historical API rate limits, use the OHLCV websocket for live 2-minute candles, treat websocket candle updates as the current in-progress candle and finalize a candle only when the next bucket begins, correctly convert price and monetary values from paise to rupees where needed, and include retry, reconnection, and graceful handling for API failures, missing instruments, socket disconnects, rejected orders, and order reconciliation so reserved capital does not get stuck. The final output must be fully working, production-ready Python code runnable from the terminal, with simple clear comments and a strong focus on correctness, reliability, simplicity, and stable real-time performance.

What made this prompt work was its specificity. It clearly defined the universe, the signal logic, the execution rules, the capital model, and the reliability requirements. That reduced ambiguity and pushed the generated code toward a production-ready structure instead of a basic indicator demo.


What Made the System Production-Ready#

The generated system was designed to do more than print crossover signals. It authenticated through the Nubra terminal flow, resolved instruments for the NIFTY 100 universe, warmed up strategy state with historical candles, and then moved into a live monitoring loop using OHLCV updates. For each symbol, it maintained rolling data, tracked fresh crossover conditions, and avoided duplicate actions on in-progress candles.

The design also included dynamic capital management, which is one of the most important differences between a strategy prototype and a usable trading system. Available capital was tracked in real time, position sizing was calculated from user-provided starting capital, and funds were reserved and released as trades opened and closed. Since the system supported multiple concurrent positions, it also had to prevent over-allocation and keep portfolio state consistent.

Equally important was observability. The prompt required the system to log startup events, authentication flow, historical warmup, websocket status, signal detection, order execution, open positions, available capital, and PnL snapshots in the terminal. That makes the output easier to monitor during live runtime and easier to debug when something goes wrong.


Demo Video#

If you want to embed the full walkthrough, place the demo video here:

This section works best if the video shows downloading the Nubra master docs, uploading the docs into Codex, pasting the master prompt, watching the system get generated, and reviewing the resulting architecture and terminal flow.


Final Thoughts#

This workflow shows what modern quant development is starting to look like. The SDK provides the operational foundation, the strategy defines the trading logic, and Codex accelerates the path from concept to runnable system.

For a strategy like 20 EMA crossing 50 EMA, the trading idea itself is simple. The hard part is everything around it: authentication, data handling, state management, capital allocation, execution sequencing, and runtime stability across a full market universe. That is exactly where documentation-grounded AI development becomes valuable.

When Codex is given the actual Nubra SDK docs and a well-structured prompt, it becomes much easier to move from idea to live-ready code without spending days on boilerplate and avoidable API mistakes. That is the real value here: faster iteration, cleaner implementation, and a much shorter path from strategy design to production testing.