From cc846b932542e40f6eeda00dc84c4550ed7812d4 Mon Sep 17 00:00:00 2001 From: pratik-urkude-algobulls Date: Sat, 2 Dec 2023 13:32:08 +0530 Subject: [PATCH] Deployed 81cd73e with MkDocs version: 1.5.3 --- brokers/non_auth_alpaca/index.html | 2 +- search/search_index.json | 2 +- sitemap.xml.gz | Bin 727 -> 727 bytes 3 files changed, 2 insertions(+), 2 deletions(-) diff --git a/brokers/non_auth_alpaca/index.html b/brokers/non_auth_alpaca/index.html index bda8fa6..a0b587e 100644 --- a/brokers/non_auth_alpaca/index.html +++ b/brokers/non_auth_alpaca/index.html @@ -1845,7 +1845,7 @@

Provide API And Secret keyimg.png

img.png

diff --git a/search/search_index.json b/search/search_index.json index 3cbb079..689497f 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Python Build","text":""},{"location":"#algobulls","title":"AlgoBulls","text":"

Welcome to AlgoBulls, the AI-powered trading platform that unlocks new dimensions in algorithmic trading. Our mission is to boost your expertise in designing and executing personalised trading strategies using our cutting-edge product - Python Build.

"},{"location":"#introducing-python-build-your-gateway-to-algorithmic-trading","title":"Introducing Python Build: Your Gateway to Algorithmic Trading","text":"

Python Build is your ultimate companion for crafting and executing trading strategies with the precision of a seasoned professional. Designed for both experienced traders and newcomers, this platform offers a range of powerful tools that empower you to make well-informed decisions and trade confidently in dynamic financial markets.

When it comes to strategy development, Python Build lets you dive into coding, backtesting, and deploying your trading strategies with remarkable ease. With an intuitive interface, you gain the ability to precisely set entry and exit points, handle multiple instruments, and take actions based on informed insights.

What sets Python Build apart is its adaptable strategy format, suitable for various trading styles. Whether you're into backtesting, paper trading, or live trading, the same strategy code works for all three, making the experience straightforward.

The library covers all scenarios (backtesting, paper trading, and live trading) during strategy execution or generating analytics. This unified approach ensures seamless transitions between these modes, eliminating the need for complex adjustments. Additionally, it simplifies the creation of progress logs, helping you track your journey and anticipate completion times. For real-time updates, live logs are available too, offering transparency and control over your trading endeavours.

Python Build's strength lies in its seamless integration with real-time market data sources, historical data, and trading platforms. Its adaptable nature enables connection with various data providers and broker APIs, ensuring access to the information you need for well-informed trading decisions.

"},{"location":"#powerful-stats-visual-analytics","title":"Powerful Stats & Visual Analytics","text":"

In the pursuit of successful trading, Python Build equips you with advanced visual tools for strategy analytics. These tools provide a deeper understanding of your strategies' performance, helping you manage risks and fine-tune your plans for optimal success. Visualisations facilitate data-driven decision-making, giving you clearer insights into the intricacies of your trading activities.

"},{"location":"#multiple-platforms-to-use-python-build","title":"Multiple Platforms to use Python Build","text":"

To support our diverse community of users, we have the options of two dynamic platforms for our users to use Python Build - pyalgotrading and Python Build Web

Explore our Python Package: Pyalgotrading

Dive into the amazing Features of our Web-App: Python Build Web

"},{"location":"#join-the-community","title":"Join the Community","text":"

AlgoBulls is more than just a platform; it's a community. Connect, learn, and collaborate with traders and developers. Code your strategies or explore ours \u2013 AlgoBulls is where innovation meets trading expertise.

By becoming part of the Python Build community, you tap into a rich network of traders and developers. This community serves as a platform for collaboration, offering guidance, valuable insights, and collective refinement of trading strategies. Diverse perspectives help you approach trading challenges from multiple angles, fostering growth and improvement.

Join us in this journey as AlgoBulls revolutionizes algorithmic trading!

In essence, Python Build is more than a product; it's your comprehensive guide to mastering algorithmic trading. With its user-friendly interface, diverse functionalities, and seamless integration, it's a valuable asset for traders of all levels. By simplifying strategy crafting, integration, execution, and analysis, Python Build empowers you to navigate the trading world with confidence and precision.

"},{"location":"#open-source-strategy-library","title":"Open Source Strategy Library","text":"

We maintain an open source GitHub repository, pyalgostrategypool containing fully functional algorithmic trading strategies. These strategies can be used for Backtesting, Paper Trading, or Live Trading across various brokers and exchanges. The same code works in all trading modes.

Keep an eye on our GitHub repo

Our team periodically updates the library to add more strategy Python codes

For those new to algorithmic trading or Python Build, exploring included example strategies is an excellent starting point. These strategies are pre-built scenarios showcasing different trading strategies and concepts. By studying and experimenting with these examples, you'll gain a deeper grasp of how Python Build operates and how strategies are constructed.

Here's what you can do with the example strategies:

Remember, these example strategies lay the foundation for your learning journey. As you grow more familiar with the library, you can create and customise your own strategies based on your insights and preferences.

To conclude, the installation process readies you to use Python Build, while the documentation and example strategies empower you to explore the library's capabilities and apply them to real trading situations. Whether you're a beginner or a seasoned trader...

"},{"location":"#limitations-of-python-build","title":"Limitations of Python Build","text":"

In the exciting world of algorithmic trading, Python Build offers numerous benefits and considerations for traders and developers. Let's also acknowledge its limitations to help you make an informed decision.

  1. Python Speed Limitations: While versatile, Python isn't the fastest language for computation. This may pose challenges for complex strategies requiring extensive calculations. Our team is actively transitioning a major part of the codebase to Cython to enhance speed while retaining Python's simplicity. We're also exploring options like GPUs for the future.

  2. Cloud Cold-Start Speed Limitations: Each strategy runs on a dedicated virtual server in the cloud. While this ensures secure execution with dedicated resources, there's a short delay as the cloud fetches the resource before strategy execution begins. This minor delay is part of our ongoing optimization efforts.

Note

Our team is working round the clock to make these limitations a thing of the past.

"},{"location":"#references","title":"References","text":"

To unleash Python Build's full potential, dive into its comprehensive documentation. This roadmap offers detailed insights into the product's features, functionalities, and capabilities. It's your go-to resource for harnessing the power of Python Build effectively. The documentation includes:

"},{"location":"analytics/pyalgotrading_analytics/","title":"Pyalgotrading Analytics","text":""},{"location":"analytics/pyalgotrading_analytics/#metric-values-and-statistics","title":"Metric Values and Statistics","text":""},{"location":"analytics/pyalgotrading_analytics/#cumulative-returns","title":"Cumulative Returns","text":""},{"location":"analytics/pyalgotrading_analytics/#end-of-year-returns-eoy","title":"End of Year Returns (EoY)","text":""},{"location":"analytics/pyalgotrading_analytics/#distributions-of-monthly-returns-histogram","title":"Distributions of Monthly Returns (Histogram)","text":""},{"location":"analytics/pyalgotrading_analytics/#daily-returns","title":"Daily Returns","text":""},{"location":"analytics/pyalgotrading_analytics/#rolling-volatility-6-months","title":"Rolling Volatility (6 months)","text":""},{"location":"analytics/pyalgotrading_analytics/#rolling-sharpe-6-months","title":"Rolling Sharpe (6 months)","text":""},{"location":"analytics/pyalgotrading_analytics/#rolling-sortino-6-months","title":"Rolling Sortino (6 months)","text":""},{"location":"analytics/pyalgotrading_analytics/#worst-5-drawdown-periods","title":"Worst 5 Drawdown Periods","text":""},{"location":"analytics/pyalgotrading_analytics/#underwater-plot","title":"Underwater Plot","text":""},{"location":"analytics/pyalgotrading_analytics/#monthly-returns-heatmap","title":"Monthly Returns (Heatmap)","text":""},{"location":"analytics/python-build-view-results/","title":"Python build view results","text":""},{"location":"analytics/python-build-view-results/#how-to-view-the-results","title":"How to view the Results?","text":"

Once you start the strategy, it may take a while for it to complete the execution. You can switch to the Analytics tab after you run your strategy. Even if the strategy execution is not complete, you will still see intermediate results.

Analytics: In the analytics section, you can view a strategy\u2019s Stats & various other metrics in the form of graphs like P&L.

"},{"location":"analytics/python-build-view-results/#stats","title":"Stats","text":"

In this section you can see the total returns, sharpe ratio, sortino ratio, volatility, Max Drawdown, Total wins or Loses, Total short or long trades, hit ratio, number of trades, average trades per day, max profit, max loss, average profit per winning trade, average loss per losing trade.

"},{"location":"analytics/python-build-view-results/#cumulative-returns","title":"Cumulative Returns","text":""},{"location":"analytics/python-build-view-results/#profit-loss-currency-or","title":"Profit & Loss (Currency or %)","text":"

The trade by trade P&L in Currency or Percentage.

"},{"location":"analytics/python-build-view-results/#end-of-year-returns-plot","title":"End of Year Returns Plot (%)","text":""},{"location":"analytics/python-build-view-results/#monthly-returns-histogram","title":"Monthly Returns Histogram (%)","text":""},{"location":"analytics/python-build-view-results/#monthly-returns-heatmap","title":"Monthly Returns Heatmap (%)","text":""},{"location":"analytics/python-build-view-results/#daily-returns","title":"Daily Returns (%)","text":""},{"location":"analytics/python-build-view-results/#underwater-drawdown-plot","title":"Underwater Drawdown Plot (%)","text":""},{"location":"analytics/python-build-view-results/#pl-book","title":"P&L Book","text":"

View detailed trade by trade report. Premium users can analyze this data in the form of heatmaps for Gross Profit & Loss, Trading Volume & Total number of Trades.

"},{"location":"analytics/python-build-view-results/#user-log","title":"User Log","text":"

Real-time logs from strategy execution are displayed in this section. Use these logs to debug your strategy\u2019s behavior and performance.

"},{"location":"analytics/python-build-view-results/#order-history","title":"Order History","text":"

View the order state transition for every order placed by your strategy in-depth.

"},{"location":"brokers/broker_alpaca_guide/","title":"Alpaca","text":"

Alpaca is a technology company that offers a modern, developer-friendly trading platform designed for algorithmic and automated trading in the financial markets, particularly focused on equities and cryptocurrencies. The company provides APIs ( Application Programming Interfaces) that allow developers and traders to access market data, execute trades, and build their own algorithmic trading strategies.

Key features and offerings of Alpaca include:

  1. APIs and SDKs: Alpaca offers APIs and software development kits (SDKs) that enable developers to programmatically access real-time and historical market data, as well as execute trades on various exchanges.

  2. Algorithmic Trading: Alpaca's platform is tailored for algorithmic trading strategies, where traders can automate trading decisions based on predefined conditions and rules.

  3. Paper Trading: Alpaca provides a simulated environment called \"paper trading,\" allowing traders to test their strategies in a risk-free setting before deploying them with real money.

  4. Market Data: The platform offers access to real-time and historical market data, which is crucial for building and testing trading strategies.

  5. Order Execution: Traders can use Alpaca's API to execute trades on supported exchanges. This includes submitting market, limit, and stop orders.

  6. Customizable Dashboards: Alpaca provides customizable dashboards and interfaces to monitor trading activity and portfolio performance.

  7. Brokerage Services: Alpaca acts as a brokerage, providing services that allow traders to execute their strategies on supported exchanges.

  8. Regulatory Compliance: Alpaca operates within the regulations of the financial industry, ensuring compliance with rules and requirements.

Alpaca's platform aims to democratize algorithmic trading by providing accessible tools and resources for both individual traders and developers. It's worth noting that the landscape of algorithmic trading and financial technology is constantly evolving, so it's a good idea to check Alpaca's official website for the most current information about their offerings and services.

"},{"location":"brokers/broker_alpaca_guide/#advantages-of-binding-alpaca-with-your-algobulls-account","title":"Advantages of binding Alpaca with your AlgoBulls account","text":""},{"location":"brokers/broker_alpaca_guide/#how-to-bind-alpaca-with-your-algobulls-account","title":"How to bind Alpaca with your AlgoBulls account?","text":"

You can connect your Alpaca account with AlgoBulls in two ways: OAuth and Non-OAuth.

WARNING: We have discontinued the Non-OAuth method in accordance with Alpaca\u2019s recommendations. Please use the OAuth method for seamless integration and improved security. Be mindful of this update as you proceed with your integrations.

"},{"location":"brokers/connecting_alpaca/","title":"OAuth","text":"

Embark on a streamlined and secure journey as you bind your Alpaca broker with AlgoBulls through OAuth integration. This seamless process ensures a robust connection between your accounts, allowing for efficient data exchange and trading activities. With OAuth binding, you can experience the convenience of a secure link without compromising on the integrity of your financial operations. Follow our comprehensive guide to effortlessly set up OAuth binding and unleash the full potential of AlgoBulls with Alpaca integration.

"},{"location":"brokers/connecting_alpaca/#an-overview","title":"An overview","text":""},{"location":"brokers/connecting_alpaca/#how-to-set-up-alpaca-for-trading-in-algobulls-with-oauth","title":"How to set up Alpaca for trading in AlgoBulls with OAuth?","text":"

Before this step, please make sure you have an Alpaca account. Click here to visit the Alpaca site for creating your account.

"},{"location":"brokers/connecting_alpaca/#add-broker","title":"Add Broker","text":""},{"location":"brokers/connecting_alpaca/#search-for-alpaca","title":"Search for Alpaca","text":"

"},{"location":"brokers/connecting_alpaca/#provide-permission","title":"Provide Permission","text":"

WARNING: We have discontinued the Non-OAuth method in accordance with Alpaca\u2019s recommendations. Please use the OAuth method for seamless integration and improved security. Be mindful of this update as you proceed with your integrations.

"},{"location":"brokers/non_auth_alpaca/","title":"Non-OAuth","text":"

WARNING: We have discontinued the Non-OAuth method in accordance with Alpaca\u2019s recommendations. Please use the OAuth method for seamless integration and improved security. Be mindful of this update as you proceed with your integrations.

If you are seeking an alternative to OAuth, the Non-OAuth binding option provides a straightforward and reliable approach to connect your Alpaca broker with AlgoBulls. This method ensures a direct and effective link between your accounts, maintaining the simplicity and efficiency that defines the AlgoBulls experience. Discover the step-by-step process to establish Non-OAuth binding and gain immediate access to the powerful synergy between AlgoBulls and Alpaca, facilitating seamless trading and data synchronisation.

"},{"location":"brokers/non_auth_alpaca/#how-to-set-up-alpaca-for-trading-in-algobulls-with-non-oauth","title":"How to set up Alpaca for trading in AlgoBulls with Non-OAuth?","text":"

Before trying to bind your broker, please make sure you have an Alpaca account or follow the steps given below to create your account.

"},{"location":"brokers/non_auth_alpaca/#create-your-alpaca-account","title":"Create your Alpaca Account","text":""},{"location":"brokers/non_auth_alpaca/#api-keys","title":"API keys","text":" "},{"location":"brokers/non_auth_alpaca/#add-broker","title":"Add Broker","text":""},{"location":"brokers/non_auth_alpaca/#search-for-alpaca-non-oauth","title":"Search for Alpaca Non-OAuth","text":""},{"location":"brokers/non_auth_alpaca/#provide-api-and-secret-key","title":"Provide API And Secret key","text":" "},{"location":"gen_ai/gen_ai_prompt_library/","title":"Prompt Library for Gen AI","text":""},{"location":"gen_ai/gen_ai_prompt_library/#here-are-some-prompts-for-creating-strategy-using-genai","title":"Here are some prompts for Creating Strategy using GenAI","text":""},{"location":"gen_ai/gen_ai_prompt_library/#moving-averages-ema-or-sma","title":"Moving Averages (EMA or SMA)","text":"

Create a trading strategy which takes a BUY trade when EMA cuts SMA upwards and a SELL trade when EMA cuts SMA downwards. While placing a trade, if a previous position is open, it should be exited before placing the new trade\n
Create a strategy which uses 2 EMAs of different time periods, and it BUYs when EMA of timeperiod 1 crosses the EMA of timeperiod 2 upwards and SELLs when EMA of timeperiod 1 crosses the EMA of timeperiod 2 downwards.\n
Create a trading strategy which takes a BUY trade when EMA cuts SMA upwards and a SELL trade when EMA cuts SMA downwards. While placing a trade, if a previous position is open, it should be exited before placing the new trade\n
Develop a strategy that generates a BUY signal when a shorter-term moving average crosses above an intermediate-term moving average, which then crosses above a longer-term moving average. Conversely, generate a SELL signal when the moving averages crossover in the opposite direction.\n

"},{"location":"gen_ai/gen_ai_prompt_library/#relative-strength-index-rsi","title":"Relative Strength Index (RSI)","text":"

Create a strategy that uses RSI indicator to give signals based on over bought or over sold conditions. If RSI is above 70, the strategy should generate a SELL signal and if it's below 30, it should generate a BUY signal\n
Create a strategy using RSI of MACD-signal of close with fast MA period as X, slow MA period as Y and signal period as Z, which will SELL on crossing the upper band and BUY on crossing the lower band\n
Create a trading strategy which takes BUY when RSI crosses lower band and create a SELL when RSI crosses the upward band, set a stop loss of 2% and target to be 15%.\n
Create a trading strategy using RSI technical indicator\n
Create a strategy using RSI of MACD-signal of close with fast MA period as X, slow MA period as Y and signal period as Z, which will SELL on crossing the upper band and BUY on crossing the lower band\n
Please help me with a strategy that uses RSI indicator to give signals based on over bought or over sold conditions. If RSI is above 70, the strategy should generate a SELL signal and if it's below 30, it should generate a BUY signal\n
Create a trading strategy which takes BUY when RSI crosses lower band and create a SELL when RSI crosses the upward band, set a stop loss of 2% and target to be 15%.\n

"},{"location":"gen_ai/gen_ai_prompt_library/#aroon","title":"Aroon","text":"
Create a trading strategy that utilizes the Aroon indicator to generate signals based on overbought or oversold conditions. If the Aroon Up line crosses below the Aroon Down line and falls below 30, the strategy should generate a BUY signal. Conversely, if the Aroon Up line crosses above the Aroon Down line and rises above 70, the strategy should generate a SELL signal\n
"},{"location":"gen_ai/gen_ai_prompt_library/#stochastic","title":"Stochastic","text":"

Develop a trading strategy that incorporates the stochastic crossover to generate signals. When the %K line crosses above the %D line and both lines are below 30, the strategy should generate a BUY signal. Similarly, when the %K line crosses below the %D line and both lines are above 70, the strategy should generate a SELL signal\n
Develop a strategy that generates a BUY signal when the Stochastic RSI indicator crosses above the oversold level (e.g., 20) and a SELL signal when it crosses below the overbought level (e.g., 80).\n

"},{"location":"gen_ai/gen_ai_prompt_library/#bollinger-bands-bb","title":"Bollinger Bands (BB)","text":"
Develop a strategy that generates a BUY signal when the price breaks above the upper Bollinger Band. Similarly, generate a SELL signal when the price breaks below the lower Bollinger Band\n
"},{"location":"gen_ai/gen_ai_prompt_library/#atr-volatility","title":"ATR (Volatility)","text":"
Develop a strategy that generates a BUY signal when the price surpasses a multiple of the ATR above a recent swing high, indicating increased volatility and potential upward momentum. Conversely, generate a SELL signal when the price drops below a multiple of the ATR below a recent swing low, indicating increased volatility and potential downward momentum.\n
"},{"location":"gen_ai/gen_ai_prompt_library/#moving-average-convergence-divergence-macd","title":"Moving Average Convergence Divergence (MACD)","text":"
Create a strategy that generates a BUY signal when the MACD histogram bars cross above the zero line and a SELL signal when the histogram bars cross below the zero line.\n
"},{"location":"gen_ai/gen_ai_prompt_library/#volume-weighted-average-price-vwap","title":"Volume Weighted Average Price (VWAP)","text":"
Create a strategy that generates a BUY signal when the price rises above the VWAP line and a SELL signal when the price drops below the VWAP line, indicating potential shifts in supply and demand.\n
"},{"location":"gen_ai/gen_ai_prompt_library/#miscellaneous","title":"Miscellaneous","text":"
Create a strategy that generates a BUY signal when the price crosses above the cloud (Span A and Span B) and the cloud changes color from red to green. Conversely, generate a SELL signal when the price crosses below the cloud and the cloud changes color from green to red.\n
Develop a strategy that generates a BUY signal when the price crosses above the Parabolic SAR dots and a SELL signal when the price crosses below the dots.\n
Implement a gap and go strategy that capitalizes on the momentum created by price gaps at the market open. When the price gaps up significantly and continues to move higher, generate a BUY signal. Similarly, when the price gaps down substantially and continues to move lower, generate a SELL signal.\n
"},{"location":"gen_ai/get_open_ai_keys/","title":"OpenAI","text":""},{"location":"gen_ai/get_open_ai_keys/#what-is-chat-gpt","title":"What is Chat-GPT ?","text":"

Generative AI involves creating new content using machine learning. A key method is GANs, where a generator creates data and a discriminator evaluates its realism. Another method is VAEs, which encode and decode data. ChatGPT is a specific AI model using generative text, like a conversation. It can understand context, answer questions, and generate text in a human-like manner. It finds use in various fields, from text generation to customer service, but also raises concerns about accuracy and responsible use.

"},{"location":"gen_ai/get_open_ai_keys/#why-we-use-chat-gpt","title":"Why we use Chat-GPT ?","text":"

ChatGPT can assist in generating code for algorithmic trading strategies. It can translate strategy ideas into code snippets, provide coding guidance, and help with customization. However, human expertise is essential to validate, optimize, and manage risks in the complex realm of algorithmic trading.

"},{"location":"gen_ai/get_open_ai_keys/#how-to-get-chat-gpt-api-keys","title":"How to get Chat-GPT API keys ?","text":"

To get your chat GPT API keys, you can watch the video given below

Or

You can simply follow the steps here:

"},{"location":"gen_ai/get_open_ai_keys/#step-1-loginsignup","title":"Step 1 - Login/Signup","text":"

Login or Signup in your open AI account, you can use gmail account, microsoft account or apple account to signup.

"},{"location":"gen_ai/get_open_ai_keys/#step-2-open-your-profile","title":"Step 2 - Open Your Profile","text":"

Once you are on the home page of your account, you can select your profile on top-right corner, and then select the option View API Keys from the drop-down menu.

"},{"location":"gen_ai/get_open_ai_keys/#step-3-generate-new-secret-keys","title":"Step 3 - Generate New Secret Keys","text":"

Now that you are in the API Keys section, you will have to create a new key.

"},{"location":"gen_ai/get_open_ai_keys/#step-4-get-secrete-keys","title":"Step 4 - Get Secrete Keys","text":"

On clicking Create new secret key a pop-up will appear, where you can enter the key name, which is for your reference to remember multiple secret keys, once done, there will be another section where you can copy the open-ai secret keys.

"},{"location":"gen_ai/get_open_ai_keys/#step-5-ready-to-go-with-algobulls","title":"Step 5 - Ready to go with AlgoBulls","text":"

Once you have copied your secret key then you can now save it on your AlgoBulls Account for accessing the gen-ai feature to create a strategy, and there you go. To know how to save keys and start with generating strategies using Chat-GPT, click here Happy Trading !

"},{"location":"pyalgotrad/brokerage/","title":"Brokerage","text":""},{"location":"pyalgotrad/brokerage/#brokerage","title":"Brokerage","text":""},{"location":"pyalgotrad/brokerage/#how-to-use","title":"How to Use","text":"

To incorporate slippage and brokerage into your backtesting, simply pass the desired values for slippage_percent, broker_commission_percentage, and broker_commission_price when calling the algobulls_connection.get_backtesting_report_pnl_table function. These parameters help you account for real-world trading costs and execution variations, making your backtesting results more realistic.

"},{"location":"pyalgotrad/brokerage/#example","title":"Example","text":"
import algobulls_connection\n# Fetch PnL data for a trading strategy with custom slippage and brokerage settings\npnl_table = algobulls_connection.get_backtesting_report_pnl_table(\n    strategy_code=\"your_strategy_code\",\n    show_all_rows=True,\n    force_fetch=True,\n    country='USA',\n    broker_commission_percentage=1.5,  # Adjust brokerage percentage as needed\n    broker_commission_price=0.3,      # Adjust fixed brokerage cost as needed\n    slippage_percent=4.5,             # Adjust slippage percentage as needed\n)\n# Print the PnL table with custom slippage and brokerage settings\nprint(pnl_table)\n
"},{"location":"pyalgotrad/introduction/","title":"pyalgotrading","text":""},{"location":"pyalgotrad/introduction/#introduction","title":"Introduction","text":"

Welcome to the Pyalgotrading Documentation \u2013 your guide to practising and acquainting yourself with the pyalgotrading package. Pyalgotrading, built with Python, is an algorithmic trading library that empowers you to design and implement trading strategies on a variety of financial instruments, such as equities, futures, and options. To embark on your journey with Pyalgotrading, ensure you have an active AlgoBulls account, a platform designed for creating and testing trading strategies.

"},{"location":"pyalgotrad/introduction/#key-features","title":"Key Features","text":"

Backtesting, Paper Trading and Real Trading can be performed on the same strategy code base!

Prerequisites

Before you commence development, make sure to establish your workspace and gather all prerequisites as outlined here.

"},{"location":"pyalgotrad/introduction/#support-seeking-assistance","title":"Support / Seeking Assistance","text":""},{"location":"pyalgotrad/introduction/#overview","title":"Overview","text":"
  1. Check out the basic structure of a strategy: Before coding your strategy, refer to the basic structure guide provided by the Pyalgotrading package. This will help you understand the trading strategy methods and flow.

  2. Code your own simple strategy using the pyalgotrading package: Use your Python IDE to code your trading strategy using the pyalgotrading package. You can also use ready-made strategies from the pyalgostrategypool package if you prefer not to code your own.

  3. Upload your strategy to the platform: Upon coding your strategy, upload it to the AlgoBulls platform by crafting a new strategy and uploading the corresponding file.

  4. Run Backtest / Paper Trade / Real Trade with your strategy: Once uploaded, initiate backtests, paper trades, or real trades on the AlgoBulls platform to evaluate its performance.

  5. Retrieve real-time logs, review reports and stats, and inspect order history:Monitor your strategy's performance by fetching runtime logs, examining reports and statistics, and reviewing your order history to track executed trades.

  6. Reach out to AlgoBulls Support for any queries: If you encounter issues during the tutorial, contact the AlgoBulls Support team for assistance.

"},{"location":"pyalgotrad/introduction/#conclusion","title":"Conclusion","text":"

This documentation serves as your launchpad into the Pyalgotrading package and the creation of your trading strategies. It also steers you through the process of uploading, executing, and monitoring strategies on the AlgoBulls platform. Our goal is to equip you with the expertise needed to craft effective trading strategies using Pyalgotrading.

"},{"location":"pyalgotrad/introduction/#contribution-guidelines","title":"Contribution Guidelines","text":"
  1. Fork this project to your account.
  2. Create a branch for the change you intend to make.
  3. Make your changes to your fork.
  4. Send a pull request from your fork\u2019s branch to our master branch.
"},{"location":"pyalgotrad/prerequisites/","title":"Setup your Workspace","text":""},{"location":"pyalgotrad/prerequisites/#prerequisites","title":"Prerequisites","text":"

You will need the following to start with Pyalgotrading:

"},{"location":"pyalgotrad/prerequisites/#algobulls-account","title":"AlgoBulls Account","text":"

To upload and test your strategies, you will need this account. You can create your account for FREE on the Algobulls website.

"},{"location":"pyalgotrad/prerequisites/#developer-key","title":"Developer Key","text":"

To access the features, you will need a developer key. The key can be obtained as follows:

Please Note

For security reasons, the developer key will get reset every time you log out from your AlgoBulls account.

Once you have the developer key, you can access the AlgoBulls platform using pyalgotrading functions.

"},{"location":"pyalgotrad/prerequisites/#python-310","title":"Python 3.10+","text":"

The Pyalgotrading platform can run all strategies that conform to Python 3.8 or higher. However, we recommend Python 3.10 or higher.

Python Tips

"},{"location":"pyalgotrad/prerequisites/#pyalgotrading-package","title":"Pyalgotrading Package","text":"

To create and execute your fully automated trading strategies, you only need to install pyalgotrading. You can install the pyalgotrading package using the following command:

pip install pyalgotrading\n

"},{"location":"pyalgotrad/prerequisites/#jupyter-notebook","title":"Jupyter Notebook","text":"

You will use a Jupyter Notebook to connect to the AlgoBulls platform. Using the notebook, you can upload the strategy, test your strategy (Backtesting, Paper Trading, or Real Trading), and fetch logs. Install Jupyter Notebook using the following command:

pip install jupyter\n

Pro Tip

If you are an experienced Pyalgotrading user, Jupyter Notebook might not be necessary. You can directly integrate it into your application.

"},{"location":"pyalgotrad/prerequisites/#enhancing-productivity","title":"Enhancing Productivity","text":"

For enhancing your productivity while building and executing strategies using Pyalgotrading, you can make use of Python IDEs of your choice, such as:

"},{"location":"pyalgotrad/programexample/","title":"Create your Strategy","text":""},{"location":"pyalgotrad/programexample/#previously","title":"Previously...","text":"

You have covered the basic code structure of a strategy.

"},{"location":"pyalgotrad/programexample/#now","title":"Now...","text":"

You can either follow this page to create a strategy, or you can pick up a ready strategy (shown below) and move to the next page.

"},{"location":"pyalgotrad/programexample/#before-you-start","title":"Before you start...","text":"

If you want to use a ready strategy from the pyalgostrategypool package, then you can directly jump to the Upload section.

"},{"location":"pyalgotrad/programexample/#lets-start","title":"Let's Start...","text":"

Follow the steps given below to create a new strategy of your own.

Create a python file called strategy_sma_regular_order.py.

You will add the following code snippets into the file and then save it.

"},{"location":"pyalgotrad/programexample/#import-statements","title":"Import statements","text":"
from pyalgotrading.strategy.strategy_base import StrategyBase\nfrom pyalgotrading.constants import *\n
"},{"location":"pyalgotrad/programexample/#create-the-class-strategysmaregularorder-and-subclass-it-from-strategybase","title":"Create the class StrategySMARegularOrder and subclass it from StrategyBase","text":"

class StrategySMARegularOrder(StrategyBase):\n
Now you can add the methods mentioned in the structure inside the class. First you can add the __init__ and the initialize methods.

"},{"location":"pyalgotrad/programexample/#constructor-def-__init__","title":"Constructor: def __init__()","text":"
def __init__(self, *args, **kwargs):\n    name = 'SMA Regular Order Strategy'\n    super().__init__(*args, **kwargs)\n\n    self.timeperiod_x = self.strategy_parameters['timeperiod1']\n    self.timeperiod_y = self.strategy_parameters['timeperiod2']\n\n    self.main_order = None\n

The init method does the following:

  1. name - variable which should store the name of your strategy
  2. super() - Calls the constructor of the superclass.
  3. self.strategy_parameters - Catches the parameters and saves them for local use - When you will submit a testing job for your SMA strategy, you will pass parameters that will be used inside the strategy. For SMA, we are calculating crossover for 2 SMA timeperiod values, example 5 and 12. These 2 parameters will be caught by self.strategy_parameters and stored for local use in self.timeperiod1 and self.timeperiod2.
  4. self.main_order - Create an object that manages orders for you throughout the strategy.

The init method is specific to Python's internal workings, and it is preceded and succeeded by double underscores ( _ _ ) joined together.

"},{"location":"pyalgotrad/programexample/#def-initialize","title":"def initialize()","text":"
def initialize(self):\n    self.main_order = {}\n

The initialize method sets the self.main_order as an empty dictionary. This method is called at the start of every trading day.

For instance, say you are submitting a backtesting job for 5 previous days starting at 10:30 every day, then the initialize method will be called every day for 5 days at 10:30.

Now add the two static methods, name and versions_supprted.

"},{"location":"pyalgotrad/programexample/#def-name-optional","title":"def name() (optional)","text":"

If the name variable is defined in __init__(), this function is not needed.

@staticmethod\ndef name():\n    return 'SMA Regular Order Strategy'\n
The name should be unique in your collection of strategies.

"},{"location":"pyalgotrad/programexample/#def-versions_supported-optional","title":"def versions_supported() (optional)","text":"

not required it will take the latest version of AlgoBullsEngine by default

@staticmethod\ndef versions_supported():\n    return AlgoBullsEngineVersion.VERSION_3_2_0\n
Mark both the above methods as @staticmethod.

The versions_supported method does the following:

  1. It notifies the AlgoBulls platform that the strategy is working correctly for the platform version 3.2.0
  2. Since the platform will be constantly upgraded to incorporate new features and improve efficiency, the version may change.
  3. If the version changes, and if you submit a job for this strategy, then the AlgoBulls platform will spawn a server having version 3.2.0 for your strategy.
  4. Having this method ensures that the AlgoBulls platform always provides the correct environment for your strategy.
"},{"location":"pyalgotrad/programexample/#def-strategy_select_instruments_for_entry","title":"def strategy_select_instruments_for_entry()","text":"
def strategy_select_instruments_for_entry(self, candle, instruments_bucket):\n\n    instruments = []\n    meta = []\n\n    for instrument in instruments_bucket:\n        crossover_value = self.get_crossover_value(instrument)\n        if crossover_value == 1:\n            instruments.append(instrument)\n            meta.append({'action': 'BUY'})\n        elif crossover_value == -1:\n            if self.strategy_mode is StrategyMode.INTRADAY:\n                instruments.append(instrument)\n                meta.append({'action': 'SELL'})\n\n    return instruments, meta\n

The strategy_select_instruments_for_entry method does the following:

  1. instruments and meta - Creates 2 empty lists that will be used to pass the selected instruments and additional information about them respectively.
  2. The Loop - The loop will iterate over each instrument name passed (while submitting the job) and will decide whether to set an entry position or not for it.
  3. crossover_value - The crossover value is calculated and stored here. Crossover values are interpreted as:
    1. Value 1 - Cut upwards
    2. Value -1 - Cut downwards
    3. Value 0 - No crossover
  4. If conditions - If the crossover value is 1, then the instrument is selected for entry position, with the position as 'BUY'. If the crossover value is -1, then the instrument is selected for entry position, with the position as 'SELL'. The selected instrument is appended to the instruments, and the associated action (BUY/SELL) is appended to the meta.
  5. instruments and meta - Both the lists (whether populated or empty) are returned to the platform for further actions.

Note

"},{"location":"pyalgotrad/programexample/#def-strategy_enter_position","title":"def strategy_enter_position()","text":"
def strategy_enter_position(self, candle, instrument, sideband_info):\n    if sideband_info['action'] == 'BUY':\n        qty = self.number_of_lots * instrument.lot_size\n        self.main_order[instrument] = \\\n            self.broker.BuyOrderRegular(instrument=instrument,\n                order_code=BrokerOrderCodeConstants.INTRADAY,\n                order_variety=BrokerOrderVarietyConstants.MARKET,\n                quantity=qty)\n    elif sideband_info['action'] == 'SELL':\n        qty = self.number_of_lots * instrument.lot_size\n        self.main_order[instrument] = \\\n            self.broker.SellOrderRegular(instrument=instrument,\n                 order_code=BrokerOrderCodeConstants.INTRADAY,\n                 order_variety=BrokerOrderVarietyConstants.MARKET,\n                 quantity=qty)\n    else:\n        raise SystemExit(f'Got invalid sideband_info value: {sideband_info}')\n\n    return self.main_order[instrument]\n
"},{"location":"pyalgotrad/programexample/#or","title":"or","text":"
def strategy_enter_position(self, candle, instrument, meta):\n    self.main_order_map[instrument] = _ = self.broker.OrderRegular(\n        intrument=instrument,                           \n        order_transaction_type=meta['action'],              # 'BUY' or 'SELL'\n        quantity=self.number_of_lots * instrument.lot_size, # number of lots (int)\n        price=None,\n        trigger_price=None\n    )\n    return _\n

The strategy_enter_position method does the following:

  1. If conditions - The conditions read the action from the sideband_info and perform the required action (BUY/SELL).
  2. qty - The quantity is calculated and stored here. The number of lots will be passed by you as a parameter while submitting a job. The parameter will be caught in self.number_of_lots. The instrument object has the 'lot size', which you can retrieve using instrument.lot_size. You can then use the formula as shown in the code to calculate the quantity.
  3. OrderRegular,BuyOrderRegular and SellOrderRegular - These execute the required action. You need to pass the instrument, order code, order variety and the quantity values.
    • instrument - the instrument on which the BUY/SELL action will be performed.
    • order_code - whether the order is for INTRADAY or DELIVERY. Possible values are:
      • BrokerOrderCodeConstants.INTRADAY
      • BrokerOrderCodeConstants.DELIVERY
      • BrokerOrderCodeConstants.DELIVERY_T1
      • BrokerOrderCodeConstants.DELIVERY_T2
    • order_variety - the type of order variety. Possible values are:
      • BrokerOrderVarietyConstants.MARKET
      • BrokerOrderVarietyConstants.LIMIT
      • BrokerOrderVarietyConstants.STOPLOSS_MARKET
      • BrokerOrderVarietyConstants.STOPLOSS_LIMIT
    • qty - the quantity to BUY/SELL.
  4. self.main_order - The main order (for that particular instrument) is now populated (BUY OR SELL) and is returned to the platform for further actions.

You can also punch Bracket Orders instead of Regular Orders. A typical BUY Bracket Order will look like this:

qty = self.number_of_lots * instrument.lot_size\nltp = self.broker.get_ltp(instrument)\nself.main_order[instrument] = \\\n            self.broker.BuyOrderBracket(instrument=instrument,\n                order_code=BrokerOrderCodeConstants.INTRADAY,\n                order_variety=BrokerOrderVarietyConstants.LIMIT,\n                quantity=qty,\n                price=ltp,\n                stoploss_trigger=ltp - (ltp * self.stoploss),\n                target_trigger=ltp + (ltp * self.target),\n                trailing_stoploss_trigger=ltp * self.trailing_stoploss)\n

The additional parameters are:

Note

"},{"location":"pyalgotrad/programexample/#def-strategy_select_instruments_for_exit","title":"def strategy_select_instruments_for_exit()","text":"
def strategy_select_instruments_for_exit(self, candle, instruments_bucket):\n    instruments = []\n    meta = []\n\n    for instrument in instruments_bucket:\n        if self.main_order.get(instrument) is not None:\n            crossover_value = self.get_crossover_value(instrument)\n            if crossover_value in [1, -1]:\n                instruments.append(instrument)\n                meta.append({'action': 'EXIT'})\n    return instruments, meta\n

The strategy_select_instruments_for_exit method does the following:

  1. instruments and meta - Creates 2 empty lists that will be used to pass the selected instruments and additional information about them respectively.
  2. The Loop - The loop will iterate over each instrument name passed (which are in Entry position (BUY/SELL)) and will decide whether to set an exit position or not for it.
  3. If condition - The exit steps are executed only if the instrument is holding at an ENTRY position (BUY/SELL). You can do this by checking if the self.main_order object is None or not, and proceed only if it is not None.
  4. crossover_value - The crossover value is calculated and stored here. Crossover values are interpreted as:
    1. Value 1 - Cut upwards
    2. Value -1 - Cut downwards
    3. Value 0 - No crossover
  5. If condition - If the crossover value is 1 or -1, then the instrument is selected for exit position. The selected instrument is appended to the instruments, and the associated action (EXIT) is appended to the meta.
  6. instruments and meta - Both the lists (whether populated or empty) are returned to the platform for further actions.

Note

"},{"location":"pyalgotrad/programexample/#def-strategy_exit_position","title":"def strategy_exit_position()","text":"
def strategy_exit_position(self, candle, instrument, sideband_info):\n    if sideband_info['action'] == 'EXIT':\n        self.main_order[instrument].exit_position()\n        self.main_order[instrument] = None\n        return True\n\n    return False\n

The strategy_exit_position method does the following:

  1. If condition - checks whether the appropriate action is set in the sideband_info.
  2. self.main_order - calls exit_position method for the particular main order of the instrument. If the Entry Position was BUY, then the exit position is automatically taken as SELL and vice versa. The platform takes care of this automatically.
  3. self.main_order - set it to None, as the order has been exited and no longer holds anything.
  4. Return values - returns True to the platform if the exit steps were performed, else return False.
"},{"location":"pyalgotrad/programexample/#def-get_crossover_value","title":"def get_crossover_value()","text":"
def get_crossover_value(self, instrument):\n    hist_data = self.get_historical_data(instrument)\n    sma_x = talib.SMA(hist_data['close'], timeperiod=self.timeperiod_x)\n    sma_y = talib.SMA(hist_data['close'], timeperiod=self.timeperiod_y)\n    crossover_value = self.utils.crossover(sma_x, sma_y)\n    return crossover_value\n

The get_crossover_value method does the following:

  1. hist_data - The historical data for the instrument is fetched using the get_historical_data method and stored here. The data is in the form of a table (Pandas DataFrame) having the following columns:
    • timestamp - the data and time when the data was measured
    • volume - the volume of that instrument
    • open, high, low and close - the OHLC values of the instrument
    • oi - the Open Interest of that instrument
  2. sma_x and sma_y - the SMA function from the talib package is used to calculate the Moving Average for both SMA time-periods. The candle close value is used for calculations, i.e. hist_data['close'].
  3. crossover_value - calculates the crossover value using the crossover method from the utils package.
  4. Return value - return the crossover value to the caller method.

Note

"},{"location":"pyalgotrad/programexample/#whats-next","title":"What's Next...","text":"

Next, you upload the strategy into your AlgoBulls account.

"},{"location":"pyalgotrad/pyalgotrading_analytics/","title":"Pyalgotrading Analytics","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#metric-values-and-statistics","title":"Metric Values and Statistics","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#cumulative-returns","title":"Cumulative Returns","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#end-of-year-returns-eoy","title":"End of Year Returns (EoY)","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#distributions-of-monthly-returns-histogram","title":"Distributions of Monthly Returns (Histogram)","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#daily-returns","title":"Daily Returns","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#rolling-volatility-6-months","title":"Rolling Volatility (6 months)","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#rolling-sharpe-6-months","title":"Rolling Sharpe (6 months)","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#rolling-sortino-6-months","title":"Rolling Sortino (6 months)","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#worst-5-drawdown-periods","title":"Worst 5 Drawdown Periods","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#underwater-plot","title":"Underwater Plot","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#monthly-returns-heatmap","title":"Monthly Returns (Heatmap)","text":""},{"location":"pyalgotrad/python-build-view-results/","title":"Python build view results","text":""},{"location":"pyalgotrad/python-build-view-results/#how-to-view-the-results","title":"How to view the Results?","text":"

Once you start the strategy, it may take a while for it to complete the execution. You can switch to the Analytics tab after you run your strategy. Even if the strategy execution is not complete, you will still see intermediate results.

Analytics: In the analytics section, you can view a strategy\u2019s Stats & various other metrics in the form of graphs like P&L.

"},{"location":"pyalgotrad/python-build-view-results/#stats","title":"Stats","text":"

In this section you can see the total returns, sharpe ratio, sortino ratio, volatility, Max Drawdown, Total wins or Loses, Total short or long trades, hit ratio, number of trades, average trades per day, max profit, max loss, average profit per winning trade, average loss per losing trade.

"},{"location":"pyalgotrad/python-build-view-results/#cumulative-returns","title":"Cumulative Returns","text":""},{"location":"pyalgotrad/python-build-view-results/#profit-loss-currency-or","title":"Profit & Loss (Currency or %)","text":"

The trade by trade P&L in Currency or Percentage.

"},{"location":"pyalgotrad/python-build-view-results/#end-of-year-returns-plot","title":"End of Year Returns Plot (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#monthly-returns-histogram","title":"Monthly Returns Histogram (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#monthly-returns-heatmap","title":"Monthly Returns Heatmap (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#daily-returns","title":"Daily Returns (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#underwater-drawdown-plot","title":"Underwater Drawdown Plot (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#pl-book","title":"P&L Book","text":"

View detailed trade by trade report. Premium users can analyze this data in the form of heatmaps for Gross Profit & Loss, Trading Volume & Total number of Trades.

"},{"location":"pyalgotrad/python-build-view-results/#user-log","title":"User Log","text":"

Real-time logs from strategy execution are displayed in this section. Use these logs to debug your strategy\u2019s behavior and performance.

"},{"location":"pyalgotrad/python-build-view-results/#order-history","title":"Order History","text":"

View the order state transition for every order placed by your strategy in-depth.

"},{"location":"pyalgotrad/select/","title":"Select your Strategy","text":""},{"location":"pyalgotrad/select/#previously","title":"Previously...","text":"

You have uploaded or saved a strategy by:

OR

"},{"location":"pyalgotrad/select/#now","title":"Now...","text":"

You are now ready to select or import your strategy from your AlgoBulls account for Backtesting, Paper Trading and/or Real Trading.

"},{"location":"pyalgotrad/select/#before-you-start","title":"Before you start...","text":""},{"location":"pyalgotrad/select/#lets-start","title":"Let's Start...","text":"

Run the following code snippets into the Jupyter Notebook one by one (or all together).

"},{"location":"pyalgotrad/select/#import-statements","title":"Import statements","text":"
import inspect\nfrom pyalgotrading.algobulls import AlgoBullsConnection\n
"},{"location":"pyalgotrad/select/#import-the-strategy-class","title":"Import the strategy class","text":"

Perform the below step either to import a ready strategy OR to import your own created strategy.

"},{"location":"pyalgotrad/select/#establish-a-connection-to-the-algobulls-platform","title":"Establish a connection to the AlgoBulls Platform","text":"

algobulls_connection = AlgoBullsConnection()\nalgobulls_connection.get_authorization_url()\n
The output of the above step is:

Please login to this URL with your AlgoBulls credentials and get your developer access token: https://app.algobulls.com/user/login

Get Developer Key

You will need to log in to your AlgoBulls account and fetch the access token from: (See How) Settings -> General -> Developer Options

Once you have the access token, set it in the code as shown here:

algobulls_connection.set_access_token('4365817b795770ea31040a21ad29c8e78b63ad88')\n
Replace the token you have copied with the token in the code above.

"},{"location":"pyalgotrad/select/#view-all-the-strategies-in-your-algobulls-account","title":"View all the strategies in your AlgoBulls Account","text":"

You can view all the strategy saved on your AlgoBulls account.

all_strategies_df = algobulls_connection.get_all_strategies()\nprint(all_strategies_df)\n

"},{"location":"pyalgotrad/select/#search-your-strategy","title":"Search your Strategy","text":""},{"location":"pyalgotrad/select/#whats-next","title":"What's Next...","text":"

You are now ready to test your uploaded strategy and perform Backtesting, Paper Trading and/or Real Trading with it.

"},{"location":"pyalgotrad/slippage/","title":"Slippage","text":""},{"location":"pyalgotrad/slippage/#slippage-and-brokerage-parameters","title":"Slippage and Brokerage Parameters","text":"

In the algobulls_connection.get_backtesting_report_pnl_table function, you have the option to specify slippage and brokerage parameters to account for transaction costs and execution variations. These parameters allow you to fine-tune your backtesting results to better simulate real-world trading conditions.

"},{"location":"pyalgotrad/slippage/#slippage","title":"Slippage","text":""},{"location":"pyalgotrad/slippage/#how-to-use","title":"How to Use","text":"

To incorporate slippage into your backtesting, simply pass the desired values for slippage_percent, when calling the algobulls_connection.get_backtesting_report_pnl_table function. These parameters help you account for real-world trading costs and execution variations, making your backtesting results more realistic.

"},{"location":"pyalgotrad/slippage/#example","title":"Example","text":"
import algobulls_connection\n# Fetch PnL data for a trading strategy with custom slippage  settings\npnl_table = algobulls_connection.get_backtesting_report_pnl_table(\n    strategy_code=\"your_strategy_code\",\n    show_all_rows=True,\n    force_fetch=True,\n    country='USA',\n    slippage_percent=4.5,             # Adjust slippage percentage as needed\n)\n# Print the PnL table with custom slippage  settings\nprint(pnl_table)\n
"},{"location":"pyalgotrad/testing/","title":"Execute your Strategy","text":""},{"location":"pyalgotrad/testing/#previously","title":"Previously...","text":"

You have uploaded your strategy to the AlgoBulls platform.

"},{"location":"pyalgotrad/testing/#now","title":"Now...","text":"

Using the uploaded strategy, you can now try:

"},{"location":"pyalgotrad/testing/#before-you-start","title":"Before you start...","text":"

Open a Jupyter Notebook.

The steps you will follow are:

  1. Establish a connection to the AlgoBulls Platform.
  2. Display all Strategies you have in your account.
  3. Select the strategy.
  4. Optionally, print the strategy once.
  5. Select instrument(s).
  6. Submit/Run a Backtest, Paper Trade or Real Trade job.
  7. Check Job Status.
  8. Fetch Logs (even while the job is running).
  9. Fetch Reports. (PnL, Statistics, Order History)
"},{"location":"pyalgotrad/testing/#lets-start","title":"Let's Start...","text":"

Run the following code snippets into the Jupyter Notebook one by one (or all together).

"},{"location":"pyalgotrad/testing/#create-a-new-strategy-file","title":"Create a new strategy file","text":"

eg: strategy_<unique_code_if_needed>_options_ema_crossover.py Make sure this strategy file is in the same folder as the jupyter notebook.

Coding Conventions

How to Code ?

To know more on how to code trading strategies and understand their format, click here. We have in detail explanation for regular strategies as well as options strategies

"},{"location":"pyalgotrad/testing/#import-statements","title":"Import statements","text":"
from pyalgotrading.algobulls import AlgoBullsConnection\nfrom datetime import datetime as dt\nfrom pyalgotrading.constants import *\n
"},{"location":"pyalgotrad/testing/#establish-a-connection-to-the-algobulls-platform","title":"Establish a connection to the AlgoBulls Platform","text":"

algobulls_connection = AlgoBullsConnection()\nalgobulls_connection.get_authorization_url()\n
The output of the above step is:

Please login to this URL with your AlgoBulls credentials and get your developer access token: https://app.algobulls.com/user/login

Get Developer Key

You will need to log in to your AlgoBulls account and fetch the access token from: (See How) Settings -> General -> Developer Options

Once you have the access token, set it in the code as shown here:

algobulls_connection.set_access_token('4365817b795770ea31040a21ad29c8e78b63ad88')\n

Replace the token you have copied with the token in the code above.

"},{"location":"pyalgotrad/testing/#display-all-strategies-in-your-account","title":"Display all strategies in your account","text":"
all_strategies = algobulls_connection.get_all_strategies()\nall_strategies\n

An example of the output will be:

"},{"location":"pyalgotrad/testing/#select-the-strategy","title":"Select the strategy","text":"

Select the last entry of the strategyCode column and display it.

strategy_code = all_strategies.iloc[-1]['strategyCode']\nstrategy_code\n

"},{"location":"pyalgotrad/testing/#print-your-strategy-code","title":"Print your Strategy code","text":"

You can print your strategy code once to verify if this is the correct code. This step is optional.

strategy_details1 = algobulls_connection.get_strategy_details(strategy_code)\nprint(strategy_details1)\n
"},{"location":"pyalgotrad/testing/#search-for-instruments-based-on-a-search-query","title":"Search for instruments (based on a search query)","text":"

Now display a few instruments with some keyword. The example below uses 'SBIN' as the keyword.

instruments = algobulls_connection.search_instrument('SBIN')\ninstruments\n
"},{"location":"pyalgotrad/testing/#select-an-instrument","title":"Select an instrument","text":"

From the output, select the instrument on which you wish to test your strategy. For this example, select the first one.

instrument = instruments[0]['value']\ninstrument\n

"},{"location":"pyalgotrad/testing/#submit-a-job","title":"Submit a Job","text":"

Delete previous trades

algobulls_connection.delete_previous_trades(strategy=strategy)\n

Set the parameters for the strategy

parameters={\n    'timeperiod1': 5,\n    'timeperiod2': 12\n}\n

vendor_details = {\n    'brokerName': '<VENDOR_NAME>',\n    'credentialParameters': {\n        'api_key': '<API_KEY>',\n        'secret_key': '<SECRET_KEY>'\n    }\n}\n
broking_details = {\n    'brokerName': '<BROKER_NAME>',\n    'credentialParameters': {\n        'user_id': '<USER_ID>',\n        'api_key': '<API_KEY>',\n        'password': '<PASSWORD>'\n    }\n}\n

Click on each of the tabs to see the relevant code snippet.

BacktestingPaper TradingReal Trading
algobulls_connection.backtest(\n        strategy=strategy_code,         # strategy code\n        start='2020-7-1 09:15 +0530',   # start date-time of strategy ('YYYY-MM-DD HH:MM z')\n        end='2020-7-7 15:30 +0530',     # end date-time of strategy ('YYYY-MM-DD HH:MM z')\n        instruments='NSE:SBIN',         # name of the instrument\n        lots=1,                         # number of lots per trade\n        parameters=parameters,          # parameters required for the strategy\n        candle='15 minutes',            # candle size eg : '1 Day', '1 hour', '3 minutes'\n        delete_previous_trades=True,    # delete the previous trades for papertrading (default is true),\n        initial_funds_virtual=10000,    # virtual funds allotted before the paper trading starts (default is 1e9)\n        vendor_details=vendor_details   # vendor's details for authentication and verification \n)\n
algobulls_connection.papertrade(\n        strategy=strategy_code,         # strategy code\n        start='09:15 +0530',            # start time of strategy (HH:MM z)     \n        end='15:30 +0530',              # end time of strategy (HH:MM z)\n        instruments='NSE:SBIN',         # name of the instrument\n        lots=1,                         # number of lots per trade\n        parameters=parameters,          # parameters required for the strategy\n        candle='15 minutes',            # candle size eg : '1 Day', '1 hour', '3 minutes'\n        delete_previous_trades=True,    # delete the previous trades for papertrading (default is true)\n        initial_funds_virtual=10000,    # virtual funds allotted before the paper trading starts (default is 1e9)\n        vendor_details=vendor_details   # vendor's details for authentication and verification \n)\n
algobulls_connection.realtrade(\n        strategy=strategy_code,          # strategy code\n        start='09:15 +0530',             # start time of strategy (HH:MM z)     \n        end='15:30 +0530',               # end time of strategy (HH:MM z)\n        instruments='NSE:SBIN',          # name of the instrument\n        lots=1,                          # number of lots per trade\n        parameters=parameters,           # parameters required for the strategy\n        candle='15 minutes',             # candle size eg : '1 Day', '1 hour', '3 minutes'\n        broking_details=broking_details  # broker's details for authentication and verification \n)\n
"},{"location":"pyalgotrad/testing/#fetch-job-status","title":"Fetch Job Status","text":"

Click on each of the tabs to see the relevant code snippet. There are 4 stages of your strategy execution : STARTING, STARTED, STOPPING and STOPPED

BacktestingPaper TradingReal Trading
algobulls_connection.get_backtesting_job_status(strategy_code)\n
algobulls_connection.get_papertrading_job_status(strategy_code)\n
algobulls_connection.get_realtrading_job_status(strategy_code)\n

You can stop a submitted job anytime.

"},{"location":"pyalgotrad/testing/#stop-a-job","title":"Stop a Job","text":"

Click on each of the tabs to see the relevant code snippet.

BacktestingPaper TradingReal Trading
algobulls_connection.stop_backtesting_job(strategy_code)\n
algobulls_connection.stop_papertrading_job(strategy_code)\n
algobulls_connection.stop_realtrading_job(strategy_code)\n

You can fetch the logs in the middle of a job to monitor the progress.

"},{"location":"pyalgotrad/testing/#fetch-logs","title":"Fetch logs","text":"

Logging Tip

Click on each of the tabs to see the relevant code snippet.

BacktestingPaper TradingReal Trading
logs = algobulls_connection.get_backtesting_logs(\n            strategy_code,                              # strategy code \n            display_progress_bar=True,                  # (default=True) to track the execution on progress bar as your strategy is executed\n            print_live_logs: True                       # (default=False) to print the live logs as your strategy is executed\n        )\nprint(logs)\n
logs = algobulls_connection.get_papertrading_logs(\n            strategy_code,                              # strategy code \n            display_progress_bar=True,                  # (default=True) to track the execution on progress bar as your strategy is executed\n            print_live_logs: True                       # (default=True) to print the live logs as your strategy is executed\n        )\nprint(logs)\n
logs = algobulls_connection.get_realtrading_logs(\n            strategy_code,                              # strategy code \n            display_progress_bar=True,                  # (default=True) to track the execution on progress bar as your strategy is executed\n            print_live_logs: True                       # (default=True) to print the live logs as your strategy is executed\n        )\nprint(logs)\n

You can fetch the PnL report, statistics and order history for a job.

"},{"location":"pyalgotrad/testing/#fetch-pnl-reports","title":"Fetch PnL Reports","text":"

Click on each of the tabs to see the relevant code snippet.

Please Note

Make sure that strategy's execution status is at STOPPED stage before generating PnL reports

BacktestingPaper TradingReal Trading
algobulls_connection.get_backtesting_report_pnl_table(\n        strategy_code,                      # strategy code\n        show_all_rows=True,                 # default=True         \n        force_fetch=True,                   # pnl data is saved locally once fetched, to update the locally fetched data, make this parameter True\n        country='USA',                      # country of the exchange that was used while starting the job ('India' or 'USA')\n        broker_commission_percentage: 1     # Percentage of broker commission per trade\n        broker_commission_price: 0.2        # Broker fee per trade\n        slippage_percent: 3                 # Slippage percentage value\n)\n
algobulls_connection.get_papertrading_report_pnl_table(\n        strategy_code,                      # strategy code\n        show_all_rows=True,                 # default=True         \n        force_fetch=True,                   # pnl data is saved locally once fetched, to update the locally fetched data, make this parameter True\n        country='USA',                      # country of the exchange that was used while starting the job ('India' or 'USA')\n        broker_commission_percentage: 1     # Percentage of broker commission per trade\n        broker_commission_price: 0.2        # Broker fee per trade\n        slippage_percent: 3                 # Slippage percentage value\n)\n
algobulls_connection.get_realtrading_report_pnl_table(\n        strategy_code,              # strategy code\n        show_all_rows=True,         # default=True         \n        force_fetch=True,           # pnl data is saved locally once fetched, to update the locally fetched data, make this parameter True\n        country='USA',              # country of the exchange that was used while starting the job ('India' or 'USA')\n)\n

To know more about slippage and brokerage parameters click here

"},{"location":"pyalgotrad/testing/#fetch-report-statistics","title":"Fetch Report Statistics","text":"

Click on each of the tabs to see the relevant code snippet.

Analytics Tips

You can view your analytics on the python build page as well, simply log inside your AlgoBulls Account, and look for your Strategy in Python Build -> My Coded Strategies

BacktestingPaper TradingReal Trading
algobulls_connection.get_backtesting_report_statistics(\n    strategy_code,          # strategy code\n    report='full',          # format of the report\n    html_dump=True          # save report as html file\n)\n
algobulls_connection.get_papertrading_report_statistics(\n    strategy_code,          # strategy code\n    report='full',          # format of the report\n    html_dump=True          # save report as html file\n)\n
algobulls_connection.get_realtrading_report_statistics(\n    strategy_code,          # strategy code\n    report='full',          # format of the report\n    html_dump=True          # save report as html file\n)\n
"},{"location":"pyalgotrad/testing/#generate-statistics-from-external-csv","title":"Generate Statistics from External CSV","text":"

Make sure your csv has the columns names as \"net_pnl\" and \"entry_timestamp\". The \"net_pnl\" column will contain the net profit and loss of every trade and its respective entry time will be stored in \"entry_timestamp\".

connection.get_report_statistics(file_path=\"testing_file.csv\", initial_funds=3000)\n

"},{"location":"pyalgotrad/testing/#fetch-order-history","title":"Fetch Order History","text":"

Click on each of the tabs to see the relevant code snippet.

BacktestingPaper TradingReal Trading
order_history = algobulls_connection.get_backtesting_report_order_history(strategy_code)\nprint(order_history)\n
order_history = algobulls_connection.get_papertrading_report_order_history(strategy_code)\nprint(order_history)\n
order_history = algobulls_connection.get_realtrading_report_order_history(strategy_code)\nprint(order_history)\n

Note

"},{"location":"pyalgotrad/testing/#whats-next","title":"What's Next...","text":"

You can now explore more by creating and uploading more complex strategies.

You can also check out the Analytics, to understand more about the returns and analyze your strategy based on the analytics report.

"},{"location":"pyalgotrad/upload/","title":"Upload your Strategy","text":""},{"location":"pyalgotrad/upload/#previously","title":"Previously...","text":"

You have created a strategy by:

OR

"},{"location":"pyalgotrad/upload/#now","title":"Now...","text":"

You are now ready to upload your strategy into your AlgoBulls account for Backtesting, Paper Trading and/or Real Trading.

"},{"location":"pyalgotrad/upload/#before-you-start","title":"Before you start...","text":""},{"location":"pyalgotrad/upload/#lets-start","title":"Let's Start...","text":"

Run the following code snippets into the Jupyter Notebook one by one (or all together).

"},{"location":"pyalgotrad/upload/#import-statements","title":"Import statements","text":"
import inspect\nfrom pyalgotrading.algobulls import AlgoBullsConnection\n
"},{"location":"pyalgotrad/upload/#establish-a-connection-to-the-algobulls-platform","title":"Establish a connection to the AlgoBulls Platform","text":"

algobulls_connection = AlgoBullsConnection()\nalgobulls_connection.get_authorization_url()\n
The output of the above step is:

Please login to this URL with your AlgoBulls credentials and get your developer access token: https://app.algobulls.com/user/login

Get Developer Key

You will need to log in to your AlgoBulls account and fetch the access token from: (See How) Settings -> General -> Developer Options

Once you have the access token, set it in the code as shown here:

algobulls_connection.set_access_token('4365817b795770ea31040a21ad29c8e78b63ad88')\n
Replace the token you have copied with the token in the code above.

"},{"location":"pyalgotrad/upload/#print-your-strategy-code","title":"Print your Strategy code","text":"

You can print your strategy code once to verify if this is the correct code before uploading it to the platform. This step is optional.

print(inspect.getsource(StrategySMARegularOrder))\n

"},{"location":"pyalgotrad/upload/#upload-your-strategy_1","title":"Upload your Strategy","text":"

Upload your strategy as shown in the code below.

algobulls_connection.create_strategy(StrategySMARegularOrder)\n

"},{"location":"pyalgotrad/upload/#re-upload-your-strategy-after-modifications","title":"Re-upload your Strategy after modifications","text":"

If you are re-uploading your strategy after some changes, then use the overwrite switch as shown here.

algobulls_connection.create_strategy(StrategySMARegularOrder, overwrite=True)\n

"},{"location":"pyalgotrad/upload/#whats-next","title":"What's Next...","text":"

You are now ready to test your uploaded strategy and perform Backtesting, Paper Trading and/or Real Trading with it.

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/","title":"Options Strategy Structure","text":"

Links

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#1-initial-steps","title":"1. Initial steps","text":""},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#naming-a-class","title":"Naming a Class","text":"eg: For the above strategy name the class name would be:
StrategyOptionsEMACrossover(StrategyOptionsBaseV2)\n

Coding Conventions

* Make a class with the same name as the file name\n* Make sure the first letter of each word is in uppercase and the initials should be in uppercase as well.\n* If the class name includes indicator names like EMA, SMA, and VWAP the name should be in uppercase in the class name but not in the file name.\n* Every options strategy is a child class of the StrategyOptionsBaseV2 class.\n
"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#naming-your-strategy","title":"Naming your Strategy","text":"

This name will be displayed in your My Coded Strategies in Python Build Web, and it will also be the strategy_name when you are fetching all strategies in pyalgotrading. Inside your strategy class, you can write your first parameter as name.

name = 'options_ema_crossover'\n

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#2-init-method","title":"2. Init method","text":"

This method gets called only once when the strategy is started.

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#strategy-info","title":"Strategy info","text":"

In the init method add the line given below

super().__init__(*args, **kwargs)\n

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#parameter-creation","title":"Parameter creation","text":"

Next, we assign the parameter values to the class variables of the same name as the parameters but in the lowercase format as shown below:

eg:

self.fresh_order_candle = self.strategy_parameters['FRESH_ORDER_CANDLE']\nself.start_time_hours = self.strategy_parameters['START_TIME_HOURS']\nself.start_time_minutes = self.strategy_parameters['START_TIME_MINUTES']\nself.end_time_hours = self.strategy_parameters['END_TIME_HOURS']\nself.end_time_minutes = self.strategy_parameters['END_TIME_MINUTES']\nself.no_of_strikes_away_ce = self.strategy_parameters['NO_OF_STRIKES_AWAY_CE']\nself.no_of_strikes_away_p = self.strategy_parameters['NO_OF_STRIKES_AWAY_PE']\nself._strike_direction_ce = self.strategy_parameters['STRIKES_DIRECTION_CE']\nself._strike_direction_pe = self.strategy_parameters['STRIKES_DIRECTION_PE']\nself.ema_period_one = self.strategy_parameters['EMA_PERIOD_ONE']\nself.ema_period_two = self.strategy_parameters['EMA_PERIOD_TWO']\nself.target_percentage = self.strategy_parameters['TARGET_PERCENTAGE']\nself.stoploss_percentage = self.strategy_parameters['STOPLOSS_PERCENTAGE']\nself.stoploss_range = self.strategy_parameters['STOPLOSS_RANGE']\nself.stoploss_order_count_allowed = self.strategy_parameters['STOPLOSS_ORDER_COUNT_ALLOWED']\n

Note

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#start-time-and-end-time-creation","title":"Start time and End time creation","text":"

Adding Start and End time is useful when you want to define a timerange between which the strategy will be running each day. Add the below code to calculate the strategy start time and end time, from the strategy_parameters.

try:

    self.candle_start_time = time(hour=self.start_time_hours, minute=self.start_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting start hours and minutes... EXITING')\n    raise SystemExit\n
try:
    self.candle_end_time = time(hour=self.end_time_hours, minute=self.end_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting end time hours and minutes... EXITING')\n    raise SystemExit\n

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#strategy-variables","title":"Strategy variables","text":"

We create our own strategy variables other than the strategy parameter variables which will be used throughout the strategy.

eg:

self.main_order = None            # We save the entry order in this variable\nself.stoploss_order = None        # We save the corresponding stoploss exit order of the entry order in this variable\n
We initialize the variables with a None value. !!! Note There could be more strategy variables required as per the strategy requirement.

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#3-initialize-method","title":"3. Initialize method","text":"

Unlike the init method, this method gets called every day at the beginning of the day once the strategy is started.

Here the strategy variables that were initialized as None are again defined as dictionaries/lists except for the self.order_tag_manager. Create a reference for OrderTagManager as shown below:

self.order_tag_manager = OrderTagManager\n
"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#4-ordertagmanager","title":"4. OrderTagManager","text":"

The self.order_tag_manager is used to store/remove the entry/exit orders. The self.order_tag_manager has the following methods:

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#add_order","title":"add_order","text":"
self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#get_orders","title":"get_orders","text":"

eg:

self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#remove_tags","title":"remove_tags","text":"

eg:

self.order_tag_manager.remove_tags(tags=entry_key)\n

Here the entry_key tag is removed from the OrderTagManager.

Note

When the tag is removed the order objects stored in that tag are also removed but the same order objects would still be present in order tags.

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#remove_order","title":"remove_order","text":"

eg:

self.order_tag_manager.remove_order(main_order)\n
Here the main_order order object is removed from the OrderTagManager.

Note

The order object will be removed from all the tags ta

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#get_internals","title":"get_internals","text":"
Returns the values i.e. both the entry and exit orders stored inside the tags list.\n
"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#5-child-instruments-calculation","title":"5. Child instruments calculation","text":""},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#get_ltp","title":"get_ltp","text":"

Fetch the ltp of the base instrument (instrument set while executing strategy)

ltp = self.broker.get_ltp(self.underlying_instrument)\n

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#options_instruments_set_up_local","title":"options_instruments_set_up_local","text":"

Get the ATM ITM and OTM lists of the child instrument based on the LTP

self.options_instruments_set_up_local(self.underlying_instrument, tradingsymbol_suffix, ltp)\n

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#get_child_instrument_details","title":"get_child_instrument_details","text":"

Select a child instrument from the lists of ATM, ITM, and OTM based on the strike direction and no of strikes given for the child instrument

child_instrument = self.get_child_instrument_details(self.underlying_instrument, tradingsymbol_suffix, strike_direction, no_of_strikes)\n

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#6-entry-methods","title":"6. Entry Methods","text":""},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry","text":""},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#strategy_enter_position","title":"strategy_enter_position","text":""},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#7-exit-methods","title":"7. Exit Methods","text":""},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit","text":""},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#strategy_exit_position","title":"strategy_exit_position","text":""},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#8-other-common-methods","title":"8. Other common methods","text":"

There are other methods that are used in the strategy:

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#check_and_place_stoploss_order","title":"check_and_place_stoploss_order","text":"

This method is called in the strategy_select_instruments_for_exit when our entry order is open, and we want to place a stoploss exit order for the same.

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#set_all_none","title":"set_all_none","text":"

This method is called in the strategy_exit_position when our entry order has exited, and we want to remove the order object from the self.main_order variable.

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#options_instruments_set_up_local_1","title":"options_instruments_set_up_local","text":"

This method is called in the strategy_select_instruments_for_entry to fetch the ATM, ITM, and OTM lists of the child instruments based on the LTP of the base instrument.

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#get_child_instrument_details_1","title":"get_child_instrument_details","text":"

This method is called in the strategy_select_instruments_for_entry to fetch a single child instrument based on the no of strikes and strike direction.

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#9-cleanup","title":"9. Cleanup","text":"
  1. Add comments and docstrings wherever possible to improve code readability.
  2. Once the strategy is completed you can optimize imports, give proper indentation and proper formatting to the strategy code and remove unwanted imports, variables, and methods before delivering the code.
"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#10-check-out-our-docs-for-developed-options-strategies","title":"10. Check out our docs for developed Options strategies","text":"

Tip

To know more about a strategy from our given template, simply check the first line of comment in the code of that specific strategy.

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/","title":"Regular Strategy Structure","text":"

Links

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#1-initial-steps","title":"1. Initial steps","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#naming-a-class","title":"Naming a Class","text":"eg: For the above strategy name the class name would be:
StrategyFuturesEMACrossover(StrategyBase)\n

Coding Conventions

* Make a class with the same name as the file name\n* Make sure the first letter of each word is in uppercase and the initials should be in uppercase as well.\n* If the class name includes indicator names like EMA, SMA, and VWAP the name should be in uppercase in the class name but not in the file name.\n* Every strategy is a child class of the StrategyBase class.\n
"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#naming-your-strategy","title":"Naming your Strategy","text":"

This name will be displayed in your My Coded Strategies in Python Build Web, and it will also be the strategy_name when you are fetching all strategies in pyalgotrading. Inside your strategy class, you can write your first parameter as name.

name = 'futures_ema_crossover'\n

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#2-init-method","title":"2. Init method","text":"

This method gets called only once when the strategy is started.

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#strategy-info","title":"Strategy info","text":"

In the init method add the line given below

super().__init__(*args, **kwargs)\n

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#parameter-creation","title":"Parameter creation","text":"

Next we assign the parameter values to the class variables of the same name as the parameters but in the lowercase format, as shown below:

eg:

self.fresh_order_candle = self.strategy_parameters['FRESH_ORDER_CANDLE']\nself.start_time_hours = self.strategy_parameters['START_TIME_HOURS']\nself.start_time_minutes = self.strategy_parameters['START_TIME_MINUTES']\nself.end_time_hours = self.strategy_parameters['END_TIME_HOURS']\nself.end_time_minutes = self.strategy_parameters['END_TIME_MINUTES']\nself.ema_period_one = self.strategy_parameters['EMA_PERIOD_ONE']\nself.ema_period_two = self.strategy_parameters['EMA_PERIOD_TWO']\nself.target_percentage = self.strategy_parameters['TARGET_PERCENTAGE']\nself.stoploss_percentage = self.strategy_parameters['STOPLOSS_PERCENTAGE']\nself.stoploss_range = self.strategy_parameters['STOPLOSS_RANGE']\nself.stoploss_order_count_allowed = self.strategy_parameters['STOPLOSS_ORDER_COUNT_ALLOWED']\n

Note

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#start-time-and-end-time-creation","title":"Start time and End time creation","text":"

Adding Start and End time is useful when you want to define a timerange between which the strategy will be running each day. Add the below code to calculate the strategy start time and end time, from the strategy_parameters. try:

    self.candle_start_time = time(hour=self.start_time_hours, minute=self.start_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting start hours and minutes... EXITING')\n    raise SystemExit\n
try:
    self.candle_end_time = time(hour=self.end_time_hours, minute=self.end_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting end time hours and minutes... EXITING')\n    raise SystemExit\n

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#strategy-variables","title":"Strategy variables","text":"

We create our own strategy variables other than the strategy parameter variables which will be used throughout the strategy.

eg: self.order_tag_manager = None

We initialize the variables with a None value.

Note

There could be more strategy variables required as per the strategy requirement.\n
"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#3-initialize-method","title":"3. Initialize method","text":"

Unlike the init method, this method gets called every day at the beginning of the day once the strategy is started.

Here the strategy variables that were initialized as None are again defined as dictionaries/lists except for the self.order_tag_manager. Create a reference for OrderTagManager as shown below:

self.order_tag_manager = OrderTagManager\n
"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#4-ordertagmanager","title":"4. OrderTagManager","text":"

The self.order_tag_manager is used to store/remove the entry/exit orders. The self.order_tag_manager has the following methods:

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#add_order","title":"add_order","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#get_orders","title":"get_orders","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#remove_tags","title":"remove_tags","text":"

Note

When the tag is removed the order objects stored in that tag are also removed but the same order objects would still be present in the order tags.

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#remove_order","title":"remove_order","text":"
self.order_tag_manager.remove_order(main_order)\n

Here the main_order order object is removed from the OrderTagManager.

Note

The order object will be removed from all the tags ta

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#get_internals","title":"get_internals","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#5-entry-methods","title":"5. Entry Methods","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#strategy_enter_position","title":"strategy_enter_position","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#6-exit-methods","title":"6. Exit Methods","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit:","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#strategy_exit_position","title":"strategy_exit_position","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#7-other-common-methods","title":"7. Other common methods","text":"

There are other methods that are used in the strategy:

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#check_and_place_stoploss_order","title":"check_and_place_stoploss_order","text":"

This method is called in the strategy_select_instruments_for_exit when our entry order is open, and we want to place a stoploss exit order for the same.

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#set_all_none","title":"set_all_none","text":"

This method is called in the strategy_exit_position when our entry order has exited, and we want to remove the order object from the self.main_order variable.

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#8-cleanup","title":"8. Cleanup","text":"
  1. Add comments and docstrings wherever possible to improve code readability.
  2. Once the strategy is completed you can optimize imports, give proper indentation and proper formatting to the strategy code and remove unwanted imports, variables, and methods before delivering the code.
"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#10-check-out-our-docs-for-developed-regular-strategies","title":"10. Check out our docs for developed Regular strategies","text":"

Tip

To know more about a strategy from our given template, simply check the first line of comment in the code of that specific strategy.

"},{"location":"pyalgotrad/strategy_guides/structure/","title":"Code Structure of Strategy","text":"

Coding Prerequisites

"},{"location":"pyalgotrad/strategy_guides/structure/#methods","title":"Methods","text":""},{"location":"pyalgotrad/strategy_guides/structure/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry()","text":"

This function helps you choose which trading instruments you want your strategy to work with. The system will use this function to go through each instrument one by one, at each candle's time. You get to write code that decides whether to place an order for a specific instrument or not.

"},{"location":"pyalgotrad/strategy_guides/structure/#strategy_enter_position","title":"strategy_enter_position()","text":"

This function is where you can place orders for the instruments you selected earlier. It's executed for each instrument you picked in the previous function.

"},{"location":"pyalgotrad/strategy_guides/structure/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit()","text":"

After you've entered a position for an instrument, this function is called for each of those instruments at each candle interval. You can use it to decide whether an instrument should be exited from the position.

"},{"location":"pyalgotrad/strategy_guides/structure/#strategy_exit_position","title":"strategy_exit_position()","text":"

In this function, you can close or exit positions for the instruments you marked for exiting in the previous function. It's done instrument by instrument.

"},{"location":"pyalgotrad/strategy_guides/structure/#supporting-methods","title":"Supporting Methods","text":"

You have the following supporting methods:

"},{"location":"pyalgotrad/strategy_guides/structure/#init","title":"init()","text":"

This method is like a starter for your strategy. It checks if the values you give it make sense and sets up some useful information for your strategy to use.

"},{"location":"pyalgotrad/strategy_guides/structure/#initialize","title":"initialize()","text":"

This method is called when your strategy begins, both at the very start and at the beginning of each trading day. It's like setting up your strategy's workspace and giving your tools a starting position.

"},{"location":"pyalgotrad/strategy_guides/structure/#name","title":"name()","text":"

This method gives your strategy a special name. It's like giving your strategy a unique nickname.

"},{"location":"pyalgotrad/strategy_guides/structure/#versions_supported","title":"versions_supported()","text":"

This method lets you specify which version of the AlgoBulls Platform your strategy works well with. It's like saying, \"My strategy is ready for this specific version of the platform.\"

"},{"location":"pyalgotrad/strategy_guides/structure/#utility-functions","title":"Utility Functions","text":"

You have the following utility function to be used in this strategy :

Links

"},{"location":"pyalgotrad/strategy_guides/structure/#get_crossover_value","title":"get_crossover_value()","text":"This handy function calculates something called the \"crossover value\" for you. It's like having a calculator that figures out this specific value for your strategy."},{"location":"pyalgotrad/strategy_guides/structure/#flowchart","title":"Flowchart","text":"

Once you create your own strategy or use a ready strategy from the pyalgostrategypool package, this is how it works internally on the AlgoBulls Core Trading Engine.

"},{"location":"python_build/pyalgotrading_analytics/","title":"Pyalgotrading Analytics","text":""},{"location":"python_build/pyalgotrading_analytics/#metric-values-and-statistics","title":"Metric Values and Statistics","text":""},{"location":"python_build/pyalgotrading_analytics/#cumulative-returns","title":"Cumulative Returns","text":""},{"location":"python_build/pyalgotrading_analytics/#end-of-year-returns-eoy","title":"End of Year Returns (EoY)","text":""},{"location":"python_build/pyalgotrading_analytics/#distributions-of-monthly-returns-histogram","title":"Distributions of Monthly Returns (Histogram)","text":""},{"location":"python_build/pyalgotrading_analytics/#daily-returns","title":"Daily Returns","text":""},{"location":"python_build/pyalgotrading_analytics/#rolling-volatility-6-months","title":"Rolling Volatility (6 months)","text":""},{"location":"python_build/pyalgotrading_analytics/#rolling-sharpe-6-months","title":"Rolling Sharpe (6 months)","text":""},{"location":"python_build/pyalgotrading_analytics/#rolling-sortino-6-months","title":"Rolling Sortino (6 months)","text":""},{"location":"python_build/pyalgotrading_analytics/#worst-5-drawdown-periods","title":"Worst 5 Drawdown Periods","text":""},{"location":"python_build/pyalgotrading_analytics/#underwater-plot","title":"Underwater Plot","text":""},{"location":"python_build/pyalgotrading_analytics/#monthly-returns-heatmap","title":"Monthly Returns (Heatmap)","text":""},{"location":"python_build/python-build-code-gen-ai/","title":"Code Using AI","text":"

If you have creative ideas in your mind and want to design a algotrading strategy but you are new at coding, don't worry, we have got it covered using our Python Build's Create Using AI feature which will help you to create trading strategies seamlessly.

Tip

You can check here on how to get your Chat-GPT API key

"},{"location":"python_build/python-build-code-gen-ai/#set-your-gen-ai-api-keys-and-model","title":"Set your Gen-AI API keys and Model","text":"
  1. Once you have retrieved the API key, you need to paste it in the input box for API keys.
  2. Select the model of AI from the drop-down menu below.
  3. Click on the Save button to save your key and model and establish the connection.

"},{"location":"python_build/python-build-code-gen-ai/#enter-your-prompts","title":"Enter your Prompts","text":"
  1. On the left hand side you can see the previous sessions and chat history
  2. Right below you will see a button for Prompts Library which has all the sample prompts that would generate wonderful strategies, you can pick any of them, if needed you can even tailor those prompts and use them.
  3. To start a new session click on New Session
  4. Enter your prompt or select from the sample prompts or take one prompt from the Prompts Library
  5. Click on the send button to start generating

Please Note, It takes some time to generate the strategy as it processes a lot of data, so please be patient

Please Note

Direct response code from gen-ai may not be 100% accurate, you will have to make sure that pythonic errors are not present. Also dont forget to configure your strategy parameters before executing the code.

Modify your code ?

To know more on how to code trading strategies and understand their format, click here. We also have in detail explanation for regular strategies as well as options strategies.

"},{"location":"python_build/python-build-code-gen-ai/#save-your-strategy","title":"Save your Strategy","text":"
  1. Once it gives you the strategy you can ask it to make more changes as per your need or you can save it directly.
  2. To save, click on the top right corner of the code, you can even copy the code if you want.
  3. Once you save it, it will redirect you to a new page where you have save your strategy and update its configuration parameters from the parameter settings.
  4. All your saved strategies can be viewed in My Coded Strategies section in Python Build.

What's Next ?

You can check out our strategy code structure and their respective formats for options and equity. Once you have verified that your strategy has no pythonic errors then you can move on to Configure and Execute your Strategy.

"},{"location":"python_build/python-build-code-new/","title":"Code New Strategy","text":""},{"location":"python_build/python-build-code-new/#how-to-code-a-new-strategy","title":"How to code a new strategy?","text":"

If you want to create your own strategy, click on the + Sign in the Code New Strategy option under the My Coded Strategies section.

A new blank code editor will open, allowing you to start coding your new strategy. You can check out the basic building blocks of a strategy here to help you with your code structure. After you've finished coding, click Save to save this strategy in the My Coded Strategies section.

How to Code ?

To know more on how to code trading strategies and understand their format, click here. We also have in detail explanation for regular strategies as well as options strategies.

Next, you need to configure the strategy\u2019s parameters by clicking on the settings symbol in the top right corner of the code editor. In this section you can add, view & edit the strategy parameters.

To test the behavior and performance of the strategy, click on Save & Start and follow the directions given earlier. The performance of the strategy will soon be available in the Results section.

You can rename a strategy by clicking the edit symbol beside the strategy name.

What's Next ?

You can check out our strategy code structure and their respective formats for options and equity. Once you have verified that your strategy has no pythonic errors then you can move on to Configure and Execute your Strategy.

"},{"location":"python_build/python-build-code-ready-templates/","title":"Code Ready Templates","text":""},{"location":"python_build/python-build-code-ready-templates/#how-to-code-strategies-using-ready-templates","title":"How to code strategies using Ready Templates?","text":"

Select a template that you would like to modify from the Ready Template section. To view all the ready-to-use templates, click on More.

Click on the Code button placed in the bottom right corner of the selected template to view the strategy code.

You should now see the code editor, where you can start modifying the code as required.

Modify your code ?

To know more on how to code trading strategies and understand their format, click here. We also have in detail explanation for regular strategies as well as options strategies.

To save the strategy, click the Save button. This strategy will be added to your list of My coded strategies.

What's Next ?

You can check out our strategy code structure and their respective formats for options and equity. Once you have verified that your strategy has no pythonic errors then you can move on to Configure and Execute your Strategy.

"},{"location":"python_build/python-build-config-parameters/","title":"Configure and Execute your Strategy","text":"

To effectively use pyalgotrading and make the most of your trading strategy, it's essential to be familiar with some frequently used stock market terminologies. Let's go over these terms before diving into configuring your strategy parameters.

  1. Exchange: An exchange is a marketplace where various financial instruments like securities, commodities, and derivatives are traded. Examples include NSE (National Stock Exchange), BSE (Bombay Stock Exchange), NYSE (New York Stock Exchange), and NASDAQ.
  2. Instruments: Instruments are the specific assets or securities traded on these exchanges. These include stocks like AAPL (Apple Inc.), TSLA (Tesla, Inc.), TATAMOTORS (Tata Motors Limited), and SBIN (State Bank of India).
  3. Candlestick Charts: Candlestick charts are commonly used in stock market analysis. They represent the opening and closing prices of a stock or asset over regular time intervals, which are often referred to as \"candle size.\"
  4. Intraday Trading: Intraday trading, also known as day trading, involves buying and selling stocks within the same trading day.
  5. Delivery Trading: Delivery trading is a type of trading where traders buy shares and hold them for an extended period, which can range from a few days to several months or even years.
  6. Position: A position refers to the amount of a security or asset owned (or sold short) by an individual or entity. Traders take positions when they make buy or sell orders.
  7. Order: An order is an instruction to buy or sell a security or asset on a trading venue, such as a stock market or cryptocurrency exchange.
  8. Crossover: A crossover occurs when two signal lines intersect. Signal lines can be various indicators like moving averages, Relative Strength Index (RSI), Volume Weighted Averages, etc. Crossovers are often used to trigger and place orders. Now that we've covered these essential terms, let's move on to configuring your trading strategy parameters.
"},{"location":"python_build/python-build-config-parameters/#configure-strategy-parameters","title":"Configure Strategy Parameters","text":"

You can configure the strategy\u2019s parameters by clicking on the settings symbol in the top right corner of the code editor. In this section, you can view a strategy\u2019s parameters or edit these parameters too.

There 4 sections for configuring your parameters:

"},{"location":"python_build/python-build-config-parameters/#instruments","title":"Instruments","text":""},{"location":"python_build/python-build-config-parameters/#strategy-settings","title":"Strategy Settings","text":""},{"location":"python_build/python-build-config-parameters/#order-settings","title":"Order Settings","text":""},{"location":"python_build/python-build-config-parameters/#user-parameters","title":"User Parameters","text":"

Once Strategy and User Parameters are configured, you can follow these steps to execute your strategy.

"},{"location":"python_build/python-build-config-parameters/#follow-these-simple-steps-to-test-the-strategys-performance","title":"Follow these simple steps to test the strategy's performance","text":"

Step 1

After clicking Save & Start, a pop-up window will appear.

Step 2

In the customizations section, choose Backtesting to backtest or Paper Trading to Paper Trade a strategy.

Select the duration option in the customizations section. Add the desired date and time, as well as the quantity/lots. In Backtesting, you will need to put the start date and end date along with time.

In Paper Trading, you only need to add the start and end time.

Step 3

In the Strategy Configuration section, you can check the parameters added or modified by you.

Step 4

To begin testing the strategy, click on Execute.

Step 5

Go to the Analytics section to see the returns and performance of the strategy visualized.

Note:

The use of Paper Trading would be available from Monday - Friday (excluding exchange's holidays) from 9 AM to 16:00 PM. You can code your strategy & analyze the strategy results 24x7.

Go to the Logs section to see the step-by-step execution of the strategy in logs.

You can rename a strategy by clicking the edit symbol beside the strategy name.

"},{"location":"python_build/python-build-getstarted/","title":"Setup your Workspace","text":""},{"location":"python_build/python-build-getstarted/#how-to-get-started-with-python-build","title":"How to get started with Python Build?","text":"

To start developing your own strategy, you must first activate a plan from the Pricing section. Select the Developers tab in the Pricing section and select a plan of your choice. There is currently one developer plan available:

After selecting your plan, you will be able to begin coding. You can either edit the preloaded Ready templates or use the My Coded Strategies section to create your own strategies.

"},{"location":"python_build/python-build-introduction/","title":"Python Build Web","text":""},{"location":"python_build/python-build-introduction/#introduction","title":"Introduction","text":"

Now you can code your own strategy easily using our Python Build service! Begin coding your own strategy from scratch, or modify some of our ready-made templates to suit your needs. Get access to our state-of-the-art AlgoBulls Core Trading Engine, which automatically leverages our infrastructure so that you can access the latest historical data to gauge the performance of your strategies. Tweak the various parameters of your strategy to choose the ideal instrument, indicator values, and profit loss percentages as per your needs! View the performance of your strategy using our visual analytics feature and continue to tweak until you are satisfied with the performance. Get your strategy approved for live trading from our experts and deploy it on 30+ supported brokers without coding any broker integration logic.

Select Python Build from the navigation bar on the left to know more.

"},{"location":"python_build/python-build-introduction/#an-overview","title":"An overview","text":"

Running Strategies: This section shows how many strategies are currently active and running in your account.

Strategies Saved: This displays the number of strategies saved in your AlgoBulls account. It also shows the number of maximum strategies that you can save as per your current plan.

Execution Time Consumed: You can view the number of minutes that have been used for Backtesting or Paper Trading your strategies.

Note:

Paper Trading would be available from Monday - Friday (excluding NSE/NASDAQ holidays) within the trading time of that particular exchange. You can code your strategy, execute on Backtesting mode or analyse the strategy results 24x7.

Analytics Support: This shows whether your analytics support is active. Analytics support is not available to free plan users.

Professional Support: This section connects you to other professional support forums for additional support while developing the strategy.

Active Plan: This section displays the current plan active on your AlgoBulls account.

Ready Templates: Ready-to-use templates that you can modify and test.

My Coded Strategies: Strategies that have been coded and saved by you are displayed here. This includes new and modified strategies developed by you.

Need Support: You can raise support for the particular statregy from here make sure your stategy is present in My Coded Strategies section

Quick Help: Resources to help you code better.

"},{"location":"python_build/python-build-professional/","title":"Python Build Professional Support","text":""},{"location":"python_build/python-build-professional/#are-you-an-experienced-trader-with-limited-coding-experience","title":"Are you an Experienced Trader with Limited Coding Experience?","text":"

If you're an experienced trader who excels at building trading strategies based on technical analysis but lacks the coding expertise to implement them, Python Build offers you the perfect solution \u2013 our Python Build Professional Support.

"},{"location":"python_build/python-build-professional/#how-can-python-build-professional-support-help-you","title":"How Can Python Build Professional Support Help You?","text":"

Our Python Build Professional Support bridges the gap between your market expertise in technical analysis and our proficiency in coding and algo trading strategy development. We understand that not everyone is a coding wizard, and that's where our professional support comes in.

"},{"location":"python_build/python-build-professional/#getting-started","title":"Getting Started","text":"

To take advantage of our Python Build Professional Support, follow these simple steps:

  1. Click on \"Professional Support\" - Look for the \"Professional Support\" button on the Python Build Web splash and click on it to get started.

  2. Describe Your Strategy - Once you're in the professional support interface, you'll be prompted to describe your trading strategy. You can provide details on how you want your strategy to work, including entry and exit criteria, risk management rules, and any specific requirements you have.

    Sample Prompt: \"I want a strategy that buys stocks when the 50-day moving average crosses above the 200-day moving average and sells when it crosses below. Additionally, I'd like a stop-loss of 5% and a take-profit at 10%.\"

  3. Indicate Technical Indicators - Specify which technical indicators you want to use in your strategy. You can mention indicators like moving averages, RSI, MACD, or any others that are crucial for your trading approach.

  4. Submit Your Request - Once you've filled in the necessary information, click on the \"Submit\" button. Your request will be sent to our professional support team.

"},{"location":"python_build/python-build-professional/#what-happens-next","title":"What Happens Next?","text":"

Our dedicated professional support team will promptly review your request. They will connect with you to gather any additional details if needed and ensure they have a clear understanding of your requirements.

Our team of experienced Python developers and algo trading experts will then get to work on implementing your strategy according to your specifications. We'll ensure that your strategy is coded efficiently and effectively, leveraging the power of Python Build.

You can expect to receive your custom-coded trading strategy as soon as possible, allowing you to put your trading expertise to work without the coding hassle.

With Python Build's Professional Support, you can confidently bring your trading ideas to life and stay ahead in the competitive world of stock market trading. Start automating your strategies today!

"},{"location":"python_build/python-build-view-results/","title":"Analytics","text":""},{"location":"python_build/python-build-view-results/#how-to-view-the-results","title":"How to view the Results?","text":"

Once you start the strategy, it may take a while for it to complete the execution. You can switch to the Analytics tab after you run your strategy. Even if the strategy execution is not complete, you will still see intermediate results.

Analytics: In the analytics section, you can view a strategy\u2019s Stats & various other metrics in the form of graphs like P&L.

"},{"location":"python_build/python-build-view-results/#stats","title":"Stats","text":"

In this section you can see the total returns, sharpe ratio, sortino ratio, volatility, Max Drawdown, Total wins or Loses, Total short or long trades, hit ratio, number of trades, average trades per day, max profit, max loss, average profit per winning trade, average loss per losing trade.

"},{"location":"python_build/python-build-view-results/#cumulative-returns","title":"Cumulative Returns","text":""},{"location":"python_build/python-build-view-results/#profit-loss-currency-or","title":"Profit & Loss (Currency or %)","text":"

The trade by trade P&L in Currency or Percentage.

"},{"location":"python_build/python-build-view-results/#end-of-year-returns-plot","title":"End of Year Returns Plot (%)","text":""},{"location":"python_build/python-build-view-results/#monthly-returns-histogram","title":"Monthly Returns Histogram (%)","text":""},{"location":"python_build/python-build-view-results/#monthly-returns-heatmap","title":"Monthly Returns Heatmap (%)","text":""},{"location":"python_build/python-build-view-results/#daily-returns","title":"Daily Returns (%)","text":""},{"location":"python_build/python-build-view-results/#underwater-drawdown-plot","title":"Underwater Drawdown Plot (%)","text":""},{"location":"python_build/python-build-view-results/#pl-book","title":"P&L Book","text":"

View detailed trade by trade report. Premium users can analyze this data in the form of heatmaps for Gross Profit & Loss, Trading Volume & Total number of Trades.

"},{"location":"python_build/python-build-view-results/#user-log","title":"User Log","text":"

Real-time logs from strategy execution are displayed in this section. Use these logs to debug your strategy\u2019s behavior and performance.

"},{"location":"python_build/python-build-view-results/#order-history","title":"Order History","text":"

View the order state transition for every order placed by your strategy in-depth.

"},{"location":"python_build/strategy_guides/common_options_strategy/","title":"Options Strategy Structure","text":"

Links

"},{"location":"python_build/strategy_guides/common_options_strategy/#1-initial-steps","title":"1. Initial steps","text":""},{"location":"python_build/strategy_guides/common_options_strategy/#naming-a-class","title":"Naming a Class","text":"eg: For the above strategy name the class name would be:
StrategyOptionsEMACrossover(StrategyOptionsBaseV2)\n

Coding Conventions

* Make a class with the same name as the file name\n* Make sure the first letter of each word is in uppercase and the initials should be in uppercase as well.\n* If the class name includes indicator names like EMA, SMA, and VWAP the name should be in uppercase in the class name but not in the file name.\n* Every options strategy is a child class of the StrategyOptionsBaseV2 class.\n
"},{"location":"python_build/strategy_guides/common_options_strategy/#naming-your-strategy","title":"Naming your Strategy","text":"

This name will be displayed in your My Coded Strategies in Python Build Web, and it will also be the strategy_name when you are fetching all strategies in pyalgotrading. Inside your strategy class, you can write your first parameter as name.

name = 'options_ema_crossover'\n

"},{"location":"python_build/strategy_guides/common_options_strategy/#2-init-method","title":"2. Init method","text":"

This method gets called only once when the strategy is started.

"},{"location":"python_build/strategy_guides/common_options_strategy/#strategy-info","title":"Strategy info","text":"

In the init method add the line given below

super().__init__(*args, **kwargs)\n

"},{"location":"python_build/strategy_guides/common_options_strategy/#parameter-creation","title":"Parameter creation","text":"

Next, we assign the parameter values to the class variables of the same name as the parameters but in the lowercase format as shown below:

eg:

self.fresh_order_candle = self.strategy_parameters['FRESH_ORDER_CANDLE']\nself.start_time_hours = self.strategy_parameters['START_TIME_HOURS']\nself.start_time_minutes = self.strategy_parameters['START_TIME_MINUTES']\nself.end_time_hours = self.strategy_parameters['END_TIME_HOURS']\nself.end_time_minutes = self.strategy_parameters['END_TIME_MINUTES']\nself.no_of_strikes_away_ce = self.strategy_parameters['NO_OF_STRIKES_AWAY_CE']\nself.no_of_strikes_away_p = self.strategy_parameters['NO_OF_STRIKES_AWAY_PE']\nself._strike_direction_ce = self.strategy_parameters['STRIKES_DIRECTION_CE']\nself._strike_direction_pe = self.strategy_parameters['STRIKES_DIRECTION_PE']\nself.ema_period_one = self.strategy_parameters['EMA_PERIOD_ONE']\nself.ema_period_two = self.strategy_parameters['EMA_PERIOD_TWO']\nself.target_percentage = self.strategy_parameters['TARGET_PERCENTAGE']\nself.stoploss_percentage = self.strategy_parameters['STOPLOSS_PERCENTAGE']\nself.stoploss_range = self.strategy_parameters['STOPLOSS_RANGE']\nself.stoploss_order_count_allowed = self.strategy_parameters['STOPLOSS_ORDER_COUNT_ALLOWED']\n

Note

"},{"location":"python_build/strategy_guides/common_options_strategy/#start-time-and-end-time-creation","title":"Start time and End time creation","text":"

Adding Start and End time is useful when you want to define a timerange between which the strategy will be running each day. Add the below code to calculate the strategy start time and end time, from the strategy_parameters.

try:

    self.candle_start_time = time(hour=self.start_time_hours, minute=self.start_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting start hours and minutes... EXITING')\n    raise SystemExit\n
try:
    self.candle_end_time = time(hour=self.end_time_hours, minute=self.end_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting end time hours and minutes... EXITING')\n    raise SystemExit\n

"},{"location":"python_build/strategy_guides/common_options_strategy/#strategy-variables","title":"Strategy variables","text":"

We create our own strategy variables other than the strategy parameter variables which will be used throughout the strategy.

eg:

self.main_order = None            # We save the entry order in this variable\nself.stoploss_order = None        # We save the corresponding stoploss exit order of the entry order in this variable\n
We initialize the variables with a None value. !!! Note There could be more strategy variables required as per the strategy requirement.

"},{"location":"python_build/strategy_guides/common_options_strategy/#3-initialize-method","title":"3. Initialize method","text":"

Unlike the init method, this method gets called every day at the beginning of the day once the strategy is started.

Here the strategy variables that were initialized as None are again defined as dictionaries/lists except for the self.order_tag_manager. Create a reference for OrderTagManager as shown below:

self.order_tag_manager = OrderTagManager\n
"},{"location":"python_build/strategy_guides/common_options_strategy/#4-ordertagmanager","title":"4. OrderTagManager","text":"

The self.order_tag_manager is used to store/remove the entry/exit orders. The self.order_tag_manager has the following methods:

"},{"location":"python_build/strategy_guides/common_options_strategy/#add_order","title":"add_order","text":"
self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
"},{"location":"python_build/strategy_guides/common_options_strategy/#get_orders","title":"get_orders","text":"

eg:

self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
"},{"location":"python_build/strategy_guides/common_options_strategy/#remove_tags","title":"remove_tags","text":"

eg:

self.order_tag_manager.remove_tags(tags=entry_key)\n

Here the entry_key tag is removed from the OrderTagManager.

Note

When the tag is removed the order objects stored in that tag are also removed but the same order objects would still be present in order tags.

"},{"location":"python_build/strategy_guides/common_options_strategy/#remove_order","title":"remove_order","text":"

eg:

self.order_tag_manager.remove_order(main_order)\n
Here the main_order order object is removed from the OrderTagManager.

Note

The order object will be removed from all the tags ta

"},{"location":"python_build/strategy_guides/common_options_strategy/#get_internals","title":"get_internals","text":"
Returns the values i.e. both the entry and exit orders stored inside the tags list.\n
"},{"location":"python_build/strategy_guides/common_options_strategy/#5-child-instruments-calculation","title":"5. Child instruments calculation","text":""},{"location":"python_build/strategy_guides/common_options_strategy/#get_ltp","title":"get_ltp","text":"

Fetch the ltp of the base instrument (instrument set while executing strategy)

ltp = self.broker.get_ltp(self.underlying_instrument)\n

"},{"location":"python_build/strategy_guides/common_options_strategy/#options_instruments_set_up_local","title":"options_instruments_set_up_local","text":"

Get the ATM ITM and OTM lists of the child instrument based on the LTP

self.options_instruments_set_up_local(self.underlying_instrument, tradingsymbol_suffix, ltp)\n

"},{"location":"python_build/strategy_guides/common_options_strategy/#get_child_instrument_details","title":"get_child_instrument_details","text":"

Select a child instrument from the lists of ATM, ITM, and OTM based on the strike direction and no of strikes given for the child instrument

child_instrument = self.get_child_instrument_details(self.underlying_instrument, tradingsymbol_suffix, strike_direction, no_of_strikes)\n

"},{"location":"python_build/strategy_guides/common_options_strategy/#6-entry-methods","title":"6. Entry Methods","text":""},{"location":"python_build/strategy_guides/common_options_strategy/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry","text":""},{"location":"python_build/strategy_guides/common_options_strategy/#strategy_enter_position","title":"strategy_enter_position","text":""},{"location":"python_build/strategy_guides/common_options_strategy/#7-exit-methods","title":"7. Exit Methods","text":""},{"location":"python_build/strategy_guides/common_options_strategy/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit","text":""},{"location":"python_build/strategy_guides/common_options_strategy/#strategy_exit_position","title":"strategy_exit_position","text":""},{"location":"python_build/strategy_guides/common_options_strategy/#8-other-common-methods","title":"8. Other common methods","text":"

There are other methods that are used in the strategy:

"},{"location":"python_build/strategy_guides/common_options_strategy/#check_and_place_stoploss_order","title":"check_and_place_stoploss_order","text":"

This method is called in the strategy_select_instruments_for_exit when our entry order is open, and we want to place a stoploss exit order for the same.

"},{"location":"python_build/strategy_guides/common_options_strategy/#set_all_none","title":"set_all_none","text":"

This method is called in the strategy_exit_position when our entry order has exited, and we want to remove the order object from the self.main_order variable.

"},{"location":"python_build/strategy_guides/common_options_strategy/#options_instruments_set_up_local_1","title":"options_instruments_set_up_local","text":"

This method is called in the strategy_select_instruments_for_entry to fetch the ATM, ITM, and OTM lists of the child instruments based on the LTP of the base instrument.

"},{"location":"python_build/strategy_guides/common_options_strategy/#get_child_instrument_details_1","title":"get_child_instrument_details","text":"

This method is called in the strategy_select_instruments_for_entry to fetch a single child instrument based on the no of strikes and strike direction.

"},{"location":"python_build/strategy_guides/common_options_strategy/#9-cleanup","title":"9. Cleanup","text":"
  1. Add comments and docstrings wherever possible to improve code readability.
  2. Once the strategy is completed you can optimize imports, give proper indentation and proper formatting to the strategy code and remove unwanted imports, variables, and methods before delivering the code.
"},{"location":"python_build/strategy_guides/common_options_strategy/#10-check-out-our-docs-for-developed-options-strategies","title":"10. Check out our docs for developed Options strategies","text":"

Tip

To know more about a strategy from our given template, simply check the first line of comment in the code of that specific strategy.

"},{"location":"python_build/strategy_guides/common_regular_strategy/","title":"Regular Strategy Structure","text":"

Links

"},{"location":"python_build/strategy_guides/common_regular_strategy/#1-initial-steps","title":"1. Initial steps","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#naming-a-class","title":"Naming a Class","text":"eg: For the above strategy name the class name would be:
StrategyFuturesEMACrossover(StrategyBase)\n

Coding Conventions

* Make a class with the same name as the file name\n* Make sure the first letter of each word is in uppercase and the initials should be in uppercase as well.\n* If the class name includes indicator names like EMA, SMA, and VWAP the name should be in uppercase in the class name but not in the file name.\n* Every strategy is a child class of the StrategyBase class.\n
"},{"location":"python_build/strategy_guides/common_regular_strategy/#naming-your-strategy","title":"Naming your Strategy","text":"

This name will be displayed in your My Coded Strategies in Python Build Web, and it will also be the strategy_name when you are fetching all strategies in pyalgotrading. Inside your strategy class, you can write your first parameter as name.

name = 'futures_ema_crossover'\n

"},{"location":"python_build/strategy_guides/common_regular_strategy/#2-init-method","title":"2. Init method","text":"

This method gets called only once when the strategy is started.

"},{"location":"python_build/strategy_guides/common_regular_strategy/#strategy-info","title":"Strategy info","text":"

In the init method add the line given below

super().__init__(*args, **kwargs)\n

"},{"location":"python_build/strategy_guides/common_regular_strategy/#parameter-creation","title":"Parameter creation","text":"

Next we assign the parameter values to the class variables of the same name as the parameters but in the lowercase format, as shown below:

eg:

self.fresh_order_candle = self.strategy_parameters['FRESH_ORDER_CANDLE']\nself.start_time_hours = self.strategy_parameters['START_TIME_HOURS']\nself.start_time_minutes = self.strategy_parameters['START_TIME_MINUTES']\nself.end_time_hours = self.strategy_parameters['END_TIME_HOURS']\nself.end_time_minutes = self.strategy_parameters['END_TIME_MINUTES']\nself.ema_period_one = self.strategy_parameters['EMA_PERIOD_ONE']\nself.ema_period_two = self.strategy_parameters['EMA_PERIOD_TWO']\nself.target_percentage = self.strategy_parameters['TARGET_PERCENTAGE']\nself.stoploss_percentage = self.strategy_parameters['STOPLOSS_PERCENTAGE']\nself.stoploss_range = self.strategy_parameters['STOPLOSS_RANGE']\nself.stoploss_order_count_allowed = self.strategy_parameters['STOPLOSS_ORDER_COUNT_ALLOWED']\n

Note

"},{"location":"python_build/strategy_guides/common_regular_strategy/#start-time-and-end-time-creation","title":"Start time and End time creation","text":"

Adding Start and End time is useful when you want to define a timerange between which the strategy will be running each day. Add the below code to calculate the strategy start time and end time, from the strategy_parameters. try:

    self.candle_start_time = time(hour=self.start_time_hours, minute=self.start_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting start hours and minutes... EXITING')\n    raise SystemExit\n
try:
    self.candle_end_time = time(hour=self.end_time_hours, minute=self.end_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting end time hours and minutes... EXITING')\n    raise SystemExit\n

"},{"location":"python_build/strategy_guides/common_regular_strategy/#strategy-variables","title":"Strategy variables","text":"

We create our own strategy variables other than the strategy parameter variables which will be used throughout the strategy.

eg: self.order_tag_manager = None

We initialize the variables with a None value.

Note

There could be more strategy variables required as per the strategy requirement.\n
"},{"location":"python_build/strategy_guides/common_regular_strategy/#3-initialize-method","title":"3. Initialize method","text":"

Unlike the init method, this method gets called every day at the beginning of the day once the strategy is started.

Here the strategy variables that were initialized as None are again defined as dictionaries/lists except for the self.order_tag_manager. Create a reference for OrderTagManager as shown below:

self.order_tag_manager = OrderTagManager\n
"},{"location":"python_build/strategy_guides/common_regular_strategy/#4-ordertagmanager","title":"4. OrderTagManager","text":"

The self.order_tag_manager is used to store/remove the entry/exit orders. The self.order_tag_manager has the following methods:

"},{"location":"python_build/strategy_guides/common_regular_strategy/#add_order","title":"add_order","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#get_orders","title":"get_orders","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#remove_tags","title":"remove_tags","text":"

Note

When the tag is removed the order objects stored in that tag are also removed but the same order objects would still be present in the order tags.

"},{"location":"python_build/strategy_guides/common_regular_strategy/#remove_order","title":"remove_order","text":"
self.order_tag_manager.remove_order(main_order)\n

Here the main_order order object is removed from the OrderTagManager.

Note

The order object will be removed from all the tags ta

"},{"location":"python_build/strategy_guides/common_regular_strategy/#get_internals","title":"get_internals","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#5-entry-methods","title":"5. Entry Methods","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#strategy_enter_position","title":"strategy_enter_position","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#6-exit-methods","title":"6. Exit Methods","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit:","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#strategy_exit_position","title":"strategy_exit_position","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#7-other-common-methods","title":"7. Other common methods","text":"

There are other methods that are used in the strategy:

"},{"location":"python_build/strategy_guides/common_regular_strategy/#check_and_place_stoploss_order","title":"check_and_place_stoploss_order","text":"

This method is called in the strategy_select_instruments_for_exit when our entry order is open, and we want to place a stoploss exit order for the same.

"},{"location":"python_build/strategy_guides/common_regular_strategy/#set_all_none","title":"set_all_none","text":"

This method is called in the strategy_exit_position when our entry order has exited, and we want to remove the order object from the self.main_order variable.

"},{"location":"python_build/strategy_guides/common_regular_strategy/#8-cleanup","title":"8. Cleanup","text":"
  1. Add comments and docstrings wherever possible to improve code readability.
  2. Once the strategy is completed you can optimize imports, give proper indentation and proper formatting to the strategy code and remove unwanted imports, variables, and methods before delivering the code.
"},{"location":"python_build/strategy_guides/common_regular_strategy/#10-check-out-our-docs-for-developed-regular-strategies","title":"10. Check out our docs for developed Regular strategies","text":"

Tip

To know more about a strategy from our given template, simply check the first line of comment in the code of that specific strategy.

"},{"location":"python_build/strategy_guides/structure/","title":"Code Structure of Strategy","text":"

Coding Prerequisites

"},{"location":"python_build/strategy_guides/structure/#methods","title":"Methods","text":""},{"location":"python_build/strategy_guides/structure/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry()","text":"

This function helps you choose which trading instruments you want your strategy to work with. The system will use this function to go through each instrument one by one, at each candle's time. You get to write code that decides whether to place an order for a specific instrument or not.

"},{"location":"python_build/strategy_guides/structure/#strategy_enter_position","title":"strategy_enter_position()","text":"

This function is where you can place orders for the instruments you selected earlier. It's executed for each instrument you picked in the previous function.

"},{"location":"python_build/strategy_guides/structure/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit()","text":"

After you've entered a position for an instrument, this function is called for each of those instruments at each candle interval. You can use it to decide whether an instrument should be exited from the position.

"},{"location":"python_build/strategy_guides/structure/#strategy_exit_position","title":"strategy_exit_position()","text":"

In this function, you can close or exit positions for the instruments you marked for exiting in the previous function. It's done instrument by instrument.

"},{"location":"python_build/strategy_guides/structure/#supporting-methods","title":"Supporting Methods","text":"

You have the following supporting methods:

"},{"location":"python_build/strategy_guides/structure/#init","title":"init()","text":"

This method is like a starter for your strategy. It checks if the values you give it make sense and sets up some useful information for your strategy to use.

"},{"location":"python_build/strategy_guides/structure/#initialize","title":"initialize()","text":"

This method is called when your strategy begins, both at the very start and at the beginning of each trading day. It's like setting up your strategy's workspace and giving your tools a starting position.

"},{"location":"python_build/strategy_guides/structure/#name","title":"name()","text":"

This method gives your strategy a special name. It's like giving your strategy a unique nickname.

"},{"location":"python_build/strategy_guides/structure/#versions_supported","title":"versions_supported()","text":"

This method lets you specify which version of the AlgoBulls Platform your strategy works well with. It's like saying, \"My strategy is ready for this specific version of the platform.\"

"},{"location":"python_build/strategy_guides/structure/#utility-functions","title":"Utility Functions","text":"

You have the following utility function to be used in this strategy :

Links

"},{"location":"python_build/strategy_guides/structure/#get_crossover_value","title":"get_crossover_value()","text":"This handy function calculates something called the \"crossover value\" for you. It's like having a calculator that figures out this specific value for your strategy."},{"location":"python_build/strategy_guides/structure/#flowchart","title":"Flowchart","text":"

Once you create your own strategy or use a ready strategy from the pyalgostrategypool package, this is how it works internally on the AlgoBulls Core Trading Engine.

"},{"location":"strategies/aroon_crossover/","title":"Aroon Crossover","text":"

This is a trading strategy called \"Aroon Crossover\" implemented in Python using the PyAlgoTrading library. The strategy is based on the Aroon indicator crossover.

Links

Jupyter Notebooks for Indian Exchange (NSE)

Jupyter Notebook for US Exchange (NASDAQ)

"},{"location":"strategies/aroon_crossover/#aroon-indicator","title":"Aroon Indicator","text":" Fig.1 - SPY candle chart (top), Aroon Indicator for that chart (bottom)"},{"location":"strategies/aroon_crossover/#strategy-overview","title":"Strategy Overview","text":"

This strategy, called Aroon Crossover, implements a crossover strategy using the Aroon indicator. It generates entry and exit signals based on the crossover of Aroon Up and Aroon Down values.

"},{"location":"strategies/aroon_crossover/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description TIME_PERIOD None greater than 0 The period for which we calculate the Aroon Value"},{"location":"strategies/aroon_crossover/#crossover-calculation","title":"Crossover Calculation","text":"

The get_crossover_value method calculates the Aroon Up and Aroon Down values for a given instrument based on the historical data. It uses the talib.AROON function from the Talib library to calculate the values. The method then determines the crossover of Aroon Up and Aroon Down and returns the corresponding entry or exit action.

"},{"location":"strategies/bollinger_bands/","title":"Bollinger Bands","text":"

This is a trading strategy called \"Bollinger Bands\" implemented in Python using the PyAlgoTrading library. The strategy is based on the bollinger bands indicator values.

Links

Jupyter Notebooks for Indian Exchange (NSE)

Jupyter Notebook for US Exchange (NASDAQ)

"},{"location":"strategies/bollinger_bands/#bollinger-bands-indicator","title":"Bollinger Bands Indicator","text":"

Bollinger Bands consists of a middle band (typically a 20-day Simple Moving Average) and two bands that represent the upper and lower price boundaries based on standard deviations. The bands adjust dynamically with market volatility.

Key points about Bollinger Bands:

Fig.1 - SPY candle chart (top) with Bollinger Bands (purple), 20 day standard deviation graph (bottom)"},{"location":"strategies/bollinger_bands/#strategy-overview","title":"Strategy Overview","text":"

This strategy, called Bollinger Bands, is an implementation of the Bollinger Bands indicator. It uses the Bollinger Bands values to compare with previous candle's OPEN, HIGH, LOW and CLOSE values and generate entry and exit signals for trading instruments.

"},{"location":"strategies/bollinger_bands/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description TIME_PERIOD None greater than 0 Period (number of candles) by which Bollinger Bands are calculated STANDARD_DEVIATION None between 0 to 10 Standard deviation (in percent) for upper and lower band from the signal bands"},{"location":"strategies/bollinger_bands/#decision-calculation","title":"Decision Calculation","text":"

The get_decision method calculates the Bollinger Bands values for a given instrument based on the OHLC (Open, High, Low, Close) historical data. It uses the talib.BBANDS function from the Talib library to calculate the upper and lower bands. The method compares the previous candle's open, low, and close values with the upper and lower bands to determine the entry or exit action. If the conditions for a buy or sell signal are met, the corresponding action is returned.

"},{"location":"strategies/ema_crossover/","title":"EMA Crossover","text":"

This is a trading strategy called \"EMA Regular Order Strategy\" implemented in Python using the PyAlgoTrading library. The strategy is based on the exponential moving average crossover.

Links

Jupyter Notebooks for Indian Exchange (NSE)

Jupyter Notebook for US Exchange (NASDAQ)

"},{"location":"strategies/ema_crossover/#ema-indicator","title":"EMA indicator","text":"

Exponential Moving Averages (EMAs) are a popular technical analysis tool used in the stock market. They are similar to Simple Moving Averages (SMAs), but they place greater emphasis on recent price data.

Here is a summary of Exponential Moving Averages:

Fig.1 - IBM candle chart (top) with EMA (green) and SMA (red) lines"},{"location":"strategies/ema_crossover/#strategy-overview","title":"Strategy Overview","text":"

This strategy, called EMA Regular Order Strategy, implements a crossover strategy using Exponential Moving Averages (EMA). It generates entry and exit signals based on the crossover of two EMAs.

"},{"location":"strategies/ema_crossover/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description TIME_PERIOD1 None greater than 0 Period (number of candles) by which EMA-1 is calculated TIME_PERIOD2 None greater than 0 Period (number of candles) by which EMA-2 is calculated"},{"location":"strategies/ema_crossover/#crossover-calculation","title":"Crossover Calculation","text":"

The get_crossover_value method calculates the crossover value based on the two EMAs of the closing prices. It uses the talib.EMA function from the Talib library to calculate the EMAs. The method then determines the crossover between the two EMAs and returns the corresponding value (-1, 0, or 1).

"},{"location":"strategies/inverse_ema_scalping/","title":"Inverse EMA Scalping","text":"

This is a trading strategy called \"Inverse EMA Scalping Regular Order Strategy\" implemented in Python using the PyAlgoTrading library. The strategy is based on the exponential moving average crossover.

Links

Jupyter Notebooks for Indian Exchange (NSE)

Jupyter Notebooks for US Exchange (NASDAQ)

"},{"location":"strategies/inverse_ema_scalping/#what-is-inverse-ema","title":"What is Inverse EMA","text":"

Inverse EMA, also known as Reverse Exponential Moving Average (REMA), is a variation of the Exponential Moving Average (EMA) in the stock market. While the EMA gives more weight to recent price data, the Inverse EMA assigns more weight to older data points.

Here is a summary of Inverse EMA:

"},{"location":"strategies/inverse_ema_scalping/#strategy-overview","title":"Strategy Overview","text":"

This strategy implements a scalping strategy using Exponential Moving Averages (EMA). It generates entry and exit signals based on the inverse crossover of two EMAs.

"},{"location":"strategies/inverse_ema_scalping/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description LARGER_TIME_PERIOD None greater than 0 Period (number of candles) by which large period EMA is calculated SMALLER_TIME_PERIOD None greater than 0 Period (number of candles) by which short period EMA is calculated"},{"location":"strategies/inverse_ema_scalping/#crossover-calculation","title":"Crossover Calculation","text":"

The get_crossover_value method calculates the crossover value based on the inverse crossover of the two EMAs of the closing prices. It uses the talib.EMA function from the Talib library to calculate the EMAs. The method then determines the inverse crossover between the two EMAs and returns the corresponding value (-1, 0, or 1).

"},{"location":"strategies/macd_crossover/","title":"MACD Crossover","text":"

This is a trading strategy called \"MACD Crossovers\" implemented in Python using the PyAlgoTrading library. The strategy is based on the MACD indicator crossover.

Links

Jupyter Notebook for Indian Exchange (NSE)

"},{"location":"strategies/macd_crossover/#macd-crossover_1","title":"MACD Crossover","text":"

In the dynamic world of stock trading, mastering effective strategies is the key to success. The Moving Average Convergence Divergence (MACD) Crossover strategy is a powerful tool that can help traders identify potential entry and exit points in the stock market.

Here is a summary of RSI and MACD in the stock market: - The MACD is a trend-following momentum indicator that consists of two lines: the MACD line and the Signal line. - A bullish signal is generated when the MACD line crosses above the Signal line, indicating a potential uptrend. - Conversely, a bearish signal occurs when the MACD line crosses below the Signal line, suggesting a potential downtrend. - When the MACD crosses above the Signal line, it's a signal to consider a long (BUY) position. - Conversely, when the MACD crosses below the Signal line, it may be time to think about a short (SELL) position.

"},{"location":"strategies/macd_crossover/#strategy-overview","title":"Strategy Overview","text":"

The MACD Crossover strategy is a robust approach that leverages the power of the MACD indicator to identify potential entry and exit points in the stock market.

"},{"location":"strategies/macd_crossover/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description TIMEPERIOD_FAST None greater than 0 Period (number of candles) by which EMA 2 is calculated TIMEPERIOD_SLOW None greater than 0 Period (number of candles) by which EMA 2 is calculated TIMEPERIOD_SIGNAL None greater than 0 Period (number of candles) by which moving average is calculated"},{"location":"strategies/macd_crossover/#crossover-calculation","title":"Crossover Calculation","text":"

The get_crossover_value method calculates the crossover value based on the inverse crossover of the two EMAs of the closing prices. It uses the talib.MACD function from the Talib library to calculate the MACDs. The method then determines the crossover between the two MACDs and returns the corresponding value (-1, 0, or 1).

"},{"location":"strategies/mean_reversion_bollinger_bands/","title":"Mean Reversion Bollinger Bands","text":"

This is a trading strategy called \"Mean Reversion Bollinger Bands\" implemented in Python using the PyAlgoTrading library. The strategy is based on the bollingerbands indicator.

Links

Jupyter Notebook for Indian Exchange (NSE)

"},{"location":"strategies/mean_reversion_bollinger_bands/#mean-reversion-bollinger-bands_1","title":"Mean Reversion Bollinger Bands","text":"

In the dynamic world of stock trading, effective strategies can make all the difference. The Mean Reversion Bollinger Bands strategy is a powerful tool that traders can use to identify potential entry and exit points in the stock market.

Here is a summary of RSI and MACD in the stock market: - Bollinger Bands are a volatility indicator that consists of a middle band (usually a simple moving average), an upper band, and a lower band. These bands expand and contract based on price volatility. The strategy leverages these bands to identify potential mean reversion opportunities. - Mean reversion is the idea that prices tend to revert to their historical average over time. In this strategy, traders look for situations where the price deviates significantly from the middle Bollinger Band and expect it to revert to the mean. - The Mean Reversion Bollinger Bands strategy involves identifying price movements that touch or cross the upper or lower bands and anticipating a reversal. - When the price touches the upper band, traders may consider a short (SELL) position, expecting a downward move. - Conversely, when the price touches the lower band, it may signal a potential long (BUY) opportunity, anticipating an upward move.

"},{"location":"strategies/mean_reversion_bollinger_bands/#strategy-overview","title":"Strategy Overview","text":"

The Mean Reversion Bollinger Bands strategy is a robust approach that leverages the power of Bollinger Bands to identify potential mean reversion opportunities in the stock market.

"},{"location":"strategies/mean_reversion_bollinger_bands/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description TIME_PERIOD None greater than 0 Period (number of candles) by which Bollinger Bands are calculated STANDARD_DEVIATION None between 0 to 10 Standard deviation (in percent) for upper and lower band from the signal bands"},{"location":"strategies/mean_reversion_bollinger_bands/#decision-calculation","title":"Decision Calculation","text":"

The get_decision method calculates the Bollinger Bands values for a given instrument based on the OHLC (Open, High, Low, Close) historical data. It uses the talib.BBANDS function from the Talib library to calculate the upper and lower bands. The method compares the previous candle's open, low, and close values with the upper and lower bands to determine the entry or exit action. If the conditions for a buy or sell signal are met, the corresponding action is returned.

"},{"location":"strategies/options_bear_call_ladder/","title":"Options Bear Call Ladder","text":""},{"location":"strategies/options_bear_call_ladder/#options-bear-call-ladder","title":"Options Bear Call Ladder","text":"

This class implements the Options Bear Call Ladder strategy.

Links

Jupyter Notebook for Options from Indian Exchange (NSE)

"},{"location":"strategies/options_bear_call_ladder/#bear-call-ladder","title":"Bear Call Ladder","text":""},{"location":"strategies/options_bear_call_ladder/#parameters","title":"Parameters","text":"Name Default Value Expected Value Description LEG_ONE_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_ONE_TRADING_SYMBOL_SUFFIX 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_ONE_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_ONE_NUMBER_OF_STRIKES 0 greater than 0 Number of strikes for leg one. LEG_TWO_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_TWO_TRADING_SYMBOL_SUFFIX 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_TWO_STRIKE_DIRECTION 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_TWO_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one. LEG_THREE_TRANSACTION_TYPE 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_THREE_TRADING_SYMBOL_SUFFIX 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_THREE_STRIKE_DIRECTION 0 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_THREE_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one."},{"location":"strategies/options_bear_put_ladder/","title":"Options Bear Put Ladder","text":""},{"location":"strategies/options_bear_put_ladder/#options-bear-put-ladder","title":"Options Bear Put Ladder","text":"

This is a template for the Options Bear Put Ladder strategy. The strategy involves the combination of buying and selling put options to profit from a downward price movement in the underlying asset. It utilizes multiple legs with different strike prices and transaction types to create a ladder-like structure.

Links

Jupyter Notebook for Options from Indian Exchange (NSE)

"},{"location":"strategies/options_bear_put_ladder/#bear-put-ladder","title":"Bear Put Ladder","text":""},{"location":"strategies/options_bear_put_ladder/#parameters","title":"Parameters","text":"Name Default Value Expected Value Description LEG_ONE_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_ONE_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_ONE_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_ONE_NUMBER_OF_STRIKES 0 greater than 0 Number of strikes for leg one. LEG_TWO_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_TWO_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_TWO_STRIKE_DIRECTION 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_TWO_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one. LEG_THREE_TRANSACTION_TYPE 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_THREE_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_THREE_STRIKE_DIRECTION 0 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_THREE_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one."},{"location":"strategies/options_bull_call_ladder/","title":"Options Bull Call Ladder","text":""},{"location":"strategies/options_bull_call_ladder/#options-bull-call-ladder","title":"Options Bull Call Ladder","text":"

Links

Jupyter Notebook for Options from Indian Exchange (NSE)

"},{"location":"strategies/options_bull_call_ladder/#bull-call-ladder","title":"Bull Call Ladder","text":""},{"location":"strategies/options_bull_call_ladder/#parameters","title":"Parameters","text":"Name Default Value Expected Value Description LEG_ONE_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_ONE_TRADING_SYMBOL_SUFFIX 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_ONE_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_ONE_NUMBER_OF_STRIKES 0 greater than 0 Number of strikes for leg one. LEG_TWO_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_TWO_TRADING_SYMBOL_SUFFIX 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_TWO_STRIKE_DIRECTION 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_TWO_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one. LEG_THREE_TRANSACTION_TYPE 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_THREE_TRADING_SYMBOL_SUFFIX 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_THREE_STRIKE_DIRECTION 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_THREE_NUMBER_OF_STRIKES 4 greater than 0 Number of strikes for leg one."},{"location":"strategies/options_bull_put_ladder/","title":"Options Bull Put Ladder","text":""},{"location":"strategies/options_bull_put_ladder/#options-bull-put-ladder","title":"Options Bull Put Ladder","text":"

Links

Jupyter Notebook for Options from Indian Exchange (NSE)

"},{"location":"strategies/options_bull_put_ladder/#bull-put-ladder","title":"Bull Put ladder","text":""},{"location":"strategies/options_bull_put_ladder/#initialization","title":"Initialization","text":"

The __init__ method initializes the strategy and accepts parameters for configuring the strategy. The parameters are:

Name Default Value Expected Value Description LEG_ONE_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_ONE_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_ONE_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_ONE_NUMBER_OF_STRIKES 0 greater than 0 Number of strikes for leg one. LEG_TWO_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_TWO_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_TWO_STRIKE_DIRECTION 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_TWO_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one. LEG_THREE_TRANSACTION_TYPE 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_THREE_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_THREE_STRIKE_DIRECTION 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_THREE_NUMBER_OF_STRIKES 4 greater than 0 Number of strikes for leg one."},{"location":"strategies/options_bull_put_ladder/#additional-notes","title":"Additional Notes","text":""},{"location":"strategies/options_long_iron_butterfly/","title":"Options Long Iron Butterfly","text":""},{"location":"strategies/options_long_iron_butterfly/#options-long-iron-butterfly","title":"Options Long Iron Butterfly","text":"

This is a template for implementing the Options Long Iron Butterfly strategy in Python.

Links

"},{"location":"strategies/options_long_iron_butterfly/#long-iron-butterfly","title":"Long Iron Butterfly","text":""},{"location":"strategies/options_long_iron_butterfly/#strategy-parameters","title":"Strategy Parameters","text":"

The strategy accepts the following parameters:

Name Default Value Expected Value Description LEG_ONE_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_ONE_TRADING_SYMBOL_SUFFIX 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_ONE_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_ONE_NUMBER_OF_STRIKES 0 greater than 0 Number of strikes for leg one. LEG_TWO_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_TWO_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_TWO_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_TWO_NUMBER_OF_STRIKES 0 greater than 0 Number of strikes for leg one. LEG_THREE_TRANSACTION_TYPE 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_THREE_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_THREE_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_THREE_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one. LEG_FOUR_TRANSACTION_TYPE 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_FOUR_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_FOUR_STRIKE_DIRECTION 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_FOUR_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one."},{"location":"strategies/options_straddle/","title":"Options Straddle","text":""},{"location":"strategies/options_straddle/#options-straddle","title":"Options Straddle","text":"

This class represents the implementation of an options straddle trading strategy.

Links

Jupyter Notebook for Options from Indian Exchange (NSE)

"},{"location":"strategies/options_straddle/#straddle-options","title":"Straddle Options","text":""},{"location":"strategies/options_straddle/#parameters","title":"Parameters","text":"Name Default Value Expected Value Description _leg_one_transaction_type 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] _leg_one_tradingsymbol_suffix 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] _leg_one_strike_direction 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] _leg_one_number_of_strikes 0 greater than 0 Number of strikes for leg one. _leg_two_transaction_type 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] _leg_two_tradingsymbol_suffix 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] _leg_two_strike_direction 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] _leg_two_number_of_strikes 0 greater than 0 Number of strikes for leg one."},{"location":"strategies/options_strangle/","title":"Options Strangle","text":""},{"location":"strategies/options_strangle/#options-strangle","title":"Options Strangle","text":"

The StrategyOptionsStrangle class is a strategy template for trading options strangles. It is derived from the StrategyOptionsBaseV2 class.

Links

Jupyter Notebook for Options from Indian Exchange (NSE)

"},{"location":"strategies/options_strangle/#strangle-options","title":"Strangle Options","text":""},{"location":"strategies/options_strangle/#parameters","title":"Parameters","text":"

The following parameters can be set in the Parameters Configuration Pane:

Name Default Value Expected Value Description _leg_one_transaction_type 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] _leg_one_tradingsymbol_suffix 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] _leg_one_strike_direction 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] _leg_one_number_of_strikes 2 greater than 0 Number of strikes for leg one. _leg_two_transaction_type 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] _leg_two_tradingsymbol_suffix 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] _leg_two_strike_direction 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] _leg_two_number_of_strikes 2 greater than 0 Number of strikes for leg one."},{"location":"strategies/reverse_rsi/","title":"Reverse RSI","text":"

This is a trading strategy called \"Reverse RSI\" implemented in Python using the PyAlgoTrading library. The strategy is based on the relative strength index indicator.

Links

Jupyter Notebook for Indian Exchange (NSE)

Jupyter Notebook for US Exchange (NASDAQ)

"},{"location":"strategies/reverse_rsi/#relative-strength-index","title":"Relative Strength Index","text":"

RSI stands for Relative Strength Index, and it is a popular technical indicator used in the stock market to analyze the strength and momentum of a price trend. The RSI provides insights into whether a stock is overbought or oversold and can help identify potential trend reversals.

Here is a summary of RSI in the stock market:

Overall, the Relative Strength Index (RSI) is a widely used indicator in the stock market to assess the strength and momentum of price movements. It helps traders identify overbought and oversold conditions, as well as potential trend reversals, which can assist in making trading decisions.

Fig.1 - MCD candle chart (top) and RSI plot (bottom)"},{"location":"strategies/reverse_rsi/#strategy-overview","title":"Strategy Overview","text":"

The Reverse RSI strategy is a trading strategy based on the Relative Strength Index (RSI) indicator. It generates entry and exit signals based on the reverse crossover of the RSI values from specified overbought and oversold levels.

"},{"location":"strategies/reverse_rsi/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description TIME_PERIOD None greater than 0 Period (number of candles) by which RSI is calculated OVERBOUGHT_VALUE None greater than 0 RSI value above which stocks are considered over-bought OVERSOLD_VALUE None greater than 0 RSI value below which stocks are considered over-sold"},{"location":"strategies/reverse_rsi/#crossover-calculation","title":"Crossover Calculation","text":"

The get_crossover_value method calculates the crossover values for the RSI indicator using historical data of the instrument. It compares the RSI values with the overbought and oversold levels to determine the entry and exit actions. The method returns the crossover values for oversold and overbought levels.

"},{"location":"strategies/rsi_macd_crossover/","title":"RSI MACD Crossover","text":"

This is a trading strategy called \"RSI MACD Crossovers\" implemented in Python using the PyAlgoTrading library. The strategy is based on the RSI and MACD indicator crossover.

Links

Jupyter Notebook for Indian Exchange (NSE)

"},{"location":"strategies/rsi_macd_crossover/#rsi-and-macd-crossover","title":"RSI and MACD Crossover","text":"

In the dynamic world of stock trading, effective strategies are the key to success. The combination of two powerful technical indicators, the Moving Average Convergence Divergence (MACD) and the Relative Strength Index (RSI), can be a game-changer for traders. This strategy leverages MACD and RSI crossovers to identify potential entry and exit points in the stock market.

Here is a summary of RSI and MACD in the stock market: - The MACD is a trend-following momentum indicator. It consists of two lines: the MACD line and the Signal line. When the MACD line crosses above the Signal line, it generates a bullish signal, suggesting a potential uptrend. Conversely, a cross below the Signal line indicates a bearish signal, signaling a potential downtrend.

"},{"location":"strategies/rsi_macd_crossover/#strategy-overview","title":"Strategy Overview","text":"

The MACD and RSI crossover strategy is a robust approach that combines the strength of two widely used technical indicators. By identifying potential entry and exit points based on these crossovers, traders can make more informed decisions in the stock market.

"},{"location":"strategies/rsi_macd_crossover/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description TIMEPERIOD_FAST None greater than 0 Period (number of candles) by which EMA 2 is calculated TIMEPERIOD_SLOW None greater than 0 Period (number of candles) by which EMA 2 is calculated TIMEPERIOD_SIGNAL None greater than 0 Period (number of candles) by which moving average is calculated TIMEPERIOD_RSI None greater than 0 Period (number of candles) by which RSI is calculated OVERSOLD_VALUE None greater than 0 Threshould value indicating potential buying opportunites OVERBOUGHT_VALUE None greater than 0 Threshould value indicating potential selling opportunites"},{"location":"strategies/rsi_macd_crossover/#crossover-calculation","title":"Crossover Calculation","text":"

The get_crossover_value method calculates the crossover value based on the inverse crossover of the two EMAs of the closing prices. It uses the talib.MACD and talib.RSI function from the Talib library to calculate the MACD and RSI. The method then determines the crossover between the MACD and RSI and returns the corresponding value (-1, 0, or 1).

"},{"location":"strategies/stochastic_crossover/","title":"Stochastic Crossover","text":"

This is a trading strategy called \"Stochastic Crossover\" implemented in Python using the PyAlgoTrading library. The strategy is based on the Stochastic indicator crossover.

Links

Jupyter Notebook for Indian Exchange (NSE)

Jupyter Notebook for US Exchange (NASDAQ)

"},{"location":"strategies/stochastic_crossover/#stochastic-oscillator-indicator","title":"Stochastic Oscillator Indicator","text":"

In the stock market, Stochastic refers to the Stochastic Oscillator, which is a popular technical indicator used to analyze price momentum and identify potential trend reversals. The Stochastic Oscillator compares the closing price of a security to its price range over a specific period of time. It consists of two lines, %K and %D, and generates values between 0 and 100.

Here is a summary of the Stochastic Oscillator in the stock market:

Fig.1 - IBM candle chart (top) with Stochastic Fast (bottom) Fig.2 - QQQQ candle chart (top) with Stochastic Fast (bottom 1), Stochastic Slow (bottom 2) and Full Stochastic (bottom 3)"},{"location":"strategies/stochastic_crossover/#strategy-overview","title":"Strategy Overview","text":"

The strategy follows a simple rule based on the Stochastic indicator crossover. When the Stochastic indicator's %K line crosses above the %D line, a buy signal is generated. Conversely, when the %K line crosses below the %D line, a sell signal is generated. The strategy aims to capture potential trend reversals.

"},{"location":"strategies/stochastic_crossover/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description FASTK_PERIOD or PERIOD None greater than 0 The period for the fast %K line of the Stochastic indicator. SLOWK_PERIOD or SMOOTH_K_PERIOD None greater than 0 The period for the slow %K line of the Stochastic indicator. SLOWD_PERIOD or SMOOTH_D_PERIOD None greater than 0 The period for the slow %D line of the Stochastic indicator."},{"location":"strategies/stochastic_crossover/#crossover-calculation","title":"Crossover Calculation","text":"

The get_crossover_value method calculates the crossover values for the Slow-K and Slow-D of Stochastic indicator using historical data of the instrument. The method returns the crossover values between slow-K and slow-D.

"},{"location":"strategies/volatility_trend_atr/","title":"Volatility Trends with Average True Range (ATR)","text":"

This is a trading strategy called \"Volatility Trends ATR\" implemented in Python using the PyAlgoTrading library. The strategy is based on the ATR indicator crossover.

Links

Jupyter Notebook for Indian Exchange (NSE)

"},{"location":"strategies/volatility_trend_atr/#volatility-trends-with-average-true-range-atr-indicator","title":"Volatility Trends with Average True Range (ATR) Indicator","text":"

In the ever-changing realm of stock trading, market volatility can be both an opportunity and a challenge. Traders and investors require a reliable instrument to gauge price fluctuations and devise informed strategies. The Average True Range (ATR) steps in as a robust technical indicator to fulfill this role. ATR delivers valuable insights into market volatility trends, equipping traders with the necessary tools to make calculated decisions in the stock market.

Here is a summary of ATR in the stock market: - The Average True Range (ATR), is a technical gauge designed to quantify a security's trading range over a specific time frame. Rather than simply tracking daily price changes, ATR calculates the \"true range,\" accounting for gaps between trading sessions.

"},{"location":"strategies/volatility_trend_atr/#strategy-overview","title":"Strategy Overview","text":"

The Average True Range (ATR) steps in as a robust technical indicator to fulfill this role. ATR delivers valuable insights into market volatility trends, equipping traders with the necessary tools to make calculated decisions in the stock market.

"},{"location":"strategies/volatility_trend_atr/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description TIME_PERIOD None greater than 0 Period (number of candles) by which ATR is calculated ATR_PREV_CANDLES_NUM None greater than 0 nth Previous candle ATR"},{"location":"strategies/volatility_trend_atr/#decision-calculation","title":"Decision Calculation","text":"

The get_trend_direction method calculates the ATR values for the volatility trend atr indicator using historical data of the instrument. It uses the talib.AROON function from the Talib library to calculate the values. It compares the ATR values with the atr of previous specified candle and determine the entry and exit actions. The method returns the ATR values for current candle.

"},{"location":"strategies/vwap_crossover/","title":"VWAP Crossover","text":"

This is a trading strategy called \"VWAP Crossover\" implemented in Python using the PyAlgoTrading library. The strategy is based on the crossover of the VWAP (Volume Weighted Average Price) indicator.

Links

Jupyter Notebook for Indian Exchange (NSE)

Jupyter Notebook for US Exchange (NASDAQ)

"},{"location":"strategies/vwap_crossover/#vwap-indicator","title":"VWAP indicator","text":"

In the stock market, VWAP stands for Volume-Weighted Average Price. VWAP is a trading indicator that calculates the average price at which a particular stock or security has traded throughout the day, taking into account both the price and the volume of each trade.

Here is a summary of VWAP in the stock market:

Fig.1 - IBM candle chart (top) with VWAP line (Blue), Volume chart with SMA line"},{"location":"strategies/vwap_crossover/#strategy-overview","title":"Strategy Overview","text":"

The strategy follows a simple rule based on the crossover of the VWAP indicator. When the price crosses above the VWAP, a buy signal is generated, and when the price crosses below the VWAP, a sell signal is generated. The strategy aims to capture potential trend reversals based on the VWAP.

"},{"location":"strategies/vwap_crossover/#strategy-parameters","title":"Strategy Parameters","text":"

No specific strategy parameters are mentioned in the code.

"},{"location":"strategies/vwap_crossover/#crossover-calculation","title":"Crossover Calculation","text":"

The get_crossover_value method calculates the VWAP from historical data and the crossover values for the VWAP of the instrument. The method returns the crossover values between close of hist data and vwap.

"},{"location":"strategies/strategy_guides/common_options_strategy/","title":"Options Strategy Structure","text":"

Links

"},{"location":"strategies/strategy_guides/common_options_strategy/#1-initial-steps","title":"1. Initial steps","text":""},{"location":"strategies/strategy_guides/common_options_strategy/#naming-a-class","title":"Naming a Class","text":"eg: For the above strategy name the class name would be:
StrategyOptionsEMACrossover(StrategyOptionsBaseV2)\n

Coding Conventions

* Make a class with the same name as the file name\n* Make sure the first letter of each word is in uppercase and the initials should be in uppercase as well.\n* If the class name includes indicator names like EMA, SMA, and VWAP the name should be in uppercase in the class name but not in the file name.\n* Every options strategy is a child class of the StrategyOptionsBaseV2 class.\n
"},{"location":"strategies/strategy_guides/common_options_strategy/#naming-your-strategy","title":"Naming your Strategy","text":"

This name will be displayed in your My Coded Strategies in Python Build Web, and it will also be the strategy_name when you are fetching all strategies in pyalgotrading. Inside your strategy class, you can write your first parameter as name.

name = 'options_ema_crossover'\n

"},{"location":"strategies/strategy_guides/common_options_strategy/#2-init-method","title":"2. Init method","text":"

This method gets called only once when the strategy is started.

"},{"location":"strategies/strategy_guides/common_options_strategy/#strategy-info","title":"Strategy info","text":"

In the init method add the line given below

super().__init__(*args, **kwargs)\n

"},{"location":"strategies/strategy_guides/common_options_strategy/#parameter-creation","title":"Parameter creation","text":"

Next, we assign the parameter values to the class variables of the same name as the parameters but in the lowercase format as shown below:

eg:

self.fresh_order_candle = self.strategy_parameters['FRESH_ORDER_CANDLE']\nself.start_time_hours = self.strategy_parameters['START_TIME_HOURS']\nself.start_time_minutes = self.strategy_parameters['START_TIME_MINUTES']\nself.end_time_hours = self.strategy_parameters['END_TIME_HOURS']\nself.end_time_minutes = self.strategy_parameters['END_TIME_MINUTES']\nself.no_of_strikes_away_ce = self.strategy_parameters['NO_OF_STRIKES_AWAY_CE']\nself.no_of_strikes_away_p = self.strategy_parameters['NO_OF_STRIKES_AWAY_PE']\nself._strike_direction_ce = self.strategy_parameters['STRIKES_DIRECTION_CE']\nself._strike_direction_pe = self.strategy_parameters['STRIKES_DIRECTION_PE']\nself.ema_period_one = self.strategy_parameters['EMA_PERIOD_ONE']\nself.ema_period_two = self.strategy_parameters['EMA_PERIOD_TWO']\nself.target_percentage = self.strategy_parameters['TARGET_PERCENTAGE']\nself.stoploss_percentage = self.strategy_parameters['STOPLOSS_PERCENTAGE']\nself.stoploss_range = self.strategy_parameters['STOPLOSS_RANGE']\nself.stoploss_order_count_allowed = self.strategy_parameters['STOPLOSS_ORDER_COUNT_ALLOWED']\n

Note

"},{"location":"strategies/strategy_guides/common_options_strategy/#start-time-and-end-time-creation","title":"Start time and End time creation","text":"

Adding Start and End time is useful when you want to define a timerange between which the strategy will be running each day. Add the below code to calculate the strategy start time and end time, from the strategy_parameters.

try:

    self.candle_start_time = time(hour=self.start_time_hours, minute=self.start_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting start hours and minutes... EXITING')\n    raise SystemExit\n
try:
    self.candle_end_time = time(hour=self.end_time_hours, minute=self.end_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting end time hours and minutes... EXITING')\n    raise SystemExit\n

"},{"location":"strategies/strategy_guides/common_options_strategy/#strategy-variables","title":"Strategy variables","text":"

We create our own strategy variables other than the strategy parameter variables which will be used throughout the strategy.

eg:

self.main_order = None            # We save the entry order in this variable\nself.stoploss_order = None        # We save the corresponding stoploss exit order of the entry order in this variable\n
We initialize the variables with a None value. !!! Note There could be more strategy variables required as per the strategy requirement.

"},{"location":"strategies/strategy_guides/common_options_strategy/#3-initialize-method","title":"3. Initialize method","text":"

Unlike the init method, this method gets called every day at the beginning of the day once the strategy is started.

Here the strategy variables that were initialized as None are again defined as dictionaries/lists except for the self.order_tag_manager. Create a reference for OrderTagManager as shown below:

self.order_tag_manager = OrderTagManager\n
"},{"location":"strategies/strategy_guides/common_options_strategy/#4-ordertagmanager","title":"4. OrderTagManager","text":"

The self.order_tag_manager is used to store/remove the entry/exit orders. The self.order_tag_manager has the following methods:

"},{"location":"strategies/strategy_guides/common_options_strategy/#add_order","title":"add_order","text":"
self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
"},{"location":"strategies/strategy_guides/common_options_strategy/#get_orders","title":"get_orders","text":"

eg:

self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
"},{"location":"strategies/strategy_guides/common_options_strategy/#remove_tags","title":"remove_tags","text":"

eg:

self.order_tag_manager.remove_tags(tags=entry_key)\n

Here the entry_key tag is removed from the OrderTagManager.

Note

When the tag is removed the order objects stored in that tag are also removed but the same order objects would still be present in order tags.

"},{"location":"strategies/strategy_guides/common_options_strategy/#remove_order","title":"remove_order","text":"

eg:

self.order_tag_manager.remove_order(main_order)\n
Here the main_order order object is removed from the OrderTagManager.

Note

The order object will be removed from all the tags ta

"},{"location":"strategies/strategy_guides/common_options_strategy/#get_internals","title":"get_internals","text":"
Returns the values i.e. both the entry and exit orders stored inside the tags list.\n
"},{"location":"strategies/strategy_guides/common_options_strategy/#5-child-instruments-calculation","title":"5. Child instruments calculation","text":""},{"location":"strategies/strategy_guides/common_options_strategy/#get_ltp","title":"get_ltp","text":"

Fetch the ltp of the base instrument (instrument set while executing strategy)

ltp = self.broker.get_ltp(self.underlying_instrument)\n

"},{"location":"strategies/strategy_guides/common_options_strategy/#options_instruments_set_up_local","title":"options_instruments_set_up_local","text":"

Get the ATM ITM and OTM lists of the child instrument based on the LTP

self.options_instruments_set_up_local(self.underlying_instrument, tradingsymbol_suffix, ltp)\n

"},{"location":"strategies/strategy_guides/common_options_strategy/#get_child_instrument_details","title":"get_child_instrument_details","text":"

Select a child instrument from the lists of ATM, ITM, and OTM based on the strike direction and no of strikes given for the child instrument

child_instrument = self.get_child_instrument_details(self.underlying_instrument, tradingsymbol_suffix, strike_direction, no_of_strikes)\n

"},{"location":"strategies/strategy_guides/common_options_strategy/#6-entry-methods","title":"6. Entry Methods","text":""},{"location":"strategies/strategy_guides/common_options_strategy/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry","text":""},{"location":"strategies/strategy_guides/common_options_strategy/#strategy_enter_position","title":"strategy_enter_position","text":""},{"location":"strategies/strategy_guides/common_options_strategy/#7-exit-methods","title":"7. Exit Methods","text":""},{"location":"strategies/strategy_guides/common_options_strategy/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit","text":""},{"location":"strategies/strategy_guides/common_options_strategy/#strategy_exit_position","title":"strategy_exit_position","text":""},{"location":"strategies/strategy_guides/common_options_strategy/#8-other-common-methods","title":"8. Other common methods","text":"

There are other methods that are used in the strategy:

"},{"location":"strategies/strategy_guides/common_options_strategy/#check_and_place_stoploss_order","title":"check_and_place_stoploss_order","text":"

This method is called in the strategy_select_instruments_for_exit when our entry order is open, and we want to place a stoploss exit order for the same.

"},{"location":"strategies/strategy_guides/common_options_strategy/#set_all_none","title":"set_all_none","text":"

This method is called in the strategy_exit_position when our entry order has exited, and we want to remove the order object from the self.main_order variable.

"},{"location":"strategies/strategy_guides/common_options_strategy/#options_instruments_set_up_local_1","title":"options_instruments_set_up_local","text":"

This method is called in the strategy_select_instruments_for_entry to fetch the ATM, ITM, and OTM lists of the child instruments based on the LTP of the base instrument.

"},{"location":"strategies/strategy_guides/common_options_strategy/#get_child_instrument_details_1","title":"get_child_instrument_details","text":"

This method is called in the strategy_select_instruments_for_entry to fetch a single child instrument based on the no of strikes and strike direction.

"},{"location":"strategies/strategy_guides/common_options_strategy/#9-cleanup","title":"9. Cleanup","text":"
  1. Add comments and docstrings wherever possible to improve code readability.
  2. Once the strategy is completed you can optimize imports, give proper indentation and proper formatting to the strategy code and remove unwanted imports, variables, and methods before delivering the code.
"},{"location":"strategies/strategy_guides/common_options_strategy/#10-check-out-our-docs-for-developed-options-strategies","title":"10. Check out our docs for developed Options strategies","text":"

Tip

To know more about a strategy from our given template, simply check the first line of comment in the code of that specific strategy.

"},{"location":"strategies/strategy_guides/common_regular_strategy/","title":"Regular Strategy Structure","text":"

Links

"},{"location":"strategies/strategy_guides/common_regular_strategy/#1-initial-steps","title":"1. Initial steps","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#naming-a-class","title":"Naming a Class","text":"eg: For the above strategy name the class name would be:
StrategyFuturesEMACrossover(StrategyBase)\n

Coding Conventions

* Make a class with the same name as the file name\n* Make sure the first letter of each word is in uppercase and the initials should be in uppercase as well.\n* If the class name includes indicator names like EMA, SMA, and VWAP the name should be in uppercase in the class name but not in the file name.\n* Every strategy is a child class of the StrategyBase class.\n
"},{"location":"strategies/strategy_guides/common_regular_strategy/#naming-your-strategy","title":"Naming your Strategy","text":"

This name will be displayed in your My Coded Strategies in Python Build Web, and it will also be the strategy_name when you are fetching all strategies in pyalgotrading. Inside your strategy class, you can write your first parameter as name.

name = 'futures_ema_crossover'\n

"},{"location":"strategies/strategy_guides/common_regular_strategy/#2-init-method","title":"2. Init method","text":"

This method gets called only once when the strategy is started.

"},{"location":"strategies/strategy_guides/common_regular_strategy/#strategy-info","title":"Strategy info","text":"

In the init method add the line given below

super().__init__(*args, **kwargs)\n

"},{"location":"strategies/strategy_guides/common_regular_strategy/#parameter-creation","title":"Parameter creation","text":"

Next we assign the parameter values to the class variables of the same name as the parameters but in the lowercase format, as shown below:

eg:

self.fresh_order_candle = self.strategy_parameters['FRESH_ORDER_CANDLE']\nself.start_time_hours = self.strategy_parameters['START_TIME_HOURS']\nself.start_time_minutes = self.strategy_parameters['START_TIME_MINUTES']\nself.end_time_hours = self.strategy_parameters['END_TIME_HOURS']\nself.end_time_minutes = self.strategy_parameters['END_TIME_MINUTES']\nself.ema_period_one = self.strategy_parameters['EMA_PERIOD_ONE']\nself.ema_period_two = self.strategy_parameters['EMA_PERIOD_TWO']\nself.target_percentage = self.strategy_parameters['TARGET_PERCENTAGE']\nself.stoploss_percentage = self.strategy_parameters['STOPLOSS_PERCENTAGE']\nself.stoploss_range = self.strategy_parameters['STOPLOSS_RANGE']\nself.stoploss_order_count_allowed = self.strategy_parameters['STOPLOSS_ORDER_COUNT_ALLOWED']\n

Note

"},{"location":"strategies/strategy_guides/common_regular_strategy/#start-time-and-end-time-creation","title":"Start time and End time creation","text":"

Adding Start and End time is useful when you want to define a timerange between which the strategy will be running each day. Add the below code to calculate the strategy start time and end time, from the strategy_parameters. try:

    self.candle_start_time = time(hour=self.start_time_hours, minute=self.start_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting start hours and minutes... EXITING')\n    raise SystemExit\n
try:
    self.candle_end_time = time(hour=self.end_time_hours, minute=self.end_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting end time hours and minutes... EXITING')\n    raise SystemExit\n

"},{"location":"strategies/strategy_guides/common_regular_strategy/#strategy-variables","title":"Strategy variables","text":"

We create our own strategy variables other than the strategy parameter variables which will be used throughout the strategy.

eg: self.order_tag_manager = None

We initialize the variables with a None value.

Note

There could be more strategy variables required as per the strategy requirement.\n
"},{"location":"strategies/strategy_guides/common_regular_strategy/#3-initialize-method","title":"3. Initialize method","text":"

Unlike the init method, this method gets called every day at the beginning of the day once the strategy is started.

Here the strategy variables that were initialized as None are again defined as dictionaries/lists except for the self.order_tag_manager. Create a reference for OrderTagManager as shown below:

self.order_tag_manager = OrderTagManager\n
"},{"location":"strategies/strategy_guides/common_regular_strategy/#4-ordertagmanager","title":"4. OrderTagManager","text":"

The self.order_tag_manager is used to store/remove the entry/exit orders. The self.order_tag_manager has the following methods:

"},{"location":"strategies/strategy_guides/common_regular_strategy/#add_order","title":"add_order","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#get_orders","title":"get_orders","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#remove_tags","title":"remove_tags","text":"

Note

When the tag is removed the order objects stored in that tag are also removed but the same order objects would still be present in the order tags.

"},{"location":"strategies/strategy_guides/common_regular_strategy/#remove_order","title":"remove_order","text":"
self.order_tag_manager.remove_order(main_order)\n

Here the main_order order object is removed from the OrderTagManager.

Note

The order object will be removed from all the tags ta

"},{"location":"strategies/strategy_guides/common_regular_strategy/#get_internals","title":"get_internals","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#5-entry-methods","title":"5. Entry Methods","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#strategy_enter_position","title":"strategy_enter_position","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#6-exit-methods","title":"6. Exit Methods","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit:","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#strategy_exit_position","title":"strategy_exit_position","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#7-other-common-methods","title":"7. Other common methods","text":"

There are other methods that are used in the strategy:

"},{"location":"strategies/strategy_guides/common_regular_strategy/#check_and_place_stoploss_order","title":"check_and_place_stoploss_order","text":"

This method is called in the strategy_select_instruments_for_exit when our entry order is open, and we want to place a stoploss exit order for the same.

"},{"location":"strategies/strategy_guides/common_regular_strategy/#set_all_none","title":"set_all_none","text":"

This method is called in the strategy_exit_position when our entry order has exited, and we want to remove the order object from the self.main_order variable.

"},{"location":"strategies/strategy_guides/common_regular_strategy/#8-cleanup","title":"8. Cleanup","text":"
  1. Add comments and docstrings wherever possible to improve code readability.
  2. Once the strategy is completed you can optimize imports, give proper indentation and proper formatting to the strategy code and remove unwanted imports, variables, and methods before delivering the code.
"},{"location":"strategies/strategy_guides/common_regular_strategy/#10-check-out-our-docs-for-developed-regular-strategies","title":"10. Check out our docs for developed Regular strategies","text":"

Tip

To know more about a strategy from our given template, simply check the first line of comment in the code of that specific strategy.

"},{"location":"strategies/strategy_guides/common_strategy_guide/","title":"Common Strategy Building Guide","text":""},{"location":"strategies/strategy_guides/common_strategy_guide/#understanding-the-strategy-structure","title":"Understanding the Strategy Structure","text":"

The strategy code is basically a Python Class, with its Base Class as StrategyBase (for regular strategies) or StrategyBaseOptionsV2 (for options strategies). In this documentation we will focus on a regular strategy called \u2018EMA Regular Order\u2019 - a strategy which gives BUY and SELL signals based on two EMA indicators and takes new-entry & previous-exit at every crossover. We also will be discussing about an options strategy called \"Options Bear Call Ladder Strategy\" - strategy which uses 3 legs to optimize the risk and returns of the options. Inside the strategy class there are many methods that could be divided into 2 different sections: Mandatory Methods: Initialization Methods, 4-Core Loop Methods & Optional Methods: Algorithmic Calculation Methods & Miscellaneous Methods. These sections are explained briefly below.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#mandatory-functions","title":"Mandatory Functions:","text":""},{"location":"strategies/strategy_guides/common_strategy_guide/#initialization-methods","title":"Initialization Methods","text":"

In this section, you will have the Strategy Class\u2019 \u201cinit\u201d method (a.k.a. Constructor). This method will extract the Strategy\u2019s Configured Parameters and save them in the different variables. There is another method in this section called \u201cinitialization\u201d, which will be called at the start of every trading day that will occur inside the timeline for which you are executing the strategy.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#4-core-loop-methods","title":"4 Core Loop Methods","text":"

These are the main methods that will be called by the AlgoBulls Core in a sequence for every candle (candle is the minimum time range for which the Open, High, Low and Close values of that instrument are available. Basically it is a representation of a time period and the data corresponds to the trades executed during that period). All the logic design methods are called inside these Core Methods, along with the helping methods.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#optional-function","title":"Optional Function","text":""},{"location":"strategies/strategy_guides/common_strategy_guide/#algorithmic-calculations-methods","title":"Algorithmic Calculations Methods","text":"

This section contains the methods that are defined by the user. These are not mandatory but good to keep your code organized and simple. Their main purpose will be to perform operations on historical data or LTP data of the selected instrument. Based on the results of these operations, it needs to decide whether it should Buy, Sell or take no action on the instrument. Apart from decision making, some of the other methods can also be useful to calculate the stop loss or target price for a trade. Point being, the purpose of these methods are totally dependent on the application of the user.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#miscellaneous-methods","title":"Miscellaneous Methods","text":"

These are handy methods that are created by a team of expert strategy developers and they are already a part of the base class. These methods do a lot of heavy lifting under the hood and can be used here for various purposes like getting the latest price of a stock, placing an order etc. These methods are not always necessary to be used and are generally a part of other methods mentioned above.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#working-flow-of-the-strategy","title":"Working Flow of the Strategy","text":"

Below Diagram is Sample Diagram on how the strategy execution engine works. Blocks in green are the mandatory methods that need to be implemented for every strategy.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#setting-up-imports-and-environment","title":"Setting Up: Imports and Environment","text":"

Before we dive into building of a strategy we need to fist setup our workspace depending the tool we are using. The available tools for creating a workspace of strategy are Pyalgotrading and Python Build Web.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#pyalgotrading","title":"Pyalgotrading","text":"

If you're coding on your local machine, I recommend setting up a virtual environment and installing the \"pyalgotrading\" Python package to keep things organised.

pip3 install pyalgotrading\n
Once you've got it installed, it's time to bring in the magic. Import the package and its constants into your Python file where your trading strategy will take shape.

from pyalgotrading.algobulls import AlgoBullsConnection\nfrom pyalgotrading.strategy import *\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#python-build-web","title":"Python Build Web","text":"

Now, if you prefer a web-based approach, we've got you covered. Head over to the \"Code New Strategy\" section on the Python Build page of the AlgoBulls website. Here, you can craft your strategy without the need to import any classes or packages. The choice is yours \u2013 flexibility at its best.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#strategy-code-creation-lets-get-started","title":"Strategy Code Creation: Let's Get Started","text":"

With the groundwork laid, it's time to create your strategy class. Be sure to choose the appropriate base class for your strategy. For regular equity strategies, the base class is StrategyBase while for options strategies, it's StrategyOptionsBaseV2.

Examples:

RegularOptions
class MovingAverageCrossoverV2(StrategyBase):\n    name = 'Moving Average Crossover V2'\n
class StrategyOptionsBearCallLadder(StrategyOptionsBaseV2):\n    name = 'Options Bear Call Ladder Template'\n

Feel free to get creative with your class name, but it's good practice to make it unique among your strategy class names. Below this declaration, we set the strategy's name.

For Pyalgotrading users

If you are uploading the strategy via pyalgotrading functions, then this name parameter's value will be the name of the strategy. That means this name will be displayed in My Coded Strategies section in Python Build.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#initialization-functions","title":"Initialization Functions","text":""},{"location":"strategies/strategy_guides/common_strategy_guide/#init","title":"init()","text":"

Every great trading strategy starts with a solid foundation \u2013 the constructor method, also known as the \"init\" method. Here's what it looks like:

def __init__(self, *args, **kwargs):\n    super().__init__(*args, **kwargs)\n
Within this method, you extract the parameters provided by the user. These user-defined parameters are stored in a dictionary called \"self.strategy_parameters.\" Here's how you can access these values:

self.timeperiod1 = self.strategy_parameters['TIMEPERIOD1']\nself.timeperiod2 = self.strategy_parameters['TIMEPERIOD2']\n
Feel free to initialise other variables here, such as self.main_order, self.number_of_allowed_expiry_dates, self.transaction_type_map and more.

Example: This is how the declaration of class along with its constructor would look like.

RegularOptions
class StrategyEMARegularOrder(StrategyBase):\n    name = 'EMA Regular Order Strategy'\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n        self.timeperiod1 = self.strategy_parameters['TIMEPERIOD1']\n        self.timeperiod2 = self.strategy_parameters['TIMEPERIOD2']\n\n        self.main_order_map = None\n
class StrategyOptionsBearCallLadder(StrategyOptionsBaseV2):\n    name = 'Options Bear Call Ladder Template'\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n        # Parameters (currently set with default values, can be overridden from the Parameters Configuration Pane)\n        self._leg_one_transaction_type = self.strategy_parameters.get('LEG_ONE_TRANSACTION_TYPE', 1)  # BUY: 1 | SELL: 2\n        self._leg_one_tradingsymbol_suffix = self.strategy_parameters.get('LEG_ONE_TRADING_SYMBOL_SUFFIX', 1)  # CE: 1 | PE: 2\n        self._leg_one_strike_direction = self.strategy_parameters.get('LEG_ONE_STRIKE_DIRECTION', 1)  # ITM: 0| ATM: 1| OTM: 2\n        self._leg_one_number_of_strikes = self.strategy_parameters.get('LEG_ONE_NUMBER_OF_STRIKES', 0)\n\n        self._leg_two_transaction_type = self.strategy_parameters.get('LEG_TWO_TRANSACTION_TYPE', 1)  # BUY: 1 | SELL: 2\n        self._leg_two_tradingsymbol_suffix = self.strategy_parameters.get('LEG_TWO_TRADING_SYMBOL_SUFFIX', 1)  # CE: 1 | PE: 2\n        self._leg_two_strike_direction = self.strategy_parameters.get('LEG_TWO_STRIKE_DIRECTION', 2)  # ITM: 0| ATM: 1| OTM: 2\n        self._leg_two_number_of_strikes = self.strategy_parameters.get('LEG_TWO_NUMBER_OF_STRIKES', 2)\n\n        self._leg_three_transaction_type = self.strategy_parameters.get('LEG_THREE_TRANSACTION_TYPE', 2)  # BUY: 1 | SELL: 2\n        self._leg_three_tradingsymbol_suffix = self.strategy_parameters.get('LEG_THREE_TRADING_SYMBOL_SUFFIX', 1)  # CE: 1 | PE: 2\n        self._leg_three_strike_direction = self.strategy_parameters.get('LEG_THREE_STRIKE_DIRECTION', 0)  # ITM: 0| ATM: 1| OTM: 2\n        self._leg_three_number_of_strikes = self.strategy_parameters.get('LEG_THREE_NUMBER_OF_STRIKES', 2)\n\n        # Maps\n        self.transaction_type_map = {1: \"BUY\", 2: \"SELL\"}\n        self.tradingsymbol_suffix_map = {1: \"CE\", 2: \"PE\"}\n        self.strike_direction_map = {0: OptionsStrikeDirection.ITM, 1: OptionsStrikeDirection.ATM, 2: OptionsStrikeDirection.OTM}\n\n        # Variables\n        self.number_of_allowed_expiry_dates = 1\n        self.instruments_done_for_the_day = None\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#initialize","title":"initialize()","text":"

The \"initialize\" method is your strategy's workspace, where you get everything ready for a fresh trading day. It's called at the start of each trading day, allowing you to reset variables, set up your tools, and perform any other tasks to ensure your strategy is primed and ready.

Example:

Examples:

RegularOptions
def initialize(self):\n    self.main_order_map = {}\n
def initialize(self):\n    super().initialize()\n    self.instruments_done_for_the_day = []\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#algorithmic-calculation-functions","title":"Algorithmic Calculation Functions","text":""},{"location":"strategies/strategy_guides/common_strategy_guide/#get_decision","title":"get_decision()","text":"

Now, let's dive into the heart of your strategy \u2013 the \"get_decision\" method. This method is where the magic happens, where you decide when to enter or exit a trade, set stop losses, and target prices. Here's how it works: Historical data of the instrument up to a certain point in your strategy is collected using:

By combining these calculated values with historical data, you can make informed decisions about when to initiate or close a trade. Additionally, you can use this information to compute potential target prices or set stop losses. AlgoBulls' Python Build empowers you to navigate the complexities of options trading with ease.

Example:

This is how an ideal get_decision() function would look like. This example is from RSI Crossover Strategy.

def get_crossover_value(self, instrument):\n    hist_data = self.get_historical_data(instrument)\n\n    rsi_value = talib.RSI(hist_data['close'],    timeperiod=self.time_period)\n\n    oversold_list = [self.oversold_value] * rsi_value.size\n    overbought_list = [self.overbought_value] * rsi_value.size\n\n    oversold_crossover_value = self.utils.crossover(rsi_value, oversold_list)\n    overbought_crossover_value = self.utils.crossover(rsi_value, overbought_list)\n\n    return oversold_crossover_value, overbought_crossover_value\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#miscellaneous-functions","title":"Miscellaneous Functions","text":""},{"location":"strategies/strategy_guides/common_strategy_guide/#get_child_instrument_details","title":"get_child_instrument_details()","text":"

The get_child_instrument_details function is at your disposal. It takes several parameters:

This function calls two other functions: self.get_allowed_expiry_dates() and get_options_instrument_with_strike_direction().

Example: This is how the function looks ideally. This example was taken from \u201cOptions Bear Call Strategy\u201d from ready templates.

    def get_child_instrument_details(self, base_instrument, tradingsymbol_suffix, strike_direction, no_of_strikes):\n        expiry_date = self.get_allowed_expiry_dates()[0]\n        child_instrument = self.get_options_instrument_with_strike_direction(base_instrument, expiry_date, tradingsymbol_suffix, strike_direction, no_of_strikes)\n        return child_instrument\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#get_allowed_expiry_dates","title":"get_allowed_expiry_dates()","text":"

In options strategies, the get_allowed_expiry_dates function plays a vital role. It doesn't require parameters; instead, it relies on the number_of_allowed_expiry_dates variable defined in the constructor method.

In essence, this function helps you select the appropriate expiry date based on the value you assign to number_of_allowed_expiry_dates variable.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#get_options_instrument_with_strike_direction","title":"get_options_instrument_with_strike_direction()","text":"

This function is a key player in options strategies, taking parameters such as:

"},{"location":"strategies/strategy_guides/common_strategy_guide/#options_instruments_set_up_local","title":"options_instruments_set_up_local()","text":"

Now, let's talk about a crucial piece of the options strategy puzzle \u2013 options_instruments_set_up_local. This function creates local instances of all available child instruments based on specified parameters:

Once executed, this function sets up and stores local instances of child instruments matching your criteria. These instances become valuable assets for further analysis or operations, including utilising the \"get_child_instrument_details\" function.

Example: This is how this function looks ideally. This example was taken from \u201cOptions Bear Call Ladder\u201d from ready templates.

def options_instruments_set_up_local(self, base_instrument, tradingsymbol_suffix, current_close, direction=OptionsInstrumentDirection.EXACT):\n        expiry_dates = self.get_allowed_expiry_dates()\n        for expiry_date in expiry_dates:\n            self.options_instruments_set_up(base_instrument, direction, expiry_date, tradingsymbol_suffix, current_close)\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#options_instruments_set_up","title":"options_instruments_set_up()","text":"

The final piece of the puzzle is \"options_instruments_set_up.\" This function takes parameters like:

Now, let's talk about the engine that drives your strategy \u2013 the core loop functions.

These include \"strategy_select_instruments_for_entry\", \"strategy_enter_position\", \"strategy_select_instruments_for_exit\" and \"strategy_exit_position\" These functions are called within a loop from the AlgoBulls core until an Exit Event for the strategy occurs.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#the-4-core-loop-functions","title":"The 4 Core Loop Functions","text":""},{"location":"strategies/strategy_guides/common_strategy_guide/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry()","text":"

This function takes parameters:

Example: This function would ideally look like this. This example was taken from \u201cOptions Straddle\u201d from Ready Templates.

Examples:

RegularOptions
def strategy_select_instruments_for_entry(self, candle, instruments_bucket):\n    selected_instruments, meta = [], []\n\n    for instrument in instruments_bucket:\n        crossover = self.get_decision(instrument)\n        action_constants = {1: 'BUY', -1: 'SELL'}\n\n        if crossover in [-1, 1]:\n            selected_instruments.append(instrument)\n            meta.append({'action': action_constants[crossover]})\n\n    return selected_instruments, meta\n
def strategy_select_instruments_for_entry(self, candle, instruments_bucket):\n    selected_instruments, meta = [], []\n\n    for instrument in instruments_bucket:\n        if instrument not in self.instruments_done_for_the_day:\n            self.instruments_done_for_the_day.append(instrument)\n            ltp = self.broker.get_ltp(instrument)\n\n            self.options_instruments_set_up_local(instrument, \"CE\", ltp)\n            self.options_instruments_set_up_local(instrument, \"PE\", ltp)\n\n            leg_wise_list = [('LEG_ONE', self._leg_one_tradingsymbol_suffix, self._leg_one_strike_direction, self._leg_one_number_of_strikes, self._leg_one_transaction_type),\n                             ('LEG_TWO', self._leg_two_tradingsymbol_suffix, self._leg_two_strike_direction, self._leg_two_number_of_strikes, self._leg_two_transaction_type),\n                             ('LEG_THREE', self._leg_three_tradingsymbol_suffix, self._leg_three_strike_direction, self._leg_three_number_of_strikes, self._leg_three_transaction_type)]\n\n            for leg_number, tradingingsymbol_suffix, strike_direction, number_of_strikes, transaction_type in leg_wise_list:\n                self.logger.info(f'Processing {leg_number}...')\n                child_instrument = self.get_child_instrument_details(instrument, self.tradingsymbol_suffix_map[tradingingsymbol_suffix], self.strike_direction_map[strike_direction], number_of_strikes)\n                selected_instruments.append(child_instrument)\n                meta.append({'base_instrument': instrument, 'action': self.transaction_type_map[transaction_type]})\n\n    return selected_instruments, meta\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#strategy_enter_position","title":"strategy_enter_position()","text":"

This function takes parameters:

Here, you place orders for the selected instruments, updating them in \"self.main_order\" for easy access in exit functions.

Example: This function would ideally look like this. This example was taken from \u201cOptions Straddle\u201d from Ready Templates.

Examples:

RegularOptions
def strategy_enter_position(self, candle, instrument, meta):\n    self.main_order_map[instrument] = _ = self.broker.OrderRegular(instrument, meta['action'], quantity=self.number_of_lots * instrument.lot_size)\n    return _\n
def strategy_enter_position(self, candle, instrument, sideband_info):\n    _ = self.broker.OrderRegular(instrument, sideband_info['action'], quantity=self.number_of_lots * instrument.lot_size)\n    return _\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit()","text":"

Similar to entry, this function takes parameters:

The function iterates through the instrument bucket, checking if the instrument is present in \"self.main_order\" and whether its exit condition is satisfied. Instruments meeting exit conditions are added to the selected instruments list, along with their respective actions and meta-information.

Example: This function should ideally look like this. This example was taken from \u201cEMA Crossover Strategy\u201d.

    def strategy_select_instruments_for_exit(self, candle, instruments_bucket):\n        selected_instruments, meta = [], []\n\n        for instrument in instruments_bucket:\n            if self.main_order_map.get(instrument) is not None:\n                crossover = self.get_decision(instrument)\n\n                if crossover in [1, -1]:\n                    selected_instruments.append(instrument)\n                    meta.append({'action': 'EXIT'})\n\n        return selected_instruments, meta\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#strategy_exit_position","title":"strategy_exit_position()","text":"

Finally, this function takes parameters:

Here, you place orders for the selected instruments, removing them from \"self.main_order\" to prepare for the next iteration of the AlgoBulls core loop.

Example: This function should ideally look like this. This example was taken from \u201cEMA Crossover Strategy\u201d.

    def strategy_exit_position(self, candle, instrument, meta):\n    if meta['action'] == 'EXIT':\n        self.main_order_map[instrument].exit_position()\n        self.main_order_map[instrument] = None\n        return True\n    return False\n
"},{"location":"strategies/strategy_guides/structure/","title":"Code Structure of Strategy","text":"

Coding Prerequisites

"},{"location":"strategies/strategy_guides/structure/#methods","title":"Methods","text":""},{"location":"strategies/strategy_guides/structure/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry()","text":"

This function helps you choose which trading instruments you want your strategy to work with. The system will use this function to go through each instrument one by one, at each candle's time. You get to write code that decides whether to place an order for a specific instrument or not.

"},{"location":"strategies/strategy_guides/structure/#strategy_enter_position","title":"strategy_enter_position()","text":"

This function is where you can place orders for the instruments you selected earlier. It's executed for each instrument you picked in the previous function.

"},{"location":"strategies/strategy_guides/structure/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit()","text":"

After you've entered a position for an instrument, this function is called for each of those instruments at each candle interval. You can use it to decide whether an instrument should be exited from the position.

"},{"location":"strategies/strategy_guides/structure/#strategy_exit_position","title":"strategy_exit_position()","text":"

In this function, you can close or exit positions for the instruments you marked for exiting in the previous function. It's done instrument by instrument.

"},{"location":"strategies/strategy_guides/structure/#supporting-methods","title":"Supporting Methods","text":"

You have the following supporting methods:

"},{"location":"strategies/strategy_guides/structure/#init","title":"init()","text":"

This method is like a starter for your strategy. It checks if the values you give it make sense and sets up some useful information for your strategy to use.

"},{"location":"strategies/strategy_guides/structure/#initialize","title":"initialize()","text":"

This method is called when your strategy begins, both at the very start and at the beginning of each trading day. It's like setting up your strategy's workspace and giving your tools a starting position.

"},{"location":"strategies/strategy_guides/structure/#name","title":"name()","text":"

This method gives your strategy a special name. It's like giving your strategy a unique nickname.

"},{"location":"strategies/strategy_guides/structure/#versions_supported","title":"versions_supported()","text":"

This method lets you specify which version of the AlgoBulls Platform your strategy works well with. It's like saying, \"My strategy is ready for this specific version of the platform.\"

"},{"location":"strategies/strategy_guides/structure/#utility-functions","title":"Utility Functions","text":"

You have the following utility function to be used in this strategy :

Links

"},{"location":"strategies/strategy_guides/structure/#get_crossover_value","title":"get_crossover_value()","text":"This handy function calculates something called the \"crossover value\" for you. It's like having a calculator that figures out this specific value for your strategy."},{"location":"strategies/strategy_guides/structure/#flowchart","title":"Flowchart","text":"

Once you create your own strategy or use a ready strategy from the pyalgostrategypool package, this is how it works internally on the AlgoBulls Core Trading Engine.

"},{"location":"support/support_pyalgo/","title":"Strategy Support - pyalgotrading","text":"

In this dedicated section, you'll find everything you need to receive the support you deserve for pyalgotrading. Whether it's troubleshooting an issue or seeking clarification, we've got you covered every step of the way. Requesting Support from pyalgotrading Module:

If you're looking to raise a support request from pyalgotrading module, follow these simple steps: - Start by executing your strategy from the pyalgotrading module. - Next, navigate to the \"My Coded Strategies\" section in python build web.

My Coded Strategies: This section displays all the strategies you've created or modified. It includes both new and updated strategies.

From this section, select the strategy you're experiencing issues with.

Need Support: If you require assistance with a specific strategy, you can raise a support request from here. Please ensure that your strategy is present in the My Coded Strategies section.

After clicking on Need Support, you'll see a popup window. Here, select the strategy for which you need assistance and explain you issue in brief.

Then, click the Submit button. Our support team will actively assist you with any issues you're facing.

"},{"location":"support/support_pybuild/","title":"Strategy Support - Python Build Web","text":"

Welcome to the realm of unparalleled support at AlgoBulls, where your algorithmic trading journey takes centre stage. Whether you're navigating the Python Build Web or harnessing the power of pyalgotrading, our commitment to your success remains unwavering. The Python Build Support page is your gateway to a world where every query, every challenge is met with expertise and dedication. We understand that your experience matters, and so does every line of code you craft.

"},{"location":"support/support_pybuild/#steps-to-get-the-support-you-need","title":"Steps to get the support you need.","text":""},{"location":"support/support_pybuild/#choose-your-strategy","title":"Choose your strategy","text":""},{"location":"support/support_pybuild/#need-support","title":"Need Support","text":""}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Python Build","text":""},{"location":"#algobulls","title":"AlgoBulls","text":"

Welcome to AlgoBulls, the AI-powered trading platform that unlocks new dimensions in algorithmic trading. Our mission is to boost your expertise in designing and executing personalised trading strategies using our cutting-edge product - Python Build.

"},{"location":"#introducing-python-build-your-gateway-to-algorithmic-trading","title":"Introducing Python Build: Your Gateway to Algorithmic Trading","text":"

Python Build is your ultimate companion for crafting and executing trading strategies with the precision of a seasoned professional. Designed for both experienced traders and newcomers, this platform offers a range of powerful tools that empower you to make well-informed decisions and trade confidently in dynamic financial markets.

When it comes to strategy development, Python Build lets you dive into coding, backtesting, and deploying your trading strategies with remarkable ease. With an intuitive interface, you gain the ability to precisely set entry and exit points, handle multiple instruments, and take actions based on informed insights.

What sets Python Build apart is its adaptable strategy format, suitable for various trading styles. Whether you're into backtesting, paper trading, or live trading, the same strategy code works for all three, making the experience straightforward.

The library covers all scenarios (backtesting, paper trading, and live trading) during strategy execution or generating analytics. This unified approach ensures seamless transitions between these modes, eliminating the need for complex adjustments. Additionally, it simplifies the creation of progress logs, helping you track your journey and anticipate completion times. For real-time updates, live logs are available too, offering transparency and control over your trading endeavours.

Python Build's strength lies in its seamless integration with real-time market data sources, historical data, and trading platforms. Its adaptable nature enables connection with various data providers and broker APIs, ensuring access to the information you need for well-informed trading decisions.

"},{"location":"#powerful-stats-visual-analytics","title":"Powerful Stats & Visual Analytics","text":"

In the pursuit of successful trading, Python Build equips you with advanced visual tools for strategy analytics. These tools provide a deeper understanding of your strategies' performance, helping you manage risks and fine-tune your plans for optimal success. Visualisations facilitate data-driven decision-making, giving you clearer insights into the intricacies of your trading activities.

"},{"location":"#multiple-platforms-to-use-python-build","title":"Multiple Platforms to use Python Build","text":"

To support our diverse community of users, we have the options of two dynamic platforms for our users to use Python Build - pyalgotrading and Python Build Web

Explore our Python Package: Pyalgotrading

Dive into the amazing Features of our Web-App: Python Build Web

"},{"location":"#join-the-community","title":"Join the Community","text":"

AlgoBulls is more than just a platform; it's a community. Connect, learn, and collaborate with traders and developers. Code your strategies or explore ours \u2013 AlgoBulls is where innovation meets trading expertise.

By becoming part of the Python Build community, you tap into a rich network of traders and developers. This community serves as a platform for collaboration, offering guidance, valuable insights, and collective refinement of trading strategies. Diverse perspectives help you approach trading challenges from multiple angles, fostering growth and improvement.

Join us in this journey as AlgoBulls revolutionizes algorithmic trading!

In essence, Python Build is more than a product; it's your comprehensive guide to mastering algorithmic trading. With its user-friendly interface, diverse functionalities, and seamless integration, it's a valuable asset for traders of all levels. By simplifying strategy crafting, integration, execution, and analysis, Python Build empowers you to navigate the trading world with confidence and precision.

"},{"location":"#open-source-strategy-library","title":"Open Source Strategy Library","text":"

We maintain an open source GitHub repository, pyalgostrategypool containing fully functional algorithmic trading strategies. These strategies can be used for Backtesting, Paper Trading, or Live Trading across various brokers and exchanges. The same code works in all trading modes.

Keep an eye on our GitHub repo

Our team periodically updates the library to add more strategy Python codes

For those new to algorithmic trading or Python Build, exploring included example strategies is an excellent starting point. These strategies are pre-built scenarios showcasing different trading strategies and concepts. By studying and experimenting with these examples, you'll gain a deeper grasp of how Python Build operates and how strategies are constructed.

Here's what you can do with the example strategies:

Remember, these example strategies lay the foundation for your learning journey. As you grow more familiar with the library, you can create and customise your own strategies based on your insights and preferences.

To conclude, the installation process readies you to use Python Build, while the documentation and example strategies empower you to explore the library's capabilities and apply them to real trading situations. Whether you're a beginner or a seasoned trader...

"},{"location":"#limitations-of-python-build","title":"Limitations of Python Build","text":"

In the exciting world of algorithmic trading, Python Build offers numerous benefits and considerations for traders and developers. Let's also acknowledge its limitations to help you make an informed decision.

  1. Python Speed Limitations: While versatile, Python isn't the fastest language for computation. This may pose challenges for complex strategies requiring extensive calculations. Our team is actively transitioning a major part of the codebase to Cython to enhance speed while retaining Python's simplicity. We're also exploring options like GPUs for the future.

  2. Cloud Cold-Start Speed Limitations: Each strategy runs on a dedicated virtual server in the cloud. While this ensures secure execution with dedicated resources, there's a short delay as the cloud fetches the resource before strategy execution begins. This minor delay is part of our ongoing optimization efforts.

Note

Our team is working round the clock to make these limitations a thing of the past.

"},{"location":"#references","title":"References","text":"

To unleash Python Build's full potential, dive into its comprehensive documentation. This roadmap offers detailed insights into the product's features, functionalities, and capabilities. It's your go-to resource for harnessing the power of Python Build effectively. The documentation includes:

"},{"location":"analytics/pyalgotrading_analytics/","title":"Pyalgotrading Analytics","text":""},{"location":"analytics/pyalgotrading_analytics/#metric-values-and-statistics","title":"Metric Values and Statistics","text":""},{"location":"analytics/pyalgotrading_analytics/#cumulative-returns","title":"Cumulative Returns","text":""},{"location":"analytics/pyalgotrading_analytics/#end-of-year-returns-eoy","title":"End of Year Returns (EoY)","text":""},{"location":"analytics/pyalgotrading_analytics/#distributions-of-monthly-returns-histogram","title":"Distributions of Monthly Returns (Histogram)","text":""},{"location":"analytics/pyalgotrading_analytics/#daily-returns","title":"Daily Returns","text":""},{"location":"analytics/pyalgotrading_analytics/#rolling-volatility-6-months","title":"Rolling Volatility (6 months)","text":""},{"location":"analytics/pyalgotrading_analytics/#rolling-sharpe-6-months","title":"Rolling Sharpe (6 months)","text":""},{"location":"analytics/pyalgotrading_analytics/#rolling-sortino-6-months","title":"Rolling Sortino (6 months)","text":""},{"location":"analytics/pyalgotrading_analytics/#worst-5-drawdown-periods","title":"Worst 5 Drawdown Periods","text":""},{"location":"analytics/pyalgotrading_analytics/#underwater-plot","title":"Underwater Plot","text":""},{"location":"analytics/pyalgotrading_analytics/#monthly-returns-heatmap","title":"Monthly Returns (Heatmap)","text":""},{"location":"analytics/python-build-view-results/","title":"Python build view results","text":""},{"location":"analytics/python-build-view-results/#how-to-view-the-results","title":"How to view the Results?","text":"

Once you start the strategy, it may take a while for it to complete the execution. You can switch to the Analytics tab after you run your strategy. Even if the strategy execution is not complete, you will still see intermediate results.

Analytics: In the analytics section, you can view a strategy\u2019s Stats & various other metrics in the form of graphs like P&L.

"},{"location":"analytics/python-build-view-results/#stats","title":"Stats","text":"

In this section you can see the total returns, sharpe ratio, sortino ratio, volatility, Max Drawdown, Total wins or Loses, Total short or long trades, hit ratio, number of trades, average trades per day, max profit, max loss, average profit per winning trade, average loss per losing trade.

"},{"location":"analytics/python-build-view-results/#cumulative-returns","title":"Cumulative Returns","text":""},{"location":"analytics/python-build-view-results/#profit-loss-currency-or","title":"Profit & Loss (Currency or %)","text":"

The trade by trade P&L in Currency or Percentage.

"},{"location":"analytics/python-build-view-results/#end-of-year-returns-plot","title":"End of Year Returns Plot (%)","text":""},{"location":"analytics/python-build-view-results/#monthly-returns-histogram","title":"Monthly Returns Histogram (%)","text":""},{"location":"analytics/python-build-view-results/#monthly-returns-heatmap","title":"Monthly Returns Heatmap (%)","text":""},{"location":"analytics/python-build-view-results/#daily-returns","title":"Daily Returns (%)","text":""},{"location":"analytics/python-build-view-results/#underwater-drawdown-plot","title":"Underwater Drawdown Plot (%)","text":""},{"location":"analytics/python-build-view-results/#pl-book","title":"P&L Book","text":"

View detailed trade by trade report. Premium users can analyze this data in the form of heatmaps for Gross Profit & Loss, Trading Volume & Total number of Trades.

"},{"location":"analytics/python-build-view-results/#user-log","title":"User Log","text":"

Real-time logs from strategy execution are displayed in this section. Use these logs to debug your strategy\u2019s behavior and performance.

"},{"location":"analytics/python-build-view-results/#order-history","title":"Order History","text":"

View the order state transition for every order placed by your strategy in-depth.

"},{"location":"brokers/broker_alpaca_guide/","title":"Alpaca","text":"

Alpaca is a technology company that offers a modern, developer-friendly trading platform designed for algorithmic and automated trading in the financial markets, particularly focused on equities and cryptocurrencies. The company provides APIs ( Application Programming Interfaces) that allow developers and traders to access market data, execute trades, and build their own algorithmic trading strategies.

Key features and offerings of Alpaca include:

  1. APIs and SDKs: Alpaca offers APIs and software development kits (SDKs) that enable developers to programmatically access real-time and historical market data, as well as execute trades on various exchanges.

  2. Algorithmic Trading: Alpaca's platform is tailored for algorithmic trading strategies, where traders can automate trading decisions based on predefined conditions and rules.

  3. Paper Trading: Alpaca provides a simulated environment called \"paper trading,\" allowing traders to test their strategies in a risk-free setting before deploying them with real money.

  4. Market Data: The platform offers access to real-time and historical market data, which is crucial for building and testing trading strategies.

  5. Order Execution: Traders can use Alpaca's API to execute trades on supported exchanges. This includes submitting market, limit, and stop orders.

  6. Customizable Dashboards: Alpaca provides customizable dashboards and interfaces to monitor trading activity and portfolio performance.

  7. Brokerage Services: Alpaca acts as a brokerage, providing services that allow traders to execute their strategies on supported exchanges.

  8. Regulatory Compliance: Alpaca operates within the regulations of the financial industry, ensuring compliance with rules and requirements.

Alpaca's platform aims to democratize algorithmic trading by providing accessible tools and resources for both individual traders and developers. It's worth noting that the landscape of algorithmic trading and financial technology is constantly evolving, so it's a good idea to check Alpaca's official website for the most current information about their offerings and services.

"},{"location":"brokers/broker_alpaca_guide/#advantages-of-binding-alpaca-with-your-algobulls-account","title":"Advantages of binding Alpaca with your AlgoBulls account","text":""},{"location":"brokers/broker_alpaca_guide/#how-to-bind-alpaca-with-your-algobulls-account","title":"How to bind Alpaca with your AlgoBulls account?","text":"

You can connect your Alpaca account with AlgoBulls in two ways: OAuth and Non-OAuth.

WARNING: We have discontinued the Non-OAuth method in accordance with Alpaca\u2019s recommendations. Please use the OAuth method for seamless integration and improved security. Be mindful of this update as you proceed with your integrations.

"},{"location":"brokers/connecting_alpaca/","title":"OAuth","text":"

Embark on a streamlined and secure journey as you bind your Alpaca broker with AlgoBulls through OAuth integration. This seamless process ensures a robust connection between your accounts, allowing for efficient data exchange and trading activities. With OAuth binding, you can experience the convenience of a secure link without compromising on the integrity of your financial operations. Follow our comprehensive guide to effortlessly set up OAuth binding and unleash the full potential of AlgoBulls with Alpaca integration.

"},{"location":"brokers/connecting_alpaca/#an-overview","title":"An overview","text":""},{"location":"brokers/connecting_alpaca/#how-to-set-up-alpaca-for-trading-in-algobulls-with-oauth","title":"How to set up Alpaca for trading in AlgoBulls with OAuth?","text":"

Before this step, please make sure you have an Alpaca account. Click here to visit the Alpaca site for creating your account.

"},{"location":"brokers/connecting_alpaca/#add-broker","title":"Add Broker","text":""},{"location":"brokers/connecting_alpaca/#search-for-alpaca","title":"Search for Alpaca","text":"

"},{"location":"brokers/connecting_alpaca/#provide-permission","title":"Provide Permission","text":"

WARNING: We have discontinued the Non-OAuth method in accordance with Alpaca\u2019s recommendations. Please use the OAuth method for seamless integration and improved security. Be mindful of this update as you proceed with your integrations.

"},{"location":"brokers/non_auth_alpaca/","title":"Non-OAuth","text":"

WARNING: We have discontinued the Non-OAuth method in accordance with Alpaca\u2019s recommendations. Please use the OAuth method for seamless integration and improved security. Be mindful of this update as you proceed with your integrations.

If you are seeking an alternative to OAuth, the Non-OAuth binding option provides a straightforward and reliable approach to connect your Alpaca broker with AlgoBulls. This method ensures a direct and effective link between your accounts, maintaining the simplicity and efficiency that defines the AlgoBulls experience. Discover the step-by-step process to establish Non-OAuth binding and gain immediate access to the powerful synergy between AlgoBulls and Alpaca, facilitating seamless trading and data synchronisation.

"},{"location":"brokers/non_auth_alpaca/#how-to-set-up-alpaca-for-trading-in-algobulls-with-non-oauth","title":"How to set up Alpaca for trading in AlgoBulls with Non-OAuth?","text":"

Before trying to bind your broker, please make sure you have an Alpaca account or follow the steps given below to create your account.

"},{"location":"brokers/non_auth_alpaca/#create-your-alpaca-account","title":"Create your Alpaca Account","text":""},{"location":"brokers/non_auth_alpaca/#api-keys","title":"API keys","text":" "},{"location":"brokers/non_auth_alpaca/#add-broker","title":"Add Broker","text":""},{"location":"brokers/non_auth_alpaca/#search-for-alpaca-non-oauth","title":"Search for Alpaca Non-OAuth","text":""},{"location":"brokers/non_auth_alpaca/#provide-api-and-secret-key","title":"Provide API And Secret key","text":" "},{"location":"gen_ai/gen_ai_prompt_library/","title":"Prompt Library for Gen AI","text":""},{"location":"gen_ai/gen_ai_prompt_library/#here-are-some-prompts-for-creating-strategy-using-genai","title":"Here are some prompts for Creating Strategy using GenAI","text":""},{"location":"gen_ai/gen_ai_prompt_library/#moving-averages-ema-or-sma","title":"Moving Averages (EMA or SMA)","text":"

Create a trading strategy which takes a BUY trade when EMA cuts SMA upwards and a SELL trade when EMA cuts SMA downwards. While placing a trade, if a previous position is open, it should be exited before placing the new trade\n
Create a strategy which uses 2 EMAs of different time periods, and it BUYs when EMA of timeperiod 1 crosses the EMA of timeperiod 2 upwards and SELLs when EMA of timeperiod 1 crosses the EMA of timeperiod 2 downwards.\n
Create a trading strategy which takes a BUY trade when EMA cuts SMA upwards and a SELL trade when EMA cuts SMA downwards. While placing a trade, if a previous position is open, it should be exited before placing the new trade\n
Develop a strategy that generates a BUY signal when a shorter-term moving average crosses above an intermediate-term moving average, which then crosses above a longer-term moving average. Conversely, generate a SELL signal when the moving averages crossover in the opposite direction.\n

"},{"location":"gen_ai/gen_ai_prompt_library/#relative-strength-index-rsi","title":"Relative Strength Index (RSI)","text":"

Create a strategy that uses RSI indicator to give signals based on over bought or over sold conditions. If RSI is above 70, the strategy should generate a SELL signal and if it's below 30, it should generate a BUY signal\n
Create a strategy using RSI of MACD-signal of close with fast MA period as X, slow MA period as Y and signal period as Z, which will SELL on crossing the upper band and BUY on crossing the lower band\n
Create a trading strategy which takes BUY when RSI crosses lower band and create a SELL when RSI crosses the upward band, set a stop loss of 2% and target to be 15%.\n
Create a trading strategy using RSI technical indicator\n
Create a strategy using RSI of MACD-signal of close with fast MA period as X, slow MA period as Y and signal period as Z, which will SELL on crossing the upper band and BUY on crossing the lower band\n
Please help me with a strategy that uses RSI indicator to give signals based on over bought or over sold conditions. If RSI is above 70, the strategy should generate a SELL signal and if it's below 30, it should generate a BUY signal\n
Create a trading strategy which takes BUY when RSI crosses lower band and create a SELL when RSI crosses the upward band, set a stop loss of 2% and target to be 15%.\n

"},{"location":"gen_ai/gen_ai_prompt_library/#aroon","title":"Aroon","text":"
Create a trading strategy that utilizes the Aroon indicator to generate signals based on overbought or oversold conditions. If the Aroon Up line crosses below the Aroon Down line and falls below 30, the strategy should generate a BUY signal. Conversely, if the Aroon Up line crosses above the Aroon Down line and rises above 70, the strategy should generate a SELL signal\n
"},{"location":"gen_ai/gen_ai_prompt_library/#stochastic","title":"Stochastic","text":"

Develop a trading strategy that incorporates the stochastic crossover to generate signals. When the %K line crosses above the %D line and both lines are below 30, the strategy should generate a BUY signal. Similarly, when the %K line crosses below the %D line and both lines are above 70, the strategy should generate a SELL signal\n
Develop a strategy that generates a BUY signal when the Stochastic RSI indicator crosses above the oversold level (e.g., 20) and a SELL signal when it crosses below the overbought level (e.g., 80).\n

"},{"location":"gen_ai/gen_ai_prompt_library/#bollinger-bands-bb","title":"Bollinger Bands (BB)","text":"
Develop a strategy that generates a BUY signal when the price breaks above the upper Bollinger Band. Similarly, generate a SELL signal when the price breaks below the lower Bollinger Band\n
"},{"location":"gen_ai/gen_ai_prompt_library/#atr-volatility","title":"ATR (Volatility)","text":"
Develop a strategy that generates a BUY signal when the price surpasses a multiple of the ATR above a recent swing high, indicating increased volatility and potential upward momentum. Conversely, generate a SELL signal when the price drops below a multiple of the ATR below a recent swing low, indicating increased volatility and potential downward momentum.\n
"},{"location":"gen_ai/gen_ai_prompt_library/#moving-average-convergence-divergence-macd","title":"Moving Average Convergence Divergence (MACD)","text":"
Create a strategy that generates a BUY signal when the MACD histogram bars cross above the zero line and a SELL signal when the histogram bars cross below the zero line.\n
"},{"location":"gen_ai/gen_ai_prompt_library/#volume-weighted-average-price-vwap","title":"Volume Weighted Average Price (VWAP)","text":"
Create a strategy that generates a BUY signal when the price rises above the VWAP line and a SELL signal when the price drops below the VWAP line, indicating potential shifts in supply and demand.\n
"},{"location":"gen_ai/gen_ai_prompt_library/#miscellaneous","title":"Miscellaneous","text":"
Create a strategy that generates a BUY signal when the price crosses above the cloud (Span A and Span B) and the cloud changes color from red to green. Conversely, generate a SELL signal when the price crosses below the cloud and the cloud changes color from green to red.\n
Develop a strategy that generates a BUY signal when the price crosses above the Parabolic SAR dots and a SELL signal when the price crosses below the dots.\n
Implement a gap and go strategy that capitalizes on the momentum created by price gaps at the market open. When the price gaps up significantly and continues to move higher, generate a BUY signal. Similarly, when the price gaps down substantially and continues to move lower, generate a SELL signal.\n
"},{"location":"gen_ai/get_open_ai_keys/","title":"OpenAI","text":""},{"location":"gen_ai/get_open_ai_keys/#what-is-chat-gpt","title":"What is Chat-GPT ?","text":"

Generative AI involves creating new content using machine learning. A key method is GANs, where a generator creates data and a discriminator evaluates its realism. Another method is VAEs, which encode and decode data. ChatGPT is a specific AI model using generative text, like a conversation. It can understand context, answer questions, and generate text in a human-like manner. It finds use in various fields, from text generation to customer service, but also raises concerns about accuracy and responsible use.

"},{"location":"gen_ai/get_open_ai_keys/#why-we-use-chat-gpt","title":"Why we use Chat-GPT ?","text":"

ChatGPT can assist in generating code for algorithmic trading strategies. It can translate strategy ideas into code snippets, provide coding guidance, and help with customization. However, human expertise is essential to validate, optimize, and manage risks in the complex realm of algorithmic trading.

"},{"location":"gen_ai/get_open_ai_keys/#how-to-get-chat-gpt-api-keys","title":"How to get Chat-GPT API keys ?","text":"

To get your chat GPT API keys, you can watch the video given below

Or

You can simply follow the steps here:

"},{"location":"gen_ai/get_open_ai_keys/#step-1-loginsignup","title":"Step 1 - Login/Signup","text":"

Login or Signup in your open AI account, you can use gmail account, microsoft account or apple account to signup.

"},{"location":"gen_ai/get_open_ai_keys/#step-2-open-your-profile","title":"Step 2 - Open Your Profile","text":"

Once you are on the home page of your account, you can select your profile on top-right corner, and then select the option View API Keys from the drop-down menu.

"},{"location":"gen_ai/get_open_ai_keys/#step-3-generate-new-secret-keys","title":"Step 3 - Generate New Secret Keys","text":"

Now that you are in the API Keys section, you will have to create a new key.

"},{"location":"gen_ai/get_open_ai_keys/#step-4-get-secrete-keys","title":"Step 4 - Get Secrete Keys","text":"

On clicking Create new secret key a pop-up will appear, where you can enter the key name, which is for your reference to remember multiple secret keys, once done, there will be another section where you can copy the open-ai secret keys.

"},{"location":"gen_ai/get_open_ai_keys/#step-5-ready-to-go-with-algobulls","title":"Step 5 - Ready to go with AlgoBulls","text":"

Once you have copied your secret key then you can now save it on your AlgoBulls Account for accessing the gen-ai feature to create a strategy, and there you go. To know how to save keys and start with generating strategies using Chat-GPT, click here Happy Trading !

"},{"location":"pyalgotrad/brokerage/","title":"Brokerage","text":""},{"location":"pyalgotrad/brokerage/#brokerage","title":"Brokerage","text":""},{"location":"pyalgotrad/brokerage/#how-to-use","title":"How to Use","text":"

To incorporate slippage and brokerage into your backtesting, simply pass the desired values for slippage_percent, broker_commission_percentage, and broker_commission_price when calling the algobulls_connection.get_backtesting_report_pnl_table function. These parameters help you account for real-world trading costs and execution variations, making your backtesting results more realistic.

"},{"location":"pyalgotrad/brokerage/#example","title":"Example","text":"
import algobulls_connection\n# Fetch PnL data for a trading strategy with custom slippage and brokerage settings\npnl_table = algobulls_connection.get_backtesting_report_pnl_table(\n    strategy_code=\"your_strategy_code\",\n    show_all_rows=True,\n    force_fetch=True,\n    country='USA',\n    broker_commission_percentage=1.5,  # Adjust brokerage percentage as needed\n    broker_commission_price=0.3,      # Adjust fixed brokerage cost as needed\n    slippage_percent=4.5,             # Adjust slippage percentage as needed\n)\n# Print the PnL table with custom slippage and brokerage settings\nprint(pnl_table)\n
"},{"location":"pyalgotrad/introduction/","title":"pyalgotrading","text":""},{"location":"pyalgotrad/introduction/#introduction","title":"Introduction","text":"

Welcome to the Pyalgotrading Documentation \u2013 your guide to practising and acquainting yourself with the pyalgotrading package. Pyalgotrading, built with Python, is an algorithmic trading library that empowers you to design and implement trading strategies on a variety of financial instruments, such as equities, futures, and options. To embark on your journey with Pyalgotrading, ensure you have an active AlgoBulls account, a platform designed for creating and testing trading strategies.

"},{"location":"pyalgotrad/introduction/#key-features","title":"Key Features","text":"

Backtesting, Paper Trading and Real Trading can be performed on the same strategy code base!

Prerequisites

Before you commence development, make sure to establish your workspace and gather all prerequisites as outlined here.

"},{"location":"pyalgotrad/introduction/#support-seeking-assistance","title":"Support / Seeking Assistance","text":""},{"location":"pyalgotrad/introduction/#overview","title":"Overview","text":"
  1. Check out the basic structure of a strategy: Before coding your strategy, refer to the basic structure guide provided by the Pyalgotrading package. This will help you understand the trading strategy methods and flow.

  2. Code your own simple strategy using the pyalgotrading package: Use your Python IDE to code your trading strategy using the pyalgotrading package. You can also use ready-made strategies from the pyalgostrategypool package if you prefer not to code your own.

  3. Upload your strategy to the platform: Upon coding your strategy, upload it to the AlgoBulls platform by crafting a new strategy and uploading the corresponding file.

  4. Run Backtest / Paper Trade / Real Trade with your strategy: Once uploaded, initiate backtests, paper trades, or real trades on the AlgoBulls platform to evaluate its performance.

  5. Retrieve real-time logs, review reports and stats, and inspect order history:Monitor your strategy's performance by fetching runtime logs, examining reports and statistics, and reviewing your order history to track executed trades.

  6. Reach out to AlgoBulls Support for any queries: If you encounter issues during the tutorial, contact the AlgoBulls Support team for assistance.

"},{"location":"pyalgotrad/introduction/#conclusion","title":"Conclusion","text":"

This documentation serves as your launchpad into the Pyalgotrading package and the creation of your trading strategies. It also steers you through the process of uploading, executing, and monitoring strategies on the AlgoBulls platform. Our goal is to equip you with the expertise needed to craft effective trading strategies using Pyalgotrading.

"},{"location":"pyalgotrad/introduction/#contribution-guidelines","title":"Contribution Guidelines","text":"
  1. Fork this project to your account.
  2. Create a branch for the change you intend to make.
  3. Make your changes to your fork.
  4. Send a pull request from your fork\u2019s branch to our master branch.
"},{"location":"pyalgotrad/prerequisites/","title":"Setup your Workspace","text":""},{"location":"pyalgotrad/prerequisites/#prerequisites","title":"Prerequisites","text":"

You will need the following to start with Pyalgotrading:

"},{"location":"pyalgotrad/prerequisites/#algobulls-account","title":"AlgoBulls Account","text":"

To upload and test your strategies, you will need this account. You can create your account for FREE on the Algobulls website.

"},{"location":"pyalgotrad/prerequisites/#developer-key","title":"Developer Key","text":"

To access the features, you will need a developer key. The key can be obtained as follows:

Please Note

For security reasons, the developer key will get reset every time you log out from your AlgoBulls account.

Once you have the developer key, you can access the AlgoBulls platform using pyalgotrading functions.

"},{"location":"pyalgotrad/prerequisites/#python-310","title":"Python 3.10+","text":"

The Pyalgotrading platform can run all strategies that conform to Python 3.8 or higher. However, we recommend Python 3.10 or higher.

Python Tips

"},{"location":"pyalgotrad/prerequisites/#pyalgotrading-package","title":"Pyalgotrading Package","text":"

To create and execute your fully automated trading strategies, you only need to install pyalgotrading. You can install the pyalgotrading package using the following command:

pip install pyalgotrading\n

"},{"location":"pyalgotrad/prerequisites/#jupyter-notebook","title":"Jupyter Notebook","text":"

You will use a Jupyter Notebook to connect to the AlgoBulls platform. Using the notebook, you can upload the strategy, test your strategy (Backtesting, Paper Trading, or Real Trading), and fetch logs. Install Jupyter Notebook using the following command:

pip install jupyter\n

Pro Tip

If you are an experienced Pyalgotrading user, Jupyter Notebook might not be necessary. You can directly integrate it into your application.

"},{"location":"pyalgotrad/prerequisites/#enhancing-productivity","title":"Enhancing Productivity","text":"

For enhancing your productivity while building and executing strategies using Pyalgotrading, you can make use of Python IDEs of your choice, such as:

"},{"location":"pyalgotrad/programexample/","title":"Create your Strategy","text":""},{"location":"pyalgotrad/programexample/#previously","title":"Previously...","text":"

You have covered the basic code structure of a strategy.

"},{"location":"pyalgotrad/programexample/#now","title":"Now...","text":"

You can either follow this page to create a strategy, or you can pick up a ready strategy (shown below) and move to the next page.

"},{"location":"pyalgotrad/programexample/#before-you-start","title":"Before you start...","text":"

If you want to use a ready strategy from the pyalgostrategypool package, then you can directly jump to the Upload section.

"},{"location":"pyalgotrad/programexample/#lets-start","title":"Let's Start...","text":"

Follow the steps given below to create a new strategy of your own.

Create a python file called strategy_sma_regular_order.py.

You will add the following code snippets into the file and then save it.

"},{"location":"pyalgotrad/programexample/#import-statements","title":"Import statements","text":"
from pyalgotrading.strategy.strategy_base import StrategyBase\nfrom pyalgotrading.constants import *\n
"},{"location":"pyalgotrad/programexample/#create-the-class-strategysmaregularorder-and-subclass-it-from-strategybase","title":"Create the class StrategySMARegularOrder and subclass it from StrategyBase","text":"

class StrategySMARegularOrder(StrategyBase):\n
Now you can add the methods mentioned in the structure inside the class. First you can add the __init__ and the initialize methods.

"},{"location":"pyalgotrad/programexample/#constructor-def-__init__","title":"Constructor: def __init__()","text":"
def __init__(self, *args, **kwargs):\n    name = 'SMA Regular Order Strategy'\n    super().__init__(*args, **kwargs)\n\n    self.timeperiod_x = self.strategy_parameters['timeperiod1']\n    self.timeperiod_y = self.strategy_parameters['timeperiod2']\n\n    self.main_order = None\n

The init method does the following:

  1. name - variable which should store the name of your strategy
  2. super() - Calls the constructor of the superclass.
  3. self.strategy_parameters - Catches the parameters and saves them for local use - When you will submit a testing job for your SMA strategy, you will pass parameters that will be used inside the strategy. For SMA, we are calculating crossover for 2 SMA timeperiod values, example 5 and 12. These 2 parameters will be caught by self.strategy_parameters and stored for local use in self.timeperiod1 and self.timeperiod2.
  4. self.main_order - Create an object that manages orders for you throughout the strategy.

The init method is specific to Python's internal workings, and it is preceded and succeeded by double underscores ( _ _ ) joined together.

"},{"location":"pyalgotrad/programexample/#def-initialize","title":"def initialize()","text":"
def initialize(self):\n    self.main_order = {}\n

The initialize method sets the self.main_order as an empty dictionary. This method is called at the start of every trading day.

For instance, say you are submitting a backtesting job for 5 previous days starting at 10:30 every day, then the initialize method will be called every day for 5 days at 10:30.

Now add the two static methods, name and versions_supprted.

"},{"location":"pyalgotrad/programexample/#def-name-optional","title":"def name() (optional)","text":"

If the name variable is defined in __init__(), this function is not needed.

@staticmethod\ndef name():\n    return 'SMA Regular Order Strategy'\n
The name should be unique in your collection of strategies.

"},{"location":"pyalgotrad/programexample/#def-versions_supported-optional","title":"def versions_supported() (optional)","text":"

not required it will take the latest version of AlgoBullsEngine by default

@staticmethod\ndef versions_supported():\n    return AlgoBullsEngineVersion.VERSION_3_2_0\n
Mark both the above methods as @staticmethod.

The versions_supported method does the following:

  1. It notifies the AlgoBulls platform that the strategy is working correctly for the platform version 3.2.0
  2. Since the platform will be constantly upgraded to incorporate new features and improve efficiency, the version may change.
  3. If the version changes, and if you submit a job for this strategy, then the AlgoBulls platform will spawn a server having version 3.2.0 for your strategy.
  4. Having this method ensures that the AlgoBulls platform always provides the correct environment for your strategy.
"},{"location":"pyalgotrad/programexample/#def-strategy_select_instruments_for_entry","title":"def strategy_select_instruments_for_entry()","text":"
def strategy_select_instruments_for_entry(self, candle, instruments_bucket):\n\n    instruments = []\n    meta = []\n\n    for instrument in instruments_bucket:\n        crossover_value = self.get_crossover_value(instrument)\n        if crossover_value == 1:\n            instruments.append(instrument)\n            meta.append({'action': 'BUY'})\n        elif crossover_value == -1:\n            if self.strategy_mode is StrategyMode.INTRADAY:\n                instruments.append(instrument)\n                meta.append({'action': 'SELL'})\n\n    return instruments, meta\n

The strategy_select_instruments_for_entry method does the following:

  1. instruments and meta - Creates 2 empty lists that will be used to pass the selected instruments and additional information about them respectively.
  2. The Loop - The loop will iterate over each instrument name passed (while submitting the job) and will decide whether to set an entry position or not for it.
  3. crossover_value - The crossover value is calculated and stored here. Crossover values are interpreted as:
    1. Value 1 - Cut upwards
    2. Value -1 - Cut downwards
    3. Value 0 - No crossover
  4. If conditions - If the crossover value is 1, then the instrument is selected for entry position, with the position as 'BUY'. If the crossover value is -1, then the instrument is selected for entry position, with the position as 'SELL'. The selected instrument is appended to the instruments, and the associated action (BUY/SELL) is appended to the meta.
  5. instruments and meta - Both the lists (whether populated or empty) are returned to the platform for further actions.

Note

"},{"location":"pyalgotrad/programexample/#def-strategy_enter_position","title":"def strategy_enter_position()","text":"
def strategy_enter_position(self, candle, instrument, sideband_info):\n    if sideband_info['action'] == 'BUY':\n        qty = self.number_of_lots * instrument.lot_size\n        self.main_order[instrument] = \\\n            self.broker.BuyOrderRegular(instrument=instrument,\n                order_code=BrokerOrderCodeConstants.INTRADAY,\n                order_variety=BrokerOrderVarietyConstants.MARKET,\n                quantity=qty)\n    elif sideband_info['action'] == 'SELL':\n        qty = self.number_of_lots * instrument.lot_size\n        self.main_order[instrument] = \\\n            self.broker.SellOrderRegular(instrument=instrument,\n                 order_code=BrokerOrderCodeConstants.INTRADAY,\n                 order_variety=BrokerOrderVarietyConstants.MARKET,\n                 quantity=qty)\n    else:\n        raise SystemExit(f'Got invalid sideband_info value: {sideband_info}')\n\n    return self.main_order[instrument]\n
"},{"location":"pyalgotrad/programexample/#or","title":"or","text":"
def strategy_enter_position(self, candle, instrument, meta):\n    self.main_order_map[instrument] = _ = self.broker.OrderRegular(\n        intrument=instrument,                           \n        order_transaction_type=meta['action'],              # 'BUY' or 'SELL'\n        quantity=self.number_of_lots * instrument.lot_size, # number of lots (int)\n        price=None,\n        trigger_price=None\n    )\n    return _\n

The strategy_enter_position method does the following:

  1. If conditions - The conditions read the action from the sideband_info and perform the required action (BUY/SELL).
  2. qty - The quantity is calculated and stored here. The number of lots will be passed by you as a parameter while submitting a job. The parameter will be caught in self.number_of_lots. The instrument object has the 'lot size', which you can retrieve using instrument.lot_size. You can then use the formula as shown in the code to calculate the quantity.
  3. OrderRegular,BuyOrderRegular and SellOrderRegular - These execute the required action. You need to pass the instrument, order code, order variety and the quantity values.
    • instrument - the instrument on which the BUY/SELL action will be performed.
    • order_code - whether the order is for INTRADAY or DELIVERY. Possible values are:
      • BrokerOrderCodeConstants.INTRADAY
      • BrokerOrderCodeConstants.DELIVERY
      • BrokerOrderCodeConstants.DELIVERY_T1
      • BrokerOrderCodeConstants.DELIVERY_T2
    • order_variety - the type of order variety. Possible values are:
      • BrokerOrderVarietyConstants.MARKET
      • BrokerOrderVarietyConstants.LIMIT
      • BrokerOrderVarietyConstants.STOPLOSS_MARKET
      • BrokerOrderVarietyConstants.STOPLOSS_LIMIT
    • qty - the quantity to BUY/SELL.
  4. self.main_order - The main order (for that particular instrument) is now populated (BUY OR SELL) and is returned to the platform for further actions.

You can also punch Bracket Orders instead of Regular Orders. A typical BUY Bracket Order will look like this:

qty = self.number_of_lots * instrument.lot_size\nltp = self.broker.get_ltp(instrument)\nself.main_order[instrument] = \\\n            self.broker.BuyOrderBracket(instrument=instrument,\n                order_code=BrokerOrderCodeConstants.INTRADAY,\n                order_variety=BrokerOrderVarietyConstants.LIMIT,\n                quantity=qty,\n                price=ltp,\n                stoploss_trigger=ltp - (ltp * self.stoploss),\n                target_trigger=ltp + (ltp * self.target),\n                trailing_stoploss_trigger=ltp * self.trailing_stoploss)\n

The additional parameters are:

Note

"},{"location":"pyalgotrad/programexample/#def-strategy_select_instruments_for_exit","title":"def strategy_select_instruments_for_exit()","text":"
def strategy_select_instruments_for_exit(self, candle, instruments_bucket):\n    instruments = []\n    meta = []\n\n    for instrument in instruments_bucket:\n        if self.main_order.get(instrument) is not None:\n            crossover_value = self.get_crossover_value(instrument)\n            if crossover_value in [1, -1]:\n                instruments.append(instrument)\n                meta.append({'action': 'EXIT'})\n    return instruments, meta\n

The strategy_select_instruments_for_exit method does the following:

  1. instruments and meta - Creates 2 empty lists that will be used to pass the selected instruments and additional information about them respectively.
  2. The Loop - The loop will iterate over each instrument name passed (which are in Entry position (BUY/SELL)) and will decide whether to set an exit position or not for it.
  3. If condition - The exit steps are executed only if the instrument is holding at an ENTRY position (BUY/SELL). You can do this by checking if the self.main_order object is None or not, and proceed only if it is not None.
  4. crossover_value - The crossover value is calculated and stored here. Crossover values are interpreted as:
    1. Value 1 - Cut upwards
    2. Value -1 - Cut downwards
    3. Value 0 - No crossover
  5. If condition - If the crossover value is 1 or -1, then the instrument is selected for exit position. The selected instrument is appended to the instruments, and the associated action (EXIT) is appended to the meta.
  6. instruments and meta - Both the lists (whether populated or empty) are returned to the platform for further actions.

Note

"},{"location":"pyalgotrad/programexample/#def-strategy_exit_position","title":"def strategy_exit_position()","text":"
def strategy_exit_position(self, candle, instrument, sideband_info):\n    if sideband_info['action'] == 'EXIT':\n        self.main_order[instrument].exit_position()\n        self.main_order[instrument] = None\n        return True\n\n    return False\n

The strategy_exit_position method does the following:

  1. If condition - checks whether the appropriate action is set in the sideband_info.
  2. self.main_order - calls exit_position method for the particular main order of the instrument. If the Entry Position was BUY, then the exit position is automatically taken as SELL and vice versa. The platform takes care of this automatically.
  3. self.main_order - set it to None, as the order has been exited and no longer holds anything.
  4. Return values - returns True to the platform if the exit steps were performed, else return False.
"},{"location":"pyalgotrad/programexample/#def-get_crossover_value","title":"def get_crossover_value()","text":"
def get_crossover_value(self, instrument):\n    hist_data = self.get_historical_data(instrument)\n    sma_x = talib.SMA(hist_data['close'], timeperiod=self.timeperiod_x)\n    sma_y = talib.SMA(hist_data['close'], timeperiod=self.timeperiod_y)\n    crossover_value = self.utils.crossover(sma_x, sma_y)\n    return crossover_value\n

The get_crossover_value method does the following:

  1. hist_data - The historical data for the instrument is fetched using the get_historical_data method and stored here. The data is in the form of a table (Pandas DataFrame) having the following columns:
    • timestamp - the data and time when the data was measured
    • volume - the volume of that instrument
    • open, high, low and close - the OHLC values of the instrument
    • oi - the Open Interest of that instrument
  2. sma_x and sma_y - the SMA function from the talib package is used to calculate the Moving Average for both SMA time-periods. The candle close value is used for calculations, i.e. hist_data['close'].
  3. crossover_value - calculates the crossover value using the crossover method from the utils package.
  4. Return value - return the crossover value to the caller method.

Note

"},{"location":"pyalgotrad/programexample/#whats-next","title":"What's Next...","text":"

Next, you upload the strategy into your AlgoBulls account.

"},{"location":"pyalgotrad/pyalgotrading_analytics/","title":"Pyalgotrading Analytics","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#metric-values-and-statistics","title":"Metric Values and Statistics","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#cumulative-returns","title":"Cumulative Returns","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#end-of-year-returns-eoy","title":"End of Year Returns (EoY)","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#distributions-of-monthly-returns-histogram","title":"Distributions of Monthly Returns (Histogram)","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#daily-returns","title":"Daily Returns","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#rolling-volatility-6-months","title":"Rolling Volatility (6 months)","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#rolling-sharpe-6-months","title":"Rolling Sharpe (6 months)","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#rolling-sortino-6-months","title":"Rolling Sortino (6 months)","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#worst-5-drawdown-periods","title":"Worst 5 Drawdown Periods","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#underwater-plot","title":"Underwater Plot","text":""},{"location":"pyalgotrad/pyalgotrading_analytics/#monthly-returns-heatmap","title":"Monthly Returns (Heatmap)","text":""},{"location":"pyalgotrad/python-build-view-results/","title":"Python build view results","text":""},{"location":"pyalgotrad/python-build-view-results/#how-to-view-the-results","title":"How to view the Results?","text":"

Once you start the strategy, it may take a while for it to complete the execution. You can switch to the Analytics tab after you run your strategy. Even if the strategy execution is not complete, you will still see intermediate results.

Analytics: In the analytics section, you can view a strategy\u2019s Stats & various other metrics in the form of graphs like P&L.

"},{"location":"pyalgotrad/python-build-view-results/#stats","title":"Stats","text":"

In this section you can see the total returns, sharpe ratio, sortino ratio, volatility, Max Drawdown, Total wins or Loses, Total short or long trades, hit ratio, number of trades, average trades per day, max profit, max loss, average profit per winning trade, average loss per losing trade.

"},{"location":"pyalgotrad/python-build-view-results/#cumulative-returns","title":"Cumulative Returns","text":""},{"location":"pyalgotrad/python-build-view-results/#profit-loss-currency-or","title":"Profit & Loss (Currency or %)","text":"

The trade by trade P&L in Currency or Percentage.

"},{"location":"pyalgotrad/python-build-view-results/#end-of-year-returns-plot","title":"End of Year Returns Plot (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#monthly-returns-histogram","title":"Monthly Returns Histogram (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#monthly-returns-heatmap","title":"Monthly Returns Heatmap (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#daily-returns","title":"Daily Returns (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#underwater-drawdown-plot","title":"Underwater Drawdown Plot (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#pl-book","title":"P&L Book","text":"

View detailed trade by trade report. Premium users can analyze this data in the form of heatmaps for Gross Profit & Loss, Trading Volume & Total number of Trades.

"},{"location":"pyalgotrad/python-build-view-results/#user-log","title":"User Log","text":"

Real-time logs from strategy execution are displayed in this section. Use these logs to debug your strategy\u2019s behavior and performance.

"},{"location":"pyalgotrad/python-build-view-results/#order-history","title":"Order History","text":"

View the order state transition for every order placed by your strategy in-depth.

"},{"location":"pyalgotrad/select/","title":"Select your Strategy","text":""},{"location":"pyalgotrad/select/#previously","title":"Previously...","text":"

You have uploaded or saved a strategy by:

OR

"},{"location":"pyalgotrad/select/#now","title":"Now...","text":"

You are now ready to select or import your strategy from your AlgoBulls account for Backtesting, Paper Trading and/or Real Trading.

"},{"location":"pyalgotrad/select/#before-you-start","title":"Before you start...","text":""},{"location":"pyalgotrad/select/#lets-start","title":"Let's Start...","text":"

Run the following code snippets into the Jupyter Notebook one by one (or all together).

"},{"location":"pyalgotrad/select/#import-statements","title":"Import statements","text":"
import inspect\nfrom pyalgotrading.algobulls import AlgoBullsConnection\n
"},{"location":"pyalgotrad/select/#import-the-strategy-class","title":"Import the strategy class","text":"

Perform the below step either to import a ready strategy OR to import your own created strategy.

"},{"location":"pyalgotrad/select/#establish-a-connection-to-the-algobulls-platform","title":"Establish a connection to the AlgoBulls Platform","text":"

algobulls_connection = AlgoBullsConnection()\nalgobulls_connection.get_authorization_url()\n
The output of the above step is:

Please login to this URL with your AlgoBulls credentials and get your developer access token: https://app.algobulls.com/user/login

Get Developer Key

You will need to log in to your AlgoBulls account and fetch the access token from: (See How) Settings -> General -> Developer Options

Once you have the access token, set it in the code as shown here:

algobulls_connection.set_access_token('4365817b795770ea31040a21ad29c8e78b63ad88')\n
Replace the token you have copied with the token in the code above.

"},{"location":"pyalgotrad/select/#view-all-the-strategies-in-your-algobulls-account","title":"View all the strategies in your AlgoBulls Account","text":"

You can view all the strategy saved on your AlgoBulls account.

all_strategies_df = algobulls_connection.get_all_strategies()\nprint(all_strategies_df)\n

"},{"location":"pyalgotrad/select/#search-your-strategy","title":"Search your Strategy","text":""},{"location":"pyalgotrad/select/#whats-next","title":"What's Next...","text":"

You are now ready to test your uploaded strategy and perform Backtesting, Paper Trading and/or Real Trading with it.

"},{"location":"pyalgotrad/slippage/","title":"Slippage","text":""},{"location":"pyalgotrad/slippage/#slippage-and-brokerage-parameters","title":"Slippage and Brokerage Parameters","text":"

In the algobulls_connection.get_backtesting_report_pnl_table function, you have the option to specify slippage and brokerage parameters to account for transaction costs and execution variations. These parameters allow you to fine-tune your backtesting results to better simulate real-world trading conditions.

"},{"location":"pyalgotrad/slippage/#slippage","title":"Slippage","text":""},{"location":"pyalgotrad/slippage/#how-to-use","title":"How to Use","text":"

To incorporate slippage into your backtesting, simply pass the desired values for slippage_percent, when calling the algobulls_connection.get_backtesting_report_pnl_table function. These parameters help you account for real-world trading costs and execution variations, making your backtesting results more realistic.

"},{"location":"pyalgotrad/slippage/#example","title":"Example","text":"
import algobulls_connection\n# Fetch PnL data for a trading strategy with custom slippage  settings\npnl_table = algobulls_connection.get_backtesting_report_pnl_table(\n    strategy_code=\"your_strategy_code\",\n    show_all_rows=True,\n    force_fetch=True,\n    country='USA',\n    slippage_percent=4.5,             # Adjust slippage percentage as needed\n)\n# Print the PnL table with custom slippage  settings\nprint(pnl_table)\n
"},{"location":"pyalgotrad/testing/","title":"Execute your Strategy","text":""},{"location":"pyalgotrad/testing/#previously","title":"Previously...","text":"

You have uploaded your strategy to the AlgoBulls platform.

"},{"location":"pyalgotrad/testing/#now","title":"Now...","text":"

Using the uploaded strategy, you can now try:

"},{"location":"pyalgotrad/testing/#before-you-start","title":"Before you start...","text":"

Open a Jupyter Notebook.

The steps you will follow are:

  1. Establish a connection to the AlgoBulls Platform.
  2. Display all Strategies you have in your account.
  3. Select the strategy.
  4. Optionally, print the strategy once.
  5. Select instrument(s).
  6. Submit/Run a Backtest, Paper Trade or Real Trade job.
  7. Check Job Status.
  8. Fetch Logs (even while the job is running).
  9. Fetch Reports. (PnL, Statistics, Order History)
"},{"location":"pyalgotrad/testing/#lets-start","title":"Let's Start...","text":"

Run the following code snippets into the Jupyter Notebook one by one (or all together).

"},{"location":"pyalgotrad/testing/#create-a-new-strategy-file","title":"Create a new strategy file","text":"

eg: strategy_<unique_code_if_needed>_options_ema_crossover.py Make sure this strategy file is in the same folder as the jupyter notebook.

Coding Conventions

How to Code ?

To know more on how to code trading strategies and understand their format, click here. We have in detail explanation for regular strategies as well as options strategies

"},{"location":"pyalgotrad/testing/#import-statements","title":"Import statements","text":"
from pyalgotrading.algobulls import AlgoBullsConnection\nfrom datetime import datetime as dt\nfrom pyalgotrading.constants import *\n
"},{"location":"pyalgotrad/testing/#establish-a-connection-to-the-algobulls-platform","title":"Establish a connection to the AlgoBulls Platform","text":"

algobulls_connection = AlgoBullsConnection()\nalgobulls_connection.get_authorization_url()\n
The output of the above step is:

Please login to this URL with your AlgoBulls credentials and get your developer access token: https://app.algobulls.com/user/login

Get Developer Key

You will need to log in to your AlgoBulls account and fetch the access token from: (See How) Settings -> General -> Developer Options

Once you have the access token, set it in the code as shown here:

algobulls_connection.set_access_token('4365817b795770ea31040a21ad29c8e78b63ad88')\n

Replace the token you have copied with the token in the code above.

"},{"location":"pyalgotrad/testing/#display-all-strategies-in-your-account","title":"Display all strategies in your account","text":"
all_strategies = algobulls_connection.get_all_strategies()\nall_strategies\n

An example of the output will be:

"},{"location":"pyalgotrad/testing/#select-the-strategy","title":"Select the strategy","text":"

Select the last entry of the strategyCode column and display it.

strategy_code = all_strategies.iloc[-1]['strategyCode']\nstrategy_code\n

"},{"location":"pyalgotrad/testing/#print-your-strategy-code","title":"Print your Strategy code","text":"

You can print your strategy code once to verify if this is the correct code. This step is optional.

strategy_details1 = algobulls_connection.get_strategy_details(strategy_code)\nprint(strategy_details1)\n
"},{"location":"pyalgotrad/testing/#search-for-instruments-based-on-a-search-query","title":"Search for instruments (based on a search query)","text":"

Now display a few instruments with some keyword. The example below uses 'SBIN' as the keyword.

instruments = algobulls_connection.search_instrument('SBIN')\ninstruments\n
"},{"location":"pyalgotrad/testing/#select-an-instrument","title":"Select an instrument","text":"

From the output, select the instrument on which you wish to test your strategy. For this example, select the first one.

instrument = instruments[0]['value']\ninstrument\n

"},{"location":"pyalgotrad/testing/#submit-a-job","title":"Submit a Job","text":"

Delete previous trades

algobulls_connection.delete_previous_trades(strategy=strategy)\n

Set the parameters for the strategy

parameters={\n    'timeperiod1': 5,\n    'timeperiod2': 12\n}\n

vendor_details = {\n    'brokerName': '<VENDOR_NAME>',\n    'credentialParameters': {\n        'api_key': '<API_KEY>',\n        'secret_key': '<SECRET_KEY>'\n    }\n}\n
broking_details = {\n    'brokerName': '<BROKER_NAME>',\n    'credentialParameters': {\n        'user_id': '<USER_ID>',\n        'api_key': '<API_KEY>',\n        'password': '<PASSWORD>'\n    }\n}\n

Click on each of the tabs to see the relevant code snippet.

BacktestingPaper TradingReal Trading
algobulls_connection.backtest(\n        strategy=strategy_code,         # strategy code\n        start='2020-7-1 09:15 +0530',   # start date-time of strategy ('YYYY-MM-DD HH:MM z')\n        end='2020-7-7 15:30 +0530',     # end date-time of strategy ('YYYY-MM-DD HH:MM z')\n        instruments='NSE:SBIN',         # name of the instrument\n        lots=1,                         # number of lots per trade\n        parameters=parameters,          # parameters required for the strategy\n        candle='15 minutes',            # candle size eg : '1 Day', '1 hour', '3 minutes'\n        delete_previous_trades=True,    # delete the previous trades for papertrading (default is true),\n        initial_funds_virtual=10000,    # virtual funds allotted before the paper trading starts (default is 1e9)\n        vendor_details=vendor_details   # vendor's details for authentication and verification \n)\n
algobulls_connection.papertrade(\n        strategy=strategy_code,         # strategy code\n        start='09:15 +0530',            # start time of strategy (HH:MM z)     \n        end='15:30 +0530',              # end time of strategy (HH:MM z)\n        instruments='NSE:SBIN',         # name of the instrument\n        lots=1,                         # number of lots per trade\n        parameters=parameters,          # parameters required for the strategy\n        candle='15 minutes',            # candle size eg : '1 Day', '1 hour', '3 minutes'\n        delete_previous_trades=True,    # delete the previous trades for papertrading (default is true)\n        initial_funds_virtual=10000,    # virtual funds allotted before the paper trading starts (default is 1e9)\n        vendor_details=vendor_details   # vendor's details for authentication and verification \n)\n
algobulls_connection.realtrade(\n        strategy=strategy_code,          # strategy code\n        start='09:15 +0530',             # start time of strategy (HH:MM z)     \n        end='15:30 +0530',               # end time of strategy (HH:MM z)\n        instruments='NSE:SBIN',          # name of the instrument\n        lots=1,                          # number of lots per trade\n        parameters=parameters,           # parameters required for the strategy\n        candle='15 minutes',             # candle size eg : '1 Day', '1 hour', '3 minutes'\n        broking_details=broking_details  # broker's details for authentication and verification \n)\n
"},{"location":"pyalgotrad/testing/#fetch-job-status","title":"Fetch Job Status","text":"

Click on each of the tabs to see the relevant code snippet. There are 4 stages of your strategy execution : STARTING, STARTED, STOPPING and STOPPED

BacktestingPaper TradingReal Trading
algobulls_connection.get_backtesting_job_status(strategy_code)\n
algobulls_connection.get_papertrading_job_status(strategy_code)\n
algobulls_connection.get_realtrading_job_status(strategy_code)\n

You can stop a submitted job anytime.

"},{"location":"pyalgotrad/testing/#stop-a-job","title":"Stop a Job","text":"

Click on each of the tabs to see the relevant code snippet.

BacktestingPaper TradingReal Trading
algobulls_connection.stop_backtesting_job(strategy_code)\n
algobulls_connection.stop_papertrading_job(strategy_code)\n
algobulls_connection.stop_realtrading_job(strategy_code)\n

You can fetch the logs in the middle of a job to monitor the progress.

"},{"location":"pyalgotrad/testing/#fetch-logs","title":"Fetch logs","text":"

Logging Tip

Click on each of the tabs to see the relevant code snippet.

BacktestingPaper TradingReal Trading
logs = algobulls_connection.get_backtesting_logs(\n            strategy_code,                              # strategy code \n            display_progress_bar=True,                  # (default=True) to track the execution on progress bar as your strategy is executed\n            print_live_logs: True                       # (default=False) to print the live logs as your strategy is executed\n        )\nprint(logs)\n
logs = algobulls_connection.get_papertrading_logs(\n            strategy_code,                              # strategy code \n            display_progress_bar=True,                  # (default=True) to track the execution on progress bar as your strategy is executed\n            print_live_logs: True                       # (default=True) to print the live logs as your strategy is executed\n        )\nprint(logs)\n
logs = algobulls_connection.get_realtrading_logs(\n            strategy_code,                              # strategy code \n            display_progress_bar=True,                  # (default=True) to track the execution on progress bar as your strategy is executed\n            print_live_logs: True                       # (default=True) to print the live logs as your strategy is executed\n        )\nprint(logs)\n

You can fetch the PnL report, statistics and order history for a job.

"},{"location":"pyalgotrad/testing/#fetch-pnl-reports","title":"Fetch PnL Reports","text":"

Click on each of the tabs to see the relevant code snippet.

Please Note

Make sure that strategy's execution status is at STOPPED stage before generating PnL reports

BacktestingPaper TradingReal Trading
algobulls_connection.get_backtesting_report_pnl_table(\n        strategy_code,                      # strategy code\n        show_all_rows=True,                 # default=True         \n        force_fetch=True,                   # pnl data is saved locally once fetched, to update the locally fetched data, make this parameter True\n        country='USA',                      # country of the exchange that was used while starting the job ('India' or 'USA')\n        broker_commission_percentage: 1     # Percentage of broker commission per trade\n        broker_commission_price: 0.2        # Broker fee per trade\n        slippage_percent: 3                 # Slippage percentage value\n)\n
algobulls_connection.get_papertrading_report_pnl_table(\n        strategy_code,                      # strategy code\n        show_all_rows=True,                 # default=True         \n        force_fetch=True,                   # pnl data is saved locally once fetched, to update the locally fetched data, make this parameter True\n        country='USA',                      # country of the exchange that was used while starting the job ('India' or 'USA')\n        broker_commission_percentage: 1     # Percentage of broker commission per trade\n        broker_commission_price: 0.2        # Broker fee per trade\n        slippage_percent: 3                 # Slippage percentage value\n)\n
algobulls_connection.get_realtrading_report_pnl_table(\n        strategy_code,              # strategy code\n        show_all_rows=True,         # default=True         \n        force_fetch=True,           # pnl data is saved locally once fetched, to update the locally fetched data, make this parameter True\n        country='USA',              # country of the exchange that was used while starting the job ('India' or 'USA')\n)\n

To know more about slippage and brokerage parameters click here

"},{"location":"pyalgotrad/testing/#fetch-report-statistics","title":"Fetch Report Statistics","text":"

Click on each of the tabs to see the relevant code snippet.

Analytics Tips

You can view your analytics on the python build page as well, simply log inside your AlgoBulls Account, and look for your Strategy in Python Build -> My Coded Strategies

BacktestingPaper TradingReal Trading
algobulls_connection.get_backtesting_report_statistics(\n    strategy_code,          # strategy code\n    report='full',          # format of the report\n    html_dump=True          # save report as html file\n)\n
algobulls_connection.get_papertrading_report_statistics(\n    strategy_code,          # strategy code\n    report='full',          # format of the report\n    html_dump=True          # save report as html file\n)\n
algobulls_connection.get_realtrading_report_statistics(\n    strategy_code,          # strategy code\n    report='full',          # format of the report\n    html_dump=True          # save report as html file\n)\n
"},{"location":"pyalgotrad/testing/#generate-statistics-from-external-csv","title":"Generate Statistics from External CSV","text":"

Make sure your csv has the columns names as \"net_pnl\" and \"entry_timestamp\". The \"net_pnl\" column will contain the net profit and loss of every trade and its respective entry time will be stored in \"entry_timestamp\".

connection.get_report_statistics(file_path=\"testing_file.csv\", initial_funds=3000)\n

"},{"location":"pyalgotrad/testing/#fetch-order-history","title":"Fetch Order History","text":"

Click on each of the tabs to see the relevant code snippet.

BacktestingPaper TradingReal Trading
order_history = algobulls_connection.get_backtesting_report_order_history(strategy_code)\nprint(order_history)\n
order_history = algobulls_connection.get_papertrading_report_order_history(strategy_code)\nprint(order_history)\n
order_history = algobulls_connection.get_realtrading_report_order_history(strategy_code)\nprint(order_history)\n

Note

"},{"location":"pyalgotrad/testing/#whats-next","title":"What's Next...","text":"

You can now explore more by creating and uploading more complex strategies.

You can also check out the Analytics, to understand more about the returns and analyze your strategy based on the analytics report.

"},{"location":"pyalgotrad/upload/","title":"Upload your Strategy","text":""},{"location":"pyalgotrad/upload/#previously","title":"Previously...","text":"

You have created a strategy by:

OR

"},{"location":"pyalgotrad/upload/#now","title":"Now...","text":"

You are now ready to upload your strategy into your AlgoBulls account for Backtesting, Paper Trading and/or Real Trading.

"},{"location":"pyalgotrad/upload/#before-you-start","title":"Before you start...","text":""},{"location":"pyalgotrad/upload/#lets-start","title":"Let's Start...","text":"

Run the following code snippets into the Jupyter Notebook one by one (or all together).

"},{"location":"pyalgotrad/upload/#import-statements","title":"Import statements","text":"
import inspect\nfrom pyalgotrading.algobulls import AlgoBullsConnection\n
"},{"location":"pyalgotrad/upload/#establish-a-connection-to-the-algobulls-platform","title":"Establish a connection to the AlgoBulls Platform","text":"

algobulls_connection = AlgoBullsConnection()\nalgobulls_connection.get_authorization_url()\n
The output of the above step is:

Please login to this URL with your AlgoBulls credentials and get your developer access token: https://app.algobulls.com/user/login

Get Developer Key

You will need to log in to your AlgoBulls account and fetch the access token from: (See How) Settings -> General -> Developer Options

Once you have the access token, set it in the code as shown here:

algobulls_connection.set_access_token('4365817b795770ea31040a21ad29c8e78b63ad88')\n
Replace the token you have copied with the token in the code above.

"},{"location":"pyalgotrad/upload/#print-your-strategy-code","title":"Print your Strategy code","text":"

You can print your strategy code once to verify if this is the correct code before uploading it to the platform. This step is optional.

print(inspect.getsource(StrategySMARegularOrder))\n

"},{"location":"pyalgotrad/upload/#upload-your-strategy_1","title":"Upload your Strategy","text":"

Upload your strategy as shown in the code below.

algobulls_connection.create_strategy(StrategySMARegularOrder)\n

"},{"location":"pyalgotrad/upload/#re-upload-your-strategy-after-modifications","title":"Re-upload your Strategy after modifications","text":"

If you are re-uploading your strategy after some changes, then use the overwrite switch as shown here.

algobulls_connection.create_strategy(StrategySMARegularOrder, overwrite=True)\n

"},{"location":"pyalgotrad/upload/#whats-next","title":"What's Next...","text":"

You are now ready to test your uploaded strategy and perform Backtesting, Paper Trading and/or Real Trading with it.

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/","title":"Options Strategy Structure","text":"

Links

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#1-initial-steps","title":"1. Initial steps","text":""},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#naming-a-class","title":"Naming a Class","text":"eg: For the above strategy name the class name would be:
StrategyOptionsEMACrossover(StrategyOptionsBaseV2)\n

Coding Conventions

* Make a class with the same name as the file name\n* Make sure the first letter of each word is in uppercase and the initials should be in uppercase as well.\n* If the class name includes indicator names like EMA, SMA, and VWAP the name should be in uppercase in the class name but not in the file name.\n* Every options strategy is a child class of the StrategyOptionsBaseV2 class.\n
"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#naming-your-strategy","title":"Naming your Strategy","text":"

This name will be displayed in your My Coded Strategies in Python Build Web, and it will also be the strategy_name when you are fetching all strategies in pyalgotrading. Inside your strategy class, you can write your first parameter as name.

name = 'options_ema_crossover'\n

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#2-init-method","title":"2. Init method","text":"

This method gets called only once when the strategy is started.

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#strategy-info","title":"Strategy info","text":"

In the init method add the line given below

super().__init__(*args, **kwargs)\n

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#parameter-creation","title":"Parameter creation","text":"

Next, we assign the parameter values to the class variables of the same name as the parameters but in the lowercase format as shown below:

eg:

self.fresh_order_candle = self.strategy_parameters['FRESH_ORDER_CANDLE']\nself.start_time_hours = self.strategy_parameters['START_TIME_HOURS']\nself.start_time_minutes = self.strategy_parameters['START_TIME_MINUTES']\nself.end_time_hours = self.strategy_parameters['END_TIME_HOURS']\nself.end_time_minutes = self.strategy_parameters['END_TIME_MINUTES']\nself.no_of_strikes_away_ce = self.strategy_parameters['NO_OF_STRIKES_AWAY_CE']\nself.no_of_strikes_away_p = self.strategy_parameters['NO_OF_STRIKES_AWAY_PE']\nself._strike_direction_ce = self.strategy_parameters['STRIKES_DIRECTION_CE']\nself._strike_direction_pe = self.strategy_parameters['STRIKES_DIRECTION_PE']\nself.ema_period_one = self.strategy_parameters['EMA_PERIOD_ONE']\nself.ema_period_two = self.strategy_parameters['EMA_PERIOD_TWO']\nself.target_percentage = self.strategy_parameters['TARGET_PERCENTAGE']\nself.stoploss_percentage = self.strategy_parameters['STOPLOSS_PERCENTAGE']\nself.stoploss_range = self.strategy_parameters['STOPLOSS_RANGE']\nself.stoploss_order_count_allowed = self.strategy_parameters['STOPLOSS_ORDER_COUNT_ALLOWED']\n

Note

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#start-time-and-end-time-creation","title":"Start time and End time creation","text":"

Adding Start and End time is useful when you want to define a timerange between which the strategy will be running each day. Add the below code to calculate the strategy start time and end time, from the strategy_parameters.

try:

    self.candle_start_time = time(hour=self.start_time_hours, minute=self.start_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting start hours and minutes... EXITING')\n    raise SystemExit\n
try:
    self.candle_end_time = time(hour=self.end_time_hours, minute=self.end_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting end time hours and minutes... EXITING')\n    raise SystemExit\n

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#strategy-variables","title":"Strategy variables","text":"

We create our own strategy variables other than the strategy parameter variables which will be used throughout the strategy.

eg:

self.main_order = None            # We save the entry order in this variable\nself.stoploss_order = None        # We save the corresponding stoploss exit order of the entry order in this variable\n
We initialize the variables with a None value. !!! Note There could be more strategy variables required as per the strategy requirement.

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#3-initialize-method","title":"3. Initialize method","text":"

Unlike the init method, this method gets called every day at the beginning of the day once the strategy is started.

Here the strategy variables that were initialized as None are again defined as dictionaries/lists except for the self.order_tag_manager. Create a reference for OrderTagManager as shown below:

self.order_tag_manager = OrderTagManager\n
"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#4-ordertagmanager","title":"4. OrderTagManager","text":"

The self.order_tag_manager is used to store/remove the entry/exit orders. The self.order_tag_manager has the following methods:

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#add_order","title":"add_order","text":"
self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#get_orders","title":"get_orders","text":"

eg:

self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#remove_tags","title":"remove_tags","text":"

eg:

self.order_tag_manager.remove_tags(tags=entry_key)\n

Here the entry_key tag is removed from the OrderTagManager.

Note

When the tag is removed the order objects stored in that tag are also removed but the same order objects would still be present in order tags.

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#remove_order","title":"remove_order","text":"

eg:

self.order_tag_manager.remove_order(main_order)\n
Here the main_order order object is removed from the OrderTagManager.

Note

The order object will be removed from all the tags ta

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#get_internals","title":"get_internals","text":"
Returns the values i.e. both the entry and exit orders stored inside the tags list.\n
"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#5-child-instruments-calculation","title":"5. Child instruments calculation","text":""},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#get_ltp","title":"get_ltp","text":"

Fetch the ltp of the base instrument (instrument set while executing strategy)

ltp = self.broker.get_ltp(self.underlying_instrument)\n

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#options_instruments_set_up_local","title":"options_instruments_set_up_local","text":"

Get the ATM ITM and OTM lists of the child instrument based on the LTP

self.options_instruments_set_up_local(self.underlying_instrument, tradingsymbol_suffix, ltp)\n

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#get_child_instrument_details","title":"get_child_instrument_details","text":"

Select a child instrument from the lists of ATM, ITM, and OTM based on the strike direction and no of strikes given for the child instrument

child_instrument = self.get_child_instrument_details(self.underlying_instrument, tradingsymbol_suffix, strike_direction, no_of_strikes)\n

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#6-entry-methods","title":"6. Entry Methods","text":""},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry","text":""},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#strategy_enter_position","title":"strategy_enter_position","text":""},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#7-exit-methods","title":"7. Exit Methods","text":""},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit","text":""},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#strategy_exit_position","title":"strategy_exit_position","text":""},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#8-other-common-methods","title":"8. Other common methods","text":"

There are other methods that are used in the strategy:

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#check_and_place_stoploss_order","title":"check_and_place_stoploss_order","text":"

This method is called in the strategy_select_instruments_for_exit when our entry order is open, and we want to place a stoploss exit order for the same.

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#set_all_none","title":"set_all_none","text":"

This method is called in the strategy_exit_position when our entry order has exited, and we want to remove the order object from the self.main_order variable.

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#options_instruments_set_up_local_1","title":"options_instruments_set_up_local","text":"

This method is called in the strategy_select_instruments_for_entry to fetch the ATM, ITM, and OTM lists of the child instruments based on the LTP of the base instrument.

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#get_child_instrument_details_1","title":"get_child_instrument_details","text":"

This method is called in the strategy_select_instruments_for_entry to fetch a single child instrument based on the no of strikes and strike direction.

"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#9-cleanup","title":"9. Cleanup","text":"
  1. Add comments and docstrings wherever possible to improve code readability.
  2. Once the strategy is completed you can optimize imports, give proper indentation and proper formatting to the strategy code and remove unwanted imports, variables, and methods before delivering the code.
"},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#10-check-out-our-docs-for-developed-options-strategies","title":"10. Check out our docs for developed Options strategies","text":"

Tip

To know more about a strategy from our given template, simply check the first line of comment in the code of that specific strategy.

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/","title":"Regular Strategy Structure","text":"

Links

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#1-initial-steps","title":"1. Initial steps","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#naming-a-class","title":"Naming a Class","text":"eg: For the above strategy name the class name would be:
StrategyFuturesEMACrossover(StrategyBase)\n

Coding Conventions

* Make a class with the same name as the file name\n* Make sure the first letter of each word is in uppercase and the initials should be in uppercase as well.\n* If the class name includes indicator names like EMA, SMA, and VWAP the name should be in uppercase in the class name but not in the file name.\n* Every strategy is a child class of the StrategyBase class.\n
"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#naming-your-strategy","title":"Naming your Strategy","text":"

This name will be displayed in your My Coded Strategies in Python Build Web, and it will also be the strategy_name when you are fetching all strategies in pyalgotrading. Inside your strategy class, you can write your first parameter as name.

name = 'futures_ema_crossover'\n

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#2-init-method","title":"2. Init method","text":"

This method gets called only once when the strategy is started.

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#strategy-info","title":"Strategy info","text":"

In the init method add the line given below

super().__init__(*args, **kwargs)\n

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#parameter-creation","title":"Parameter creation","text":"

Next we assign the parameter values to the class variables of the same name as the parameters but in the lowercase format, as shown below:

eg:

self.fresh_order_candle = self.strategy_parameters['FRESH_ORDER_CANDLE']\nself.start_time_hours = self.strategy_parameters['START_TIME_HOURS']\nself.start_time_minutes = self.strategy_parameters['START_TIME_MINUTES']\nself.end_time_hours = self.strategy_parameters['END_TIME_HOURS']\nself.end_time_minutes = self.strategy_parameters['END_TIME_MINUTES']\nself.ema_period_one = self.strategy_parameters['EMA_PERIOD_ONE']\nself.ema_period_two = self.strategy_parameters['EMA_PERIOD_TWO']\nself.target_percentage = self.strategy_parameters['TARGET_PERCENTAGE']\nself.stoploss_percentage = self.strategy_parameters['STOPLOSS_PERCENTAGE']\nself.stoploss_range = self.strategy_parameters['STOPLOSS_RANGE']\nself.stoploss_order_count_allowed = self.strategy_parameters['STOPLOSS_ORDER_COUNT_ALLOWED']\n

Note

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#start-time-and-end-time-creation","title":"Start time and End time creation","text":"

Adding Start and End time is useful when you want to define a timerange between which the strategy will be running each day. Add the below code to calculate the strategy start time and end time, from the strategy_parameters. try:

    self.candle_start_time = time(hour=self.start_time_hours, minute=self.start_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting start hours and minutes... EXITING')\n    raise SystemExit\n
try:
    self.candle_end_time = time(hour=self.end_time_hours, minute=self.end_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting end time hours and minutes... EXITING')\n    raise SystemExit\n

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#strategy-variables","title":"Strategy variables","text":"

We create our own strategy variables other than the strategy parameter variables which will be used throughout the strategy.

eg: self.order_tag_manager = None

We initialize the variables with a None value.

Note

There could be more strategy variables required as per the strategy requirement.\n
"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#3-initialize-method","title":"3. Initialize method","text":"

Unlike the init method, this method gets called every day at the beginning of the day once the strategy is started.

Here the strategy variables that were initialized as None are again defined as dictionaries/lists except for the self.order_tag_manager. Create a reference for OrderTagManager as shown below:

self.order_tag_manager = OrderTagManager\n
"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#4-ordertagmanager","title":"4. OrderTagManager","text":"

The self.order_tag_manager is used to store/remove the entry/exit orders. The self.order_tag_manager has the following methods:

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#add_order","title":"add_order","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#get_orders","title":"get_orders","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#remove_tags","title":"remove_tags","text":"

Note

When the tag is removed the order objects stored in that tag are also removed but the same order objects would still be present in the order tags.

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#remove_order","title":"remove_order","text":"
self.order_tag_manager.remove_order(main_order)\n

Here the main_order order object is removed from the OrderTagManager.

Note

The order object will be removed from all the tags ta

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#get_internals","title":"get_internals","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#5-entry-methods","title":"5. Entry Methods","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#strategy_enter_position","title":"strategy_enter_position","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#6-exit-methods","title":"6. Exit Methods","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit:","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#strategy_exit_position","title":"strategy_exit_position","text":""},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#7-other-common-methods","title":"7. Other common methods","text":"

There are other methods that are used in the strategy:

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#check_and_place_stoploss_order","title":"check_and_place_stoploss_order","text":"

This method is called in the strategy_select_instruments_for_exit when our entry order is open, and we want to place a stoploss exit order for the same.

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#set_all_none","title":"set_all_none","text":"

This method is called in the strategy_exit_position when our entry order has exited, and we want to remove the order object from the self.main_order variable.

"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#8-cleanup","title":"8. Cleanup","text":"
  1. Add comments and docstrings wherever possible to improve code readability.
  2. Once the strategy is completed you can optimize imports, give proper indentation and proper formatting to the strategy code and remove unwanted imports, variables, and methods before delivering the code.
"},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#10-check-out-our-docs-for-developed-regular-strategies","title":"10. Check out our docs for developed Regular strategies","text":"

Tip

To know more about a strategy from our given template, simply check the first line of comment in the code of that specific strategy.

"},{"location":"pyalgotrad/strategy_guides/structure/","title":"Code Structure of Strategy","text":"

Coding Prerequisites

"},{"location":"pyalgotrad/strategy_guides/structure/#methods","title":"Methods","text":""},{"location":"pyalgotrad/strategy_guides/structure/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry()","text":"

This function helps you choose which trading instruments you want your strategy to work with. The system will use this function to go through each instrument one by one, at each candle's time. You get to write code that decides whether to place an order for a specific instrument or not.

"},{"location":"pyalgotrad/strategy_guides/structure/#strategy_enter_position","title":"strategy_enter_position()","text":"

This function is where you can place orders for the instruments you selected earlier. It's executed for each instrument you picked in the previous function.

"},{"location":"pyalgotrad/strategy_guides/structure/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit()","text":"

After you've entered a position for an instrument, this function is called for each of those instruments at each candle interval. You can use it to decide whether an instrument should be exited from the position.

"},{"location":"pyalgotrad/strategy_guides/structure/#strategy_exit_position","title":"strategy_exit_position()","text":"

In this function, you can close or exit positions for the instruments you marked for exiting in the previous function. It's done instrument by instrument.

"},{"location":"pyalgotrad/strategy_guides/structure/#supporting-methods","title":"Supporting Methods","text":"

You have the following supporting methods:

"},{"location":"pyalgotrad/strategy_guides/structure/#init","title":"init()","text":"

This method is like a starter for your strategy. It checks if the values you give it make sense and sets up some useful information for your strategy to use.

"},{"location":"pyalgotrad/strategy_guides/structure/#initialize","title":"initialize()","text":"

This method is called when your strategy begins, both at the very start and at the beginning of each trading day. It's like setting up your strategy's workspace and giving your tools a starting position.

"},{"location":"pyalgotrad/strategy_guides/structure/#name","title":"name()","text":"

This method gives your strategy a special name. It's like giving your strategy a unique nickname.

"},{"location":"pyalgotrad/strategy_guides/structure/#versions_supported","title":"versions_supported()","text":"

This method lets you specify which version of the AlgoBulls Platform your strategy works well with. It's like saying, \"My strategy is ready for this specific version of the platform.\"

"},{"location":"pyalgotrad/strategy_guides/structure/#utility-functions","title":"Utility Functions","text":"

You have the following utility function to be used in this strategy :

Links

"},{"location":"pyalgotrad/strategy_guides/structure/#get_crossover_value","title":"get_crossover_value()","text":"This handy function calculates something called the \"crossover value\" for you. It's like having a calculator that figures out this specific value for your strategy."},{"location":"pyalgotrad/strategy_guides/structure/#flowchart","title":"Flowchart","text":"

Once you create your own strategy or use a ready strategy from the pyalgostrategypool package, this is how it works internally on the AlgoBulls Core Trading Engine.

"},{"location":"python_build/pyalgotrading_analytics/","title":"Pyalgotrading Analytics","text":""},{"location":"python_build/pyalgotrading_analytics/#metric-values-and-statistics","title":"Metric Values and Statistics","text":""},{"location":"python_build/pyalgotrading_analytics/#cumulative-returns","title":"Cumulative Returns","text":""},{"location":"python_build/pyalgotrading_analytics/#end-of-year-returns-eoy","title":"End of Year Returns (EoY)","text":""},{"location":"python_build/pyalgotrading_analytics/#distributions-of-monthly-returns-histogram","title":"Distributions of Monthly Returns (Histogram)","text":""},{"location":"python_build/pyalgotrading_analytics/#daily-returns","title":"Daily Returns","text":""},{"location":"python_build/pyalgotrading_analytics/#rolling-volatility-6-months","title":"Rolling Volatility (6 months)","text":""},{"location":"python_build/pyalgotrading_analytics/#rolling-sharpe-6-months","title":"Rolling Sharpe (6 months)","text":""},{"location":"python_build/pyalgotrading_analytics/#rolling-sortino-6-months","title":"Rolling Sortino (6 months)","text":""},{"location":"python_build/pyalgotrading_analytics/#worst-5-drawdown-periods","title":"Worst 5 Drawdown Periods","text":""},{"location":"python_build/pyalgotrading_analytics/#underwater-plot","title":"Underwater Plot","text":""},{"location":"python_build/pyalgotrading_analytics/#monthly-returns-heatmap","title":"Monthly Returns (Heatmap)","text":""},{"location":"python_build/python-build-code-gen-ai/","title":"Code Using AI","text":"

If you have creative ideas in your mind and want to design a algotrading strategy but you are new at coding, don't worry, we have got it covered using our Python Build's Create Using AI feature which will help you to create trading strategies seamlessly.

Tip

You can check here on how to get your Chat-GPT API key

"},{"location":"python_build/python-build-code-gen-ai/#set-your-gen-ai-api-keys-and-model","title":"Set your Gen-AI API keys and Model","text":"
  1. Once you have retrieved the API key, you need to paste it in the input box for API keys.
  2. Select the model of AI from the drop-down menu below.
  3. Click on the Save button to save your key and model and establish the connection.

"},{"location":"python_build/python-build-code-gen-ai/#enter-your-prompts","title":"Enter your Prompts","text":"
  1. On the left hand side you can see the previous sessions and chat history
  2. Right below you will see a button for Prompts Library which has all the sample prompts that would generate wonderful strategies, you can pick any of them, if needed you can even tailor those prompts and use them.
  3. To start a new session click on New Session
  4. Enter your prompt or select from the sample prompts or take one prompt from the Prompts Library
  5. Click on the send button to start generating

Please Note, It takes some time to generate the strategy as it processes a lot of data, so please be patient

Please Note

Direct response code from gen-ai may not be 100% accurate, you will have to make sure that pythonic errors are not present. Also dont forget to configure your strategy parameters before executing the code.

Modify your code ?

To know more on how to code trading strategies and understand their format, click here. We also have in detail explanation for regular strategies as well as options strategies.

"},{"location":"python_build/python-build-code-gen-ai/#save-your-strategy","title":"Save your Strategy","text":"
  1. Once it gives you the strategy you can ask it to make more changes as per your need or you can save it directly.
  2. To save, click on the top right corner of the code, you can even copy the code if you want.
  3. Once you save it, it will redirect you to a new page where you have save your strategy and update its configuration parameters from the parameter settings.
  4. All your saved strategies can be viewed in My Coded Strategies section in Python Build.

What's Next ?

You can check out our strategy code structure and their respective formats for options and equity. Once you have verified that your strategy has no pythonic errors then you can move on to Configure and Execute your Strategy.

"},{"location":"python_build/python-build-code-new/","title":"Code New Strategy","text":""},{"location":"python_build/python-build-code-new/#how-to-code-a-new-strategy","title":"How to code a new strategy?","text":"

If you want to create your own strategy, click on the + Sign in the Code New Strategy option under the My Coded Strategies section.

A new blank code editor will open, allowing you to start coding your new strategy. You can check out the basic building blocks of a strategy here to help you with your code structure. After you've finished coding, click Save to save this strategy in the My Coded Strategies section.

How to Code ?

To know more on how to code trading strategies and understand their format, click here. We also have in detail explanation for regular strategies as well as options strategies.

Next, you need to configure the strategy\u2019s parameters by clicking on the settings symbol in the top right corner of the code editor. In this section you can add, view & edit the strategy parameters.

To test the behavior and performance of the strategy, click on Save & Start and follow the directions given earlier. The performance of the strategy will soon be available in the Results section.

You can rename a strategy by clicking the edit symbol beside the strategy name.

What's Next ?

You can check out our strategy code structure and their respective formats for options and equity. Once you have verified that your strategy has no pythonic errors then you can move on to Configure and Execute your Strategy.

"},{"location":"python_build/python-build-code-ready-templates/","title":"Code Ready Templates","text":""},{"location":"python_build/python-build-code-ready-templates/#how-to-code-strategies-using-ready-templates","title":"How to code strategies using Ready Templates?","text":"

Select a template that you would like to modify from the Ready Template section. To view all the ready-to-use templates, click on More.

Click on the Code button placed in the bottom right corner of the selected template to view the strategy code.

You should now see the code editor, where you can start modifying the code as required.

Modify your code ?

To know more on how to code trading strategies and understand their format, click here. We also have in detail explanation for regular strategies as well as options strategies.

To save the strategy, click the Save button. This strategy will be added to your list of My coded strategies.

What's Next ?

You can check out our strategy code structure and their respective formats for options and equity. Once you have verified that your strategy has no pythonic errors then you can move on to Configure and Execute your Strategy.

"},{"location":"python_build/python-build-config-parameters/","title":"Configure and Execute your Strategy","text":"

To effectively use pyalgotrading and make the most of your trading strategy, it's essential to be familiar with some frequently used stock market terminologies. Let's go over these terms before diving into configuring your strategy parameters.

  1. Exchange: An exchange is a marketplace where various financial instruments like securities, commodities, and derivatives are traded. Examples include NSE (National Stock Exchange), BSE (Bombay Stock Exchange), NYSE (New York Stock Exchange), and NASDAQ.
  2. Instruments: Instruments are the specific assets or securities traded on these exchanges. These include stocks like AAPL (Apple Inc.), TSLA (Tesla, Inc.), TATAMOTORS (Tata Motors Limited), and SBIN (State Bank of India).
  3. Candlestick Charts: Candlestick charts are commonly used in stock market analysis. They represent the opening and closing prices of a stock or asset over regular time intervals, which are often referred to as \"candle size.\"
  4. Intraday Trading: Intraday trading, also known as day trading, involves buying and selling stocks within the same trading day.
  5. Delivery Trading: Delivery trading is a type of trading where traders buy shares and hold them for an extended period, which can range from a few days to several months or even years.
  6. Position: A position refers to the amount of a security or asset owned (or sold short) by an individual or entity. Traders take positions when they make buy or sell orders.
  7. Order: An order is an instruction to buy or sell a security or asset on a trading venue, such as a stock market or cryptocurrency exchange.
  8. Crossover: A crossover occurs when two signal lines intersect. Signal lines can be various indicators like moving averages, Relative Strength Index (RSI), Volume Weighted Averages, etc. Crossovers are often used to trigger and place orders. Now that we've covered these essential terms, let's move on to configuring your trading strategy parameters.
"},{"location":"python_build/python-build-config-parameters/#configure-strategy-parameters","title":"Configure Strategy Parameters","text":"

You can configure the strategy\u2019s parameters by clicking on the settings symbol in the top right corner of the code editor. In this section, you can view a strategy\u2019s parameters or edit these parameters too.

There 4 sections for configuring your parameters:

"},{"location":"python_build/python-build-config-parameters/#instruments","title":"Instruments","text":""},{"location":"python_build/python-build-config-parameters/#strategy-settings","title":"Strategy Settings","text":""},{"location":"python_build/python-build-config-parameters/#order-settings","title":"Order Settings","text":""},{"location":"python_build/python-build-config-parameters/#user-parameters","title":"User Parameters","text":"

Once Strategy and User Parameters are configured, you can follow these steps to execute your strategy.

"},{"location":"python_build/python-build-config-parameters/#follow-these-simple-steps-to-test-the-strategys-performance","title":"Follow these simple steps to test the strategy's performance","text":"

Step 1

After clicking Save & Start, a pop-up window will appear.

Step 2

In the customizations section, choose Backtesting to backtest or Paper Trading to Paper Trade a strategy.

Select the duration option in the customizations section. Add the desired date and time, as well as the quantity/lots. In Backtesting, you will need to put the start date and end date along with time.

In Paper Trading, you only need to add the start and end time.

Step 3

In the Strategy Configuration section, you can check the parameters added or modified by you.

Step 4

To begin testing the strategy, click on Execute.

Step 5

Go to the Analytics section to see the returns and performance of the strategy visualized.

Note:

The use of Paper Trading would be available from Monday - Friday (excluding exchange's holidays) from 9 AM to 16:00 PM. You can code your strategy & analyze the strategy results 24x7.

Go to the Logs section to see the step-by-step execution of the strategy in logs.

You can rename a strategy by clicking the edit symbol beside the strategy name.

"},{"location":"python_build/python-build-getstarted/","title":"Setup your Workspace","text":""},{"location":"python_build/python-build-getstarted/#how-to-get-started-with-python-build","title":"How to get started with Python Build?","text":"

To start developing your own strategy, you must first activate a plan from the Pricing section. Select the Developers tab in the Pricing section and select a plan of your choice. There is currently one developer plan available:

After selecting your plan, you will be able to begin coding. You can either edit the preloaded Ready templates or use the My Coded Strategies section to create your own strategies.

"},{"location":"python_build/python-build-introduction/","title":"Python Build Web","text":""},{"location":"python_build/python-build-introduction/#introduction","title":"Introduction","text":"

Now you can code your own strategy easily using our Python Build service! Begin coding your own strategy from scratch, or modify some of our ready-made templates to suit your needs. Get access to our state-of-the-art AlgoBulls Core Trading Engine, which automatically leverages our infrastructure so that you can access the latest historical data to gauge the performance of your strategies. Tweak the various parameters of your strategy to choose the ideal instrument, indicator values, and profit loss percentages as per your needs! View the performance of your strategy using our visual analytics feature and continue to tweak until you are satisfied with the performance. Get your strategy approved for live trading from our experts and deploy it on 30+ supported brokers without coding any broker integration logic.

Select Python Build from the navigation bar on the left to know more.

"},{"location":"python_build/python-build-introduction/#an-overview","title":"An overview","text":"

Running Strategies: This section shows how many strategies are currently active and running in your account.

Strategies Saved: This displays the number of strategies saved in your AlgoBulls account. It also shows the number of maximum strategies that you can save as per your current plan.

Execution Time Consumed: You can view the number of minutes that have been used for Backtesting or Paper Trading your strategies.

Note:

Paper Trading would be available from Monday - Friday (excluding NSE/NASDAQ holidays) within the trading time of that particular exchange. You can code your strategy, execute on Backtesting mode or analyse the strategy results 24x7.

Analytics Support: This shows whether your analytics support is active. Analytics support is not available to free plan users.

Professional Support: This section connects you to other professional support forums for additional support while developing the strategy.

Active Plan: This section displays the current plan active on your AlgoBulls account.

Ready Templates: Ready-to-use templates that you can modify and test.

My Coded Strategies: Strategies that have been coded and saved by you are displayed here. This includes new and modified strategies developed by you.

Need Support: You can raise support for the particular statregy from here make sure your stategy is present in My Coded Strategies section

Quick Help: Resources to help you code better.

"},{"location":"python_build/python-build-professional/","title":"Python Build Professional Support","text":""},{"location":"python_build/python-build-professional/#are-you-an-experienced-trader-with-limited-coding-experience","title":"Are you an Experienced Trader with Limited Coding Experience?","text":"

If you're an experienced trader who excels at building trading strategies based on technical analysis but lacks the coding expertise to implement them, Python Build offers you the perfect solution \u2013 our Python Build Professional Support.

"},{"location":"python_build/python-build-professional/#how-can-python-build-professional-support-help-you","title":"How Can Python Build Professional Support Help You?","text":"

Our Python Build Professional Support bridges the gap between your market expertise in technical analysis and our proficiency in coding and algo trading strategy development. We understand that not everyone is a coding wizard, and that's where our professional support comes in.

"},{"location":"python_build/python-build-professional/#getting-started","title":"Getting Started","text":"

To take advantage of our Python Build Professional Support, follow these simple steps:

  1. Click on \"Professional Support\" - Look for the \"Professional Support\" button on the Python Build Web splash and click on it to get started.

  2. Describe Your Strategy - Once you're in the professional support interface, you'll be prompted to describe your trading strategy. You can provide details on how you want your strategy to work, including entry and exit criteria, risk management rules, and any specific requirements you have.

    Sample Prompt: \"I want a strategy that buys stocks when the 50-day moving average crosses above the 200-day moving average and sells when it crosses below. Additionally, I'd like a stop-loss of 5% and a take-profit at 10%.\"

  3. Indicate Technical Indicators - Specify which technical indicators you want to use in your strategy. You can mention indicators like moving averages, RSI, MACD, or any others that are crucial for your trading approach.

  4. Submit Your Request - Once you've filled in the necessary information, click on the \"Submit\" button. Your request will be sent to our professional support team.

"},{"location":"python_build/python-build-professional/#what-happens-next","title":"What Happens Next?","text":"

Our dedicated professional support team will promptly review your request. They will connect with you to gather any additional details if needed and ensure they have a clear understanding of your requirements.

Our team of experienced Python developers and algo trading experts will then get to work on implementing your strategy according to your specifications. We'll ensure that your strategy is coded efficiently and effectively, leveraging the power of Python Build.

You can expect to receive your custom-coded trading strategy as soon as possible, allowing you to put your trading expertise to work without the coding hassle.

With Python Build's Professional Support, you can confidently bring your trading ideas to life and stay ahead in the competitive world of stock market trading. Start automating your strategies today!

"},{"location":"python_build/python-build-view-results/","title":"Analytics","text":""},{"location":"python_build/python-build-view-results/#how-to-view-the-results","title":"How to view the Results?","text":"

Once you start the strategy, it may take a while for it to complete the execution. You can switch to the Analytics tab after you run your strategy. Even if the strategy execution is not complete, you will still see intermediate results.

Analytics: In the analytics section, you can view a strategy\u2019s Stats & various other metrics in the form of graphs like P&L.

"},{"location":"python_build/python-build-view-results/#stats","title":"Stats","text":"

In this section you can see the total returns, sharpe ratio, sortino ratio, volatility, Max Drawdown, Total wins or Loses, Total short or long trades, hit ratio, number of trades, average trades per day, max profit, max loss, average profit per winning trade, average loss per losing trade.

"},{"location":"python_build/python-build-view-results/#cumulative-returns","title":"Cumulative Returns","text":""},{"location":"python_build/python-build-view-results/#profit-loss-currency-or","title":"Profit & Loss (Currency or %)","text":"

The trade by trade P&L in Currency or Percentage.

"},{"location":"python_build/python-build-view-results/#end-of-year-returns-plot","title":"End of Year Returns Plot (%)","text":""},{"location":"python_build/python-build-view-results/#monthly-returns-histogram","title":"Monthly Returns Histogram (%)","text":""},{"location":"python_build/python-build-view-results/#monthly-returns-heatmap","title":"Monthly Returns Heatmap (%)","text":""},{"location":"python_build/python-build-view-results/#daily-returns","title":"Daily Returns (%)","text":""},{"location":"python_build/python-build-view-results/#underwater-drawdown-plot","title":"Underwater Drawdown Plot (%)","text":""},{"location":"python_build/python-build-view-results/#pl-book","title":"P&L Book","text":"

View detailed trade by trade report. Premium users can analyze this data in the form of heatmaps for Gross Profit & Loss, Trading Volume & Total number of Trades.

"},{"location":"python_build/python-build-view-results/#user-log","title":"User Log","text":"

Real-time logs from strategy execution are displayed in this section. Use these logs to debug your strategy\u2019s behavior and performance.

"},{"location":"python_build/python-build-view-results/#order-history","title":"Order History","text":"

View the order state transition for every order placed by your strategy in-depth.

"},{"location":"python_build/strategy_guides/common_options_strategy/","title":"Options Strategy Structure","text":"

Links

"},{"location":"python_build/strategy_guides/common_options_strategy/#1-initial-steps","title":"1. Initial steps","text":""},{"location":"python_build/strategy_guides/common_options_strategy/#naming-a-class","title":"Naming a Class","text":"eg: For the above strategy name the class name would be:
StrategyOptionsEMACrossover(StrategyOptionsBaseV2)\n

Coding Conventions

* Make a class with the same name as the file name\n* Make sure the first letter of each word is in uppercase and the initials should be in uppercase as well.\n* If the class name includes indicator names like EMA, SMA, and VWAP the name should be in uppercase in the class name but not in the file name.\n* Every options strategy is a child class of the StrategyOptionsBaseV2 class.\n
"},{"location":"python_build/strategy_guides/common_options_strategy/#naming-your-strategy","title":"Naming your Strategy","text":"

This name will be displayed in your My Coded Strategies in Python Build Web, and it will also be the strategy_name when you are fetching all strategies in pyalgotrading. Inside your strategy class, you can write your first parameter as name.

name = 'options_ema_crossover'\n

"},{"location":"python_build/strategy_guides/common_options_strategy/#2-init-method","title":"2. Init method","text":"

This method gets called only once when the strategy is started.

"},{"location":"python_build/strategy_guides/common_options_strategy/#strategy-info","title":"Strategy info","text":"

In the init method add the line given below

super().__init__(*args, **kwargs)\n

"},{"location":"python_build/strategy_guides/common_options_strategy/#parameter-creation","title":"Parameter creation","text":"

Next, we assign the parameter values to the class variables of the same name as the parameters but in the lowercase format as shown below:

eg:

self.fresh_order_candle = self.strategy_parameters['FRESH_ORDER_CANDLE']\nself.start_time_hours = self.strategy_parameters['START_TIME_HOURS']\nself.start_time_minutes = self.strategy_parameters['START_TIME_MINUTES']\nself.end_time_hours = self.strategy_parameters['END_TIME_HOURS']\nself.end_time_minutes = self.strategy_parameters['END_TIME_MINUTES']\nself.no_of_strikes_away_ce = self.strategy_parameters['NO_OF_STRIKES_AWAY_CE']\nself.no_of_strikes_away_p = self.strategy_parameters['NO_OF_STRIKES_AWAY_PE']\nself._strike_direction_ce = self.strategy_parameters['STRIKES_DIRECTION_CE']\nself._strike_direction_pe = self.strategy_parameters['STRIKES_DIRECTION_PE']\nself.ema_period_one = self.strategy_parameters['EMA_PERIOD_ONE']\nself.ema_period_two = self.strategy_parameters['EMA_PERIOD_TWO']\nself.target_percentage = self.strategy_parameters['TARGET_PERCENTAGE']\nself.stoploss_percentage = self.strategy_parameters['STOPLOSS_PERCENTAGE']\nself.stoploss_range = self.strategy_parameters['STOPLOSS_RANGE']\nself.stoploss_order_count_allowed = self.strategy_parameters['STOPLOSS_ORDER_COUNT_ALLOWED']\n

Note

"},{"location":"python_build/strategy_guides/common_options_strategy/#start-time-and-end-time-creation","title":"Start time and End time creation","text":"

Adding Start and End time is useful when you want to define a timerange between which the strategy will be running each day. Add the below code to calculate the strategy start time and end time, from the strategy_parameters.

try:

    self.candle_start_time = time(hour=self.start_time_hours, minute=self.start_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting start hours and minutes... EXITING')\n    raise SystemExit\n
try:
    self.candle_end_time = time(hour=self.end_time_hours, minute=self.end_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting end time hours and minutes... EXITING')\n    raise SystemExit\n

"},{"location":"python_build/strategy_guides/common_options_strategy/#strategy-variables","title":"Strategy variables","text":"

We create our own strategy variables other than the strategy parameter variables which will be used throughout the strategy.

eg:

self.main_order = None            # We save the entry order in this variable\nself.stoploss_order = None        # We save the corresponding stoploss exit order of the entry order in this variable\n
We initialize the variables with a None value. !!! Note There could be more strategy variables required as per the strategy requirement.

"},{"location":"python_build/strategy_guides/common_options_strategy/#3-initialize-method","title":"3. Initialize method","text":"

Unlike the init method, this method gets called every day at the beginning of the day once the strategy is started.

Here the strategy variables that were initialized as None are again defined as dictionaries/lists except for the self.order_tag_manager. Create a reference for OrderTagManager as shown below:

self.order_tag_manager = OrderTagManager\n
"},{"location":"python_build/strategy_guides/common_options_strategy/#4-ordertagmanager","title":"4. OrderTagManager","text":"

The self.order_tag_manager is used to store/remove the entry/exit orders. The self.order_tag_manager has the following methods:

"},{"location":"python_build/strategy_guides/common_options_strategy/#add_order","title":"add_order","text":"
self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
"},{"location":"python_build/strategy_guides/common_options_strategy/#get_orders","title":"get_orders","text":"

eg:

self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
"},{"location":"python_build/strategy_guides/common_options_strategy/#remove_tags","title":"remove_tags","text":"

eg:

self.order_tag_manager.remove_tags(tags=entry_key)\n

Here the entry_key tag is removed from the OrderTagManager.

Note

When the tag is removed the order objects stored in that tag are also removed but the same order objects would still be present in order tags.

"},{"location":"python_build/strategy_guides/common_options_strategy/#remove_order","title":"remove_order","text":"

eg:

self.order_tag_manager.remove_order(main_order)\n
Here the main_order order object is removed from the OrderTagManager.

Note

The order object will be removed from all the tags ta

"},{"location":"python_build/strategy_guides/common_options_strategy/#get_internals","title":"get_internals","text":"
Returns the values i.e. both the entry and exit orders stored inside the tags list.\n
"},{"location":"python_build/strategy_guides/common_options_strategy/#5-child-instruments-calculation","title":"5. Child instruments calculation","text":""},{"location":"python_build/strategy_guides/common_options_strategy/#get_ltp","title":"get_ltp","text":"

Fetch the ltp of the base instrument (instrument set while executing strategy)

ltp = self.broker.get_ltp(self.underlying_instrument)\n

"},{"location":"python_build/strategy_guides/common_options_strategy/#options_instruments_set_up_local","title":"options_instruments_set_up_local","text":"

Get the ATM ITM and OTM lists of the child instrument based on the LTP

self.options_instruments_set_up_local(self.underlying_instrument, tradingsymbol_suffix, ltp)\n

"},{"location":"python_build/strategy_guides/common_options_strategy/#get_child_instrument_details","title":"get_child_instrument_details","text":"

Select a child instrument from the lists of ATM, ITM, and OTM based on the strike direction and no of strikes given for the child instrument

child_instrument = self.get_child_instrument_details(self.underlying_instrument, tradingsymbol_suffix, strike_direction, no_of_strikes)\n

"},{"location":"python_build/strategy_guides/common_options_strategy/#6-entry-methods","title":"6. Entry Methods","text":""},{"location":"python_build/strategy_guides/common_options_strategy/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry","text":""},{"location":"python_build/strategy_guides/common_options_strategy/#strategy_enter_position","title":"strategy_enter_position","text":""},{"location":"python_build/strategy_guides/common_options_strategy/#7-exit-methods","title":"7. Exit Methods","text":""},{"location":"python_build/strategy_guides/common_options_strategy/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit","text":""},{"location":"python_build/strategy_guides/common_options_strategy/#strategy_exit_position","title":"strategy_exit_position","text":""},{"location":"python_build/strategy_guides/common_options_strategy/#8-other-common-methods","title":"8. Other common methods","text":"

There are other methods that are used in the strategy:

"},{"location":"python_build/strategy_guides/common_options_strategy/#check_and_place_stoploss_order","title":"check_and_place_stoploss_order","text":"

This method is called in the strategy_select_instruments_for_exit when our entry order is open, and we want to place a stoploss exit order for the same.

"},{"location":"python_build/strategy_guides/common_options_strategy/#set_all_none","title":"set_all_none","text":"

This method is called in the strategy_exit_position when our entry order has exited, and we want to remove the order object from the self.main_order variable.

"},{"location":"python_build/strategy_guides/common_options_strategy/#options_instruments_set_up_local_1","title":"options_instruments_set_up_local","text":"

This method is called in the strategy_select_instruments_for_entry to fetch the ATM, ITM, and OTM lists of the child instruments based on the LTP of the base instrument.

"},{"location":"python_build/strategy_guides/common_options_strategy/#get_child_instrument_details_1","title":"get_child_instrument_details","text":"

This method is called in the strategy_select_instruments_for_entry to fetch a single child instrument based on the no of strikes and strike direction.

"},{"location":"python_build/strategy_guides/common_options_strategy/#9-cleanup","title":"9. Cleanup","text":"
  1. Add comments and docstrings wherever possible to improve code readability.
  2. Once the strategy is completed you can optimize imports, give proper indentation and proper formatting to the strategy code and remove unwanted imports, variables, and methods before delivering the code.
"},{"location":"python_build/strategy_guides/common_options_strategy/#10-check-out-our-docs-for-developed-options-strategies","title":"10. Check out our docs for developed Options strategies","text":"

Tip

To know more about a strategy from our given template, simply check the first line of comment in the code of that specific strategy.

"},{"location":"python_build/strategy_guides/common_regular_strategy/","title":"Regular Strategy Structure","text":"

Links

"},{"location":"python_build/strategy_guides/common_regular_strategy/#1-initial-steps","title":"1. Initial steps","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#naming-a-class","title":"Naming a Class","text":"eg: For the above strategy name the class name would be:
StrategyFuturesEMACrossover(StrategyBase)\n

Coding Conventions

* Make a class with the same name as the file name\n* Make sure the first letter of each word is in uppercase and the initials should be in uppercase as well.\n* If the class name includes indicator names like EMA, SMA, and VWAP the name should be in uppercase in the class name but not in the file name.\n* Every strategy is a child class of the StrategyBase class.\n
"},{"location":"python_build/strategy_guides/common_regular_strategy/#naming-your-strategy","title":"Naming your Strategy","text":"

This name will be displayed in your My Coded Strategies in Python Build Web, and it will also be the strategy_name when you are fetching all strategies in pyalgotrading. Inside your strategy class, you can write your first parameter as name.

name = 'futures_ema_crossover'\n

"},{"location":"python_build/strategy_guides/common_regular_strategy/#2-init-method","title":"2. Init method","text":"

This method gets called only once when the strategy is started.

"},{"location":"python_build/strategy_guides/common_regular_strategy/#strategy-info","title":"Strategy info","text":"

In the init method add the line given below

super().__init__(*args, **kwargs)\n

"},{"location":"python_build/strategy_guides/common_regular_strategy/#parameter-creation","title":"Parameter creation","text":"

Next we assign the parameter values to the class variables of the same name as the parameters but in the lowercase format, as shown below:

eg:

self.fresh_order_candle = self.strategy_parameters['FRESH_ORDER_CANDLE']\nself.start_time_hours = self.strategy_parameters['START_TIME_HOURS']\nself.start_time_minutes = self.strategy_parameters['START_TIME_MINUTES']\nself.end_time_hours = self.strategy_parameters['END_TIME_HOURS']\nself.end_time_minutes = self.strategy_parameters['END_TIME_MINUTES']\nself.ema_period_one = self.strategy_parameters['EMA_PERIOD_ONE']\nself.ema_period_two = self.strategy_parameters['EMA_PERIOD_TWO']\nself.target_percentage = self.strategy_parameters['TARGET_PERCENTAGE']\nself.stoploss_percentage = self.strategy_parameters['STOPLOSS_PERCENTAGE']\nself.stoploss_range = self.strategy_parameters['STOPLOSS_RANGE']\nself.stoploss_order_count_allowed = self.strategy_parameters['STOPLOSS_ORDER_COUNT_ALLOWED']\n

Note

"},{"location":"python_build/strategy_guides/common_regular_strategy/#start-time-and-end-time-creation","title":"Start time and End time creation","text":"

Adding Start and End time is useful when you want to define a timerange between which the strategy will be running each day. Add the below code to calculate the strategy start time and end time, from the strategy_parameters. try:

    self.candle_start_time = time(hour=self.start_time_hours, minute=self.start_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting start hours and minutes... EXITING')\n    raise SystemExit\n
try:
    self.candle_end_time = time(hour=self.end_time_hours, minute=self.end_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting end time hours and minutes... EXITING')\n    raise SystemExit\n

"},{"location":"python_build/strategy_guides/common_regular_strategy/#strategy-variables","title":"Strategy variables","text":"

We create our own strategy variables other than the strategy parameter variables which will be used throughout the strategy.

eg: self.order_tag_manager = None

We initialize the variables with a None value.

Note

There could be more strategy variables required as per the strategy requirement.\n
"},{"location":"python_build/strategy_guides/common_regular_strategy/#3-initialize-method","title":"3. Initialize method","text":"

Unlike the init method, this method gets called every day at the beginning of the day once the strategy is started.

Here the strategy variables that were initialized as None are again defined as dictionaries/lists except for the self.order_tag_manager. Create a reference for OrderTagManager as shown below:

self.order_tag_manager = OrderTagManager\n
"},{"location":"python_build/strategy_guides/common_regular_strategy/#4-ordertagmanager","title":"4. OrderTagManager","text":"

The self.order_tag_manager is used to store/remove the entry/exit orders. The self.order_tag_manager has the following methods:

"},{"location":"python_build/strategy_guides/common_regular_strategy/#add_order","title":"add_order","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#get_orders","title":"get_orders","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#remove_tags","title":"remove_tags","text":"

Note

When the tag is removed the order objects stored in that tag are also removed but the same order objects would still be present in the order tags.

"},{"location":"python_build/strategy_guides/common_regular_strategy/#remove_order","title":"remove_order","text":"
self.order_tag_manager.remove_order(main_order)\n

Here the main_order order object is removed from the OrderTagManager.

Note

The order object will be removed from all the tags ta

"},{"location":"python_build/strategy_guides/common_regular_strategy/#get_internals","title":"get_internals","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#5-entry-methods","title":"5. Entry Methods","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#strategy_enter_position","title":"strategy_enter_position","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#6-exit-methods","title":"6. Exit Methods","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit:","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#strategy_exit_position","title":"strategy_exit_position","text":""},{"location":"python_build/strategy_guides/common_regular_strategy/#7-other-common-methods","title":"7. Other common methods","text":"

There are other methods that are used in the strategy:

"},{"location":"python_build/strategy_guides/common_regular_strategy/#check_and_place_stoploss_order","title":"check_and_place_stoploss_order","text":"

This method is called in the strategy_select_instruments_for_exit when our entry order is open, and we want to place a stoploss exit order for the same.

"},{"location":"python_build/strategy_guides/common_regular_strategy/#set_all_none","title":"set_all_none","text":"

This method is called in the strategy_exit_position when our entry order has exited, and we want to remove the order object from the self.main_order variable.

"},{"location":"python_build/strategy_guides/common_regular_strategy/#8-cleanup","title":"8. Cleanup","text":"
  1. Add comments and docstrings wherever possible to improve code readability.
  2. Once the strategy is completed you can optimize imports, give proper indentation and proper formatting to the strategy code and remove unwanted imports, variables, and methods before delivering the code.
"},{"location":"python_build/strategy_guides/common_regular_strategy/#10-check-out-our-docs-for-developed-regular-strategies","title":"10. Check out our docs for developed Regular strategies","text":"

Tip

To know more about a strategy from our given template, simply check the first line of comment in the code of that specific strategy.

"},{"location":"python_build/strategy_guides/structure/","title":"Code Structure of Strategy","text":"

Coding Prerequisites

"},{"location":"python_build/strategy_guides/structure/#methods","title":"Methods","text":""},{"location":"python_build/strategy_guides/structure/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry()","text":"

This function helps you choose which trading instruments you want your strategy to work with. The system will use this function to go through each instrument one by one, at each candle's time. You get to write code that decides whether to place an order for a specific instrument or not.

"},{"location":"python_build/strategy_guides/structure/#strategy_enter_position","title":"strategy_enter_position()","text":"

This function is where you can place orders for the instruments you selected earlier. It's executed for each instrument you picked in the previous function.

"},{"location":"python_build/strategy_guides/structure/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit()","text":"

After you've entered a position for an instrument, this function is called for each of those instruments at each candle interval. You can use it to decide whether an instrument should be exited from the position.

"},{"location":"python_build/strategy_guides/structure/#strategy_exit_position","title":"strategy_exit_position()","text":"

In this function, you can close or exit positions for the instruments you marked for exiting in the previous function. It's done instrument by instrument.

"},{"location":"python_build/strategy_guides/structure/#supporting-methods","title":"Supporting Methods","text":"

You have the following supporting methods:

"},{"location":"python_build/strategy_guides/structure/#init","title":"init()","text":"

This method is like a starter for your strategy. It checks if the values you give it make sense and sets up some useful information for your strategy to use.

"},{"location":"python_build/strategy_guides/structure/#initialize","title":"initialize()","text":"

This method is called when your strategy begins, both at the very start and at the beginning of each trading day. It's like setting up your strategy's workspace and giving your tools a starting position.

"},{"location":"python_build/strategy_guides/structure/#name","title":"name()","text":"

This method gives your strategy a special name. It's like giving your strategy a unique nickname.

"},{"location":"python_build/strategy_guides/structure/#versions_supported","title":"versions_supported()","text":"

This method lets you specify which version of the AlgoBulls Platform your strategy works well with. It's like saying, \"My strategy is ready for this specific version of the platform.\"

"},{"location":"python_build/strategy_guides/structure/#utility-functions","title":"Utility Functions","text":"

You have the following utility function to be used in this strategy :

Links

"},{"location":"python_build/strategy_guides/structure/#get_crossover_value","title":"get_crossover_value()","text":"This handy function calculates something called the \"crossover value\" for you. It's like having a calculator that figures out this specific value for your strategy."},{"location":"python_build/strategy_guides/structure/#flowchart","title":"Flowchart","text":"

Once you create your own strategy or use a ready strategy from the pyalgostrategypool package, this is how it works internally on the AlgoBulls Core Trading Engine.

"},{"location":"strategies/aroon_crossover/","title":"Aroon Crossover","text":"

This is a trading strategy called \"Aroon Crossover\" implemented in Python using the PyAlgoTrading library. The strategy is based on the Aroon indicator crossover.

Links

Jupyter Notebooks for Indian Exchange (NSE)

Jupyter Notebook for US Exchange (NASDAQ)

"},{"location":"strategies/aroon_crossover/#aroon-indicator","title":"Aroon Indicator","text":" Fig.1 - SPY candle chart (top), Aroon Indicator for that chart (bottom)"},{"location":"strategies/aroon_crossover/#strategy-overview","title":"Strategy Overview","text":"

This strategy, called Aroon Crossover, implements a crossover strategy using the Aroon indicator. It generates entry and exit signals based on the crossover of Aroon Up and Aroon Down values.

"},{"location":"strategies/aroon_crossover/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description TIME_PERIOD None greater than 0 The period for which we calculate the Aroon Value"},{"location":"strategies/aroon_crossover/#crossover-calculation","title":"Crossover Calculation","text":"

The get_crossover_value method calculates the Aroon Up and Aroon Down values for a given instrument based on the historical data. It uses the talib.AROON function from the Talib library to calculate the values. The method then determines the crossover of Aroon Up and Aroon Down and returns the corresponding entry or exit action.

"},{"location":"strategies/bollinger_bands/","title":"Bollinger Bands","text":"

This is a trading strategy called \"Bollinger Bands\" implemented in Python using the PyAlgoTrading library. The strategy is based on the bollinger bands indicator values.

Links

Jupyter Notebooks for Indian Exchange (NSE)

Jupyter Notebook for US Exchange (NASDAQ)

"},{"location":"strategies/bollinger_bands/#bollinger-bands-indicator","title":"Bollinger Bands Indicator","text":"

Bollinger Bands consists of a middle band (typically a 20-day Simple Moving Average) and two bands that represent the upper and lower price boundaries based on standard deviations. The bands adjust dynamically with market volatility.

Key points about Bollinger Bands:

Fig.1 - SPY candle chart (top) with Bollinger Bands (purple), 20 day standard deviation graph (bottom)"},{"location":"strategies/bollinger_bands/#strategy-overview","title":"Strategy Overview","text":"

This strategy, called Bollinger Bands, is an implementation of the Bollinger Bands indicator. It uses the Bollinger Bands values to compare with previous candle's OPEN, HIGH, LOW and CLOSE values and generate entry and exit signals for trading instruments.

"},{"location":"strategies/bollinger_bands/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description TIME_PERIOD None greater than 0 Period (number of candles) by which Bollinger Bands are calculated STANDARD_DEVIATION None between 0 to 10 Standard deviation (in percent) for upper and lower band from the signal bands"},{"location":"strategies/bollinger_bands/#decision-calculation","title":"Decision Calculation","text":"

The get_decision method calculates the Bollinger Bands values for a given instrument based on the OHLC (Open, High, Low, Close) historical data. It uses the talib.BBANDS function from the Talib library to calculate the upper and lower bands. The method compares the previous candle's open, low, and close values with the upper and lower bands to determine the entry or exit action. If the conditions for a buy or sell signal are met, the corresponding action is returned.

"},{"location":"strategies/ema_crossover/","title":"EMA Crossover","text":"

This is a trading strategy called \"EMA Regular Order Strategy\" implemented in Python using the PyAlgoTrading library. The strategy is based on the exponential moving average crossover.

Links

Jupyter Notebooks for Indian Exchange (NSE)

Jupyter Notebook for US Exchange (NASDAQ)

"},{"location":"strategies/ema_crossover/#ema-indicator","title":"EMA indicator","text":"

Exponential Moving Averages (EMAs) are a popular technical analysis tool used in the stock market. They are similar to Simple Moving Averages (SMAs), but they place greater emphasis on recent price data.

Here is a summary of Exponential Moving Averages:

Fig.1 - IBM candle chart (top) with EMA (green) and SMA (red) lines"},{"location":"strategies/ema_crossover/#strategy-overview","title":"Strategy Overview","text":"

This strategy, called EMA Regular Order Strategy, implements a crossover strategy using Exponential Moving Averages (EMA). It generates entry and exit signals based on the crossover of two EMAs.

"},{"location":"strategies/ema_crossover/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description TIME_PERIOD1 None greater than 0 Period (number of candles) by which EMA-1 is calculated TIME_PERIOD2 None greater than 0 Period (number of candles) by which EMA-2 is calculated"},{"location":"strategies/ema_crossover/#crossover-calculation","title":"Crossover Calculation","text":"

The get_crossover_value method calculates the crossover value based on the two EMAs of the closing prices. It uses the talib.EMA function from the Talib library to calculate the EMAs. The method then determines the crossover between the two EMAs and returns the corresponding value (-1, 0, or 1).

"},{"location":"strategies/inverse_ema_scalping/","title":"Inverse EMA Scalping","text":"

This is a trading strategy called \"Inverse EMA Scalping Regular Order Strategy\" implemented in Python using the PyAlgoTrading library. The strategy is based on the exponential moving average crossover.

Links

Jupyter Notebooks for Indian Exchange (NSE)

Jupyter Notebooks for US Exchange (NASDAQ)

"},{"location":"strategies/inverse_ema_scalping/#what-is-inverse-ema","title":"What is Inverse EMA","text":"

Inverse EMA, also known as Reverse Exponential Moving Average (REMA), is a variation of the Exponential Moving Average (EMA) in the stock market. While the EMA gives more weight to recent price data, the Inverse EMA assigns more weight to older data points.

Here is a summary of Inverse EMA:

"},{"location":"strategies/inverse_ema_scalping/#strategy-overview","title":"Strategy Overview","text":"

This strategy implements a scalping strategy using Exponential Moving Averages (EMA). It generates entry and exit signals based on the inverse crossover of two EMAs.

"},{"location":"strategies/inverse_ema_scalping/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description LARGER_TIME_PERIOD None greater than 0 Period (number of candles) by which large period EMA is calculated SMALLER_TIME_PERIOD None greater than 0 Period (number of candles) by which short period EMA is calculated"},{"location":"strategies/inverse_ema_scalping/#crossover-calculation","title":"Crossover Calculation","text":"

The get_crossover_value method calculates the crossover value based on the inverse crossover of the two EMAs of the closing prices. It uses the talib.EMA function from the Talib library to calculate the EMAs. The method then determines the inverse crossover between the two EMAs and returns the corresponding value (-1, 0, or 1).

"},{"location":"strategies/macd_crossover/","title":"MACD Crossover","text":"

This is a trading strategy called \"MACD Crossovers\" implemented in Python using the PyAlgoTrading library. The strategy is based on the MACD indicator crossover.

Links

Jupyter Notebook for Indian Exchange (NSE)

"},{"location":"strategies/macd_crossover/#macd-crossover_1","title":"MACD Crossover","text":"

In the dynamic world of stock trading, mastering effective strategies is the key to success. The Moving Average Convergence Divergence (MACD) Crossover strategy is a powerful tool that can help traders identify potential entry and exit points in the stock market.

Here is a summary of RSI and MACD in the stock market: - The MACD is a trend-following momentum indicator that consists of two lines: the MACD line and the Signal line. - A bullish signal is generated when the MACD line crosses above the Signal line, indicating a potential uptrend. - Conversely, a bearish signal occurs when the MACD line crosses below the Signal line, suggesting a potential downtrend. - When the MACD crosses above the Signal line, it's a signal to consider a long (BUY) position. - Conversely, when the MACD crosses below the Signal line, it may be time to think about a short (SELL) position.

"},{"location":"strategies/macd_crossover/#strategy-overview","title":"Strategy Overview","text":"

The MACD Crossover strategy is a robust approach that leverages the power of the MACD indicator to identify potential entry and exit points in the stock market.

"},{"location":"strategies/macd_crossover/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description TIMEPERIOD_FAST None greater than 0 Period (number of candles) by which EMA 2 is calculated TIMEPERIOD_SLOW None greater than 0 Period (number of candles) by which EMA 2 is calculated TIMEPERIOD_SIGNAL None greater than 0 Period (number of candles) by which moving average is calculated"},{"location":"strategies/macd_crossover/#crossover-calculation","title":"Crossover Calculation","text":"

The get_crossover_value method calculates the crossover value based on the inverse crossover of the two EMAs of the closing prices. It uses the talib.MACD function from the Talib library to calculate the MACDs. The method then determines the crossover between the two MACDs and returns the corresponding value (-1, 0, or 1).

"},{"location":"strategies/mean_reversion_bollinger_bands/","title":"Mean Reversion Bollinger Bands","text":"

This is a trading strategy called \"Mean Reversion Bollinger Bands\" implemented in Python using the PyAlgoTrading library. The strategy is based on the bollingerbands indicator.

Links

Jupyter Notebook for Indian Exchange (NSE)

"},{"location":"strategies/mean_reversion_bollinger_bands/#mean-reversion-bollinger-bands_1","title":"Mean Reversion Bollinger Bands","text":"

In the dynamic world of stock trading, effective strategies can make all the difference. The Mean Reversion Bollinger Bands strategy is a powerful tool that traders can use to identify potential entry and exit points in the stock market.

Here is a summary of RSI and MACD in the stock market: - Bollinger Bands are a volatility indicator that consists of a middle band (usually a simple moving average), an upper band, and a lower band. These bands expand and contract based on price volatility. The strategy leverages these bands to identify potential mean reversion opportunities. - Mean reversion is the idea that prices tend to revert to their historical average over time. In this strategy, traders look for situations where the price deviates significantly from the middle Bollinger Band and expect it to revert to the mean. - The Mean Reversion Bollinger Bands strategy involves identifying price movements that touch or cross the upper or lower bands and anticipating a reversal. - When the price touches the upper band, traders may consider a short (SELL) position, expecting a downward move. - Conversely, when the price touches the lower band, it may signal a potential long (BUY) opportunity, anticipating an upward move.

"},{"location":"strategies/mean_reversion_bollinger_bands/#strategy-overview","title":"Strategy Overview","text":"

The Mean Reversion Bollinger Bands strategy is a robust approach that leverages the power of Bollinger Bands to identify potential mean reversion opportunities in the stock market.

"},{"location":"strategies/mean_reversion_bollinger_bands/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description TIME_PERIOD None greater than 0 Period (number of candles) by which Bollinger Bands are calculated STANDARD_DEVIATION None between 0 to 10 Standard deviation (in percent) for upper and lower band from the signal bands"},{"location":"strategies/mean_reversion_bollinger_bands/#decision-calculation","title":"Decision Calculation","text":"

The get_decision method calculates the Bollinger Bands values for a given instrument based on the OHLC (Open, High, Low, Close) historical data. It uses the talib.BBANDS function from the Talib library to calculate the upper and lower bands. The method compares the previous candle's open, low, and close values with the upper and lower bands to determine the entry or exit action. If the conditions for a buy or sell signal are met, the corresponding action is returned.

"},{"location":"strategies/options_bear_call_ladder/","title":"Options Bear Call Ladder","text":""},{"location":"strategies/options_bear_call_ladder/#options-bear-call-ladder","title":"Options Bear Call Ladder","text":"

This class implements the Options Bear Call Ladder strategy.

Links

Jupyter Notebook for Options from Indian Exchange (NSE)

"},{"location":"strategies/options_bear_call_ladder/#bear-call-ladder","title":"Bear Call Ladder","text":""},{"location":"strategies/options_bear_call_ladder/#parameters","title":"Parameters","text":"Name Default Value Expected Value Description LEG_ONE_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_ONE_TRADING_SYMBOL_SUFFIX 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_ONE_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_ONE_NUMBER_OF_STRIKES 0 greater than 0 Number of strikes for leg one. LEG_TWO_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_TWO_TRADING_SYMBOL_SUFFIX 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_TWO_STRIKE_DIRECTION 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_TWO_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one. LEG_THREE_TRANSACTION_TYPE 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_THREE_TRADING_SYMBOL_SUFFIX 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_THREE_STRIKE_DIRECTION 0 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_THREE_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one."},{"location":"strategies/options_bear_put_ladder/","title":"Options Bear Put Ladder","text":""},{"location":"strategies/options_bear_put_ladder/#options-bear-put-ladder","title":"Options Bear Put Ladder","text":"

This is a template for the Options Bear Put Ladder strategy. The strategy involves the combination of buying and selling put options to profit from a downward price movement in the underlying asset. It utilizes multiple legs with different strike prices and transaction types to create a ladder-like structure.

Links

Jupyter Notebook for Options from Indian Exchange (NSE)

"},{"location":"strategies/options_bear_put_ladder/#bear-put-ladder","title":"Bear Put Ladder","text":""},{"location":"strategies/options_bear_put_ladder/#parameters","title":"Parameters","text":"Name Default Value Expected Value Description LEG_ONE_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_ONE_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_ONE_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_ONE_NUMBER_OF_STRIKES 0 greater than 0 Number of strikes for leg one. LEG_TWO_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_TWO_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_TWO_STRIKE_DIRECTION 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_TWO_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one. LEG_THREE_TRANSACTION_TYPE 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_THREE_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_THREE_STRIKE_DIRECTION 0 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_THREE_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one."},{"location":"strategies/options_bull_call_ladder/","title":"Options Bull Call Ladder","text":""},{"location":"strategies/options_bull_call_ladder/#options-bull-call-ladder","title":"Options Bull Call Ladder","text":"

Links

Jupyter Notebook for Options from Indian Exchange (NSE)

"},{"location":"strategies/options_bull_call_ladder/#bull-call-ladder","title":"Bull Call Ladder","text":""},{"location":"strategies/options_bull_call_ladder/#parameters","title":"Parameters","text":"Name Default Value Expected Value Description LEG_ONE_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_ONE_TRADING_SYMBOL_SUFFIX 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_ONE_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_ONE_NUMBER_OF_STRIKES 0 greater than 0 Number of strikes for leg one. LEG_TWO_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_TWO_TRADING_SYMBOL_SUFFIX 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_TWO_STRIKE_DIRECTION 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_TWO_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one. LEG_THREE_TRANSACTION_TYPE 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_THREE_TRADING_SYMBOL_SUFFIX 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_THREE_STRIKE_DIRECTION 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_THREE_NUMBER_OF_STRIKES 4 greater than 0 Number of strikes for leg one."},{"location":"strategies/options_bull_put_ladder/","title":"Options Bull Put Ladder","text":""},{"location":"strategies/options_bull_put_ladder/#options-bull-put-ladder","title":"Options Bull Put Ladder","text":"

Links

Jupyter Notebook for Options from Indian Exchange (NSE)

"},{"location":"strategies/options_bull_put_ladder/#bull-put-ladder","title":"Bull Put ladder","text":""},{"location":"strategies/options_bull_put_ladder/#initialization","title":"Initialization","text":"

The __init__ method initializes the strategy and accepts parameters for configuring the strategy. The parameters are:

Name Default Value Expected Value Description LEG_ONE_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_ONE_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_ONE_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_ONE_NUMBER_OF_STRIKES 0 greater than 0 Number of strikes for leg one. LEG_TWO_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_TWO_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_TWO_STRIKE_DIRECTION 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_TWO_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one. LEG_THREE_TRANSACTION_TYPE 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_THREE_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_THREE_STRIKE_DIRECTION 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_THREE_NUMBER_OF_STRIKES 4 greater than 0 Number of strikes for leg one."},{"location":"strategies/options_bull_put_ladder/#additional-notes","title":"Additional Notes","text":""},{"location":"strategies/options_long_iron_butterfly/","title":"Options Long Iron Butterfly","text":""},{"location":"strategies/options_long_iron_butterfly/#options-long-iron-butterfly","title":"Options Long Iron Butterfly","text":"

This is a template for implementing the Options Long Iron Butterfly strategy in Python.

Links

"},{"location":"strategies/options_long_iron_butterfly/#long-iron-butterfly","title":"Long Iron Butterfly","text":""},{"location":"strategies/options_long_iron_butterfly/#strategy-parameters","title":"Strategy Parameters","text":"

The strategy accepts the following parameters:

Name Default Value Expected Value Description LEG_ONE_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_ONE_TRADING_SYMBOL_SUFFIX 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_ONE_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_ONE_NUMBER_OF_STRIKES 0 greater than 0 Number of strikes for leg one. LEG_TWO_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_TWO_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_TWO_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_TWO_NUMBER_OF_STRIKES 0 greater than 0 Number of strikes for leg one. LEG_THREE_TRANSACTION_TYPE 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_THREE_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_THREE_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_THREE_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one. LEG_FOUR_TRANSACTION_TYPE 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_FOUR_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_FOUR_STRIKE_DIRECTION 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_FOUR_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one."},{"location":"strategies/options_straddle/","title":"Options Straddle","text":""},{"location":"strategies/options_straddle/#options-straddle","title":"Options Straddle","text":"

This class represents the implementation of an options straddle trading strategy.

Links

Jupyter Notebook for Options from Indian Exchange (NSE)

"},{"location":"strategies/options_straddle/#straddle-options","title":"Straddle Options","text":""},{"location":"strategies/options_straddle/#parameters","title":"Parameters","text":"Name Default Value Expected Value Description _leg_one_transaction_type 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] _leg_one_tradingsymbol_suffix 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] _leg_one_strike_direction 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] _leg_one_number_of_strikes 0 greater than 0 Number of strikes for leg one. _leg_two_transaction_type 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] _leg_two_tradingsymbol_suffix 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] _leg_two_strike_direction 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] _leg_two_number_of_strikes 0 greater than 0 Number of strikes for leg one."},{"location":"strategies/options_strangle/","title":"Options Strangle","text":""},{"location":"strategies/options_strangle/#options-strangle","title":"Options Strangle","text":"

The StrategyOptionsStrangle class is a strategy template for trading options strangles. It is derived from the StrategyOptionsBaseV2 class.

Links

Jupyter Notebook for Options from Indian Exchange (NSE)

"},{"location":"strategies/options_strangle/#strangle-options","title":"Strangle Options","text":""},{"location":"strategies/options_strangle/#parameters","title":"Parameters","text":"

The following parameters can be set in the Parameters Configuration Pane:

Name Default Value Expected Value Description _leg_one_transaction_type 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] _leg_one_tradingsymbol_suffix 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] _leg_one_strike_direction 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] _leg_one_number_of_strikes 2 greater than 0 Number of strikes for leg one. _leg_two_transaction_type 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] _leg_two_tradingsymbol_suffix 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] _leg_two_strike_direction 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] _leg_two_number_of_strikes 2 greater than 0 Number of strikes for leg one."},{"location":"strategies/reverse_rsi/","title":"Reverse RSI","text":"

This is a trading strategy called \"Reverse RSI\" implemented in Python using the PyAlgoTrading library. The strategy is based on the relative strength index indicator.

Links

Jupyter Notebook for Indian Exchange (NSE)

Jupyter Notebook for US Exchange (NASDAQ)

"},{"location":"strategies/reverse_rsi/#relative-strength-index","title":"Relative Strength Index","text":"

RSI stands for Relative Strength Index, and it is a popular technical indicator used in the stock market to analyze the strength and momentum of a price trend. The RSI provides insights into whether a stock is overbought or oversold and can help identify potential trend reversals.

Here is a summary of RSI in the stock market:

Overall, the Relative Strength Index (RSI) is a widely used indicator in the stock market to assess the strength and momentum of price movements. It helps traders identify overbought and oversold conditions, as well as potential trend reversals, which can assist in making trading decisions.

Fig.1 - MCD candle chart (top) and RSI plot (bottom)"},{"location":"strategies/reverse_rsi/#strategy-overview","title":"Strategy Overview","text":"

The Reverse RSI strategy is a trading strategy based on the Relative Strength Index (RSI) indicator. It generates entry and exit signals based on the reverse crossover of the RSI values from specified overbought and oversold levels.

"},{"location":"strategies/reverse_rsi/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description TIME_PERIOD None greater than 0 Period (number of candles) by which RSI is calculated OVERBOUGHT_VALUE None greater than 0 RSI value above which stocks are considered over-bought OVERSOLD_VALUE None greater than 0 RSI value below which stocks are considered over-sold"},{"location":"strategies/reverse_rsi/#crossover-calculation","title":"Crossover Calculation","text":"

The get_crossover_value method calculates the crossover values for the RSI indicator using historical data of the instrument. It compares the RSI values with the overbought and oversold levels to determine the entry and exit actions. The method returns the crossover values for oversold and overbought levels.

"},{"location":"strategies/rsi_macd_crossover/","title":"RSI MACD Crossover","text":"

This is a trading strategy called \"RSI MACD Crossovers\" implemented in Python using the PyAlgoTrading library. The strategy is based on the RSI and MACD indicator crossover.

Links

Jupyter Notebook for Indian Exchange (NSE)

"},{"location":"strategies/rsi_macd_crossover/#rsi-and-macd-crossover","title":"RSI and MACD Crossover","text":"

In the dynamic world of stock trading, effective strategies are the key to success. The combination of two powerful technical indicators, the Moving Average Convergence Divergence (MACD) and the Relative Strength Index (RSI), can be a game-changer for traders. This strategy leverages MACD and RSI crossovers to identify potential entry and exit points in the stock market.

Here is a summary of RSI and MACD in the stock market: - The MACD is a trend-following momentum indicator. It consists of two lines: the MACD line and the Signal line. When the MACD line crosses above the Signal line, it generates a bullish signal, suggesting a potential uptrend. Conversely, a cross below the Signal line indicates a bearish signal, signaling a potential downtrend.

"},{"location":"strategies/rsi_macd_crossover/#strategy-overview","title":"Strategy Overview","text":"

The MACD and RSI crossover strategy is a robust approach that combines the strength of two widely used technical indicators. By identifying potential entry and exit points based on these crossovers, traders can make more informed decisions in the stock market.

"},{"location":"strategies/rsi_macd_crossover/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description TIMEPERIOD_FAST None greater than 0 Period (number of candles) by which EMA 2 is calculated TIMEPERIOD_SLOW None greater than 0 Period (number of candles) by which EMA 2 is calculated TIMEPERIOD_SIGNAL None greater than 0 Period (number of candles) by which moving average is calculated TIMEPERIOD_RSI None greater than 0 Period (number of candles) by which RSI is calculated OVERSOLD_VALUE None greater than 0 Threshould value indicating potential buying opportunites OVERBOUGHT_VALUE None greater than 0 Threshould value indicating potential selling opportunites"},{"location":"strategies/rsi_macd_crossover/#crossover-calculation","title":"Crossover Calculation","text":"

The get_crossover_value method calculates the crossover value based on the inverse crossover of the two EMAs of the closing prices. It uses the talib.MACD and talib.RSI function from the Talib library to calculate the MACD and RSI. The method then determines the crossover between the MACD and RSI and returns the corresponding value (-1, 0, or 1).

"},{"location":"strategies/stochastic_crossover/","title":"Stochastic Crossover","text":"

This is a trading strategy called \"Stochastic Crossover\" implemented in Python using the PyAlgoTrading library. The strategy is based on the Stochastic indicator crossover.

Links

Jupyter Notebook for Indian Exchange (NSE)

Jupyter Notebook for US Exchange (NASDAQ)

"},{"location":"strategies/stochastic_crossover/#stochastic-oscillator-indicator","title":"Stochastic Oscillator Indicator","text":"

In the stock market, Stochastic refers to the Stochastic Oscillator, which is a popular technical indicator used to analyze price momentum and identify potential trend reversals. The Stochastic Oscillator compares the closing price of a security to its price range over a specific period of time. It consists of two lines, %K and %D, and generates values between 0 and 100.

Here is a summary of the Stochastic Oscillator in the stock market:

Fig.1 - IBM candle chart (top) with Stochastic Fast (bottom) Fig.2 - QQQQ candle chart (top) with Stochastic Fast (bottom 1), Stochastic Slow (bottom 2) and Full Stochastic (bottom 3)"},{"location":"strategies/stochastic_crossover/#strategy-overview","title":"Strategy Overview","text":"

The strategy follows a simple rule based on the Stochastic indicator crossover. When the Stochastic indicator's %K line crosses above the %D line, a buy signal is generated. Conversely, when the %K line crosses below the %D line, a sell signal is generated. The strategy aims to capture potential trend reversals.

"},{"location":"strategies/stochastic_crossover/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description FASTK_PERIOD or PERIOD None greater than 0 The period for the fast %K line of the Stochastic indicator. SLOWK_PERIOD or SMOOTH_K_PERIOD None greater than 0 The period for the slow %K line of the Stochastic indicator. SLOWD_PERIOD or SMOOTH_D_PERIOD None greater than 0 The period for the slow %D line of the Stochastic indicator."},{"location":"strategies/stochastic_crossover/#crossover-calculation","title":"Crossover Calculation","text":"

The get_crossover_value method calculates the crossover values for the Slow-K and Slow-D of Stochastic indicator using historical data of the instrument. The method returns the crossover values between slow-K and slow-D.

"},{"location":"strategies/volatility_trend_atr/","title":"Volatility Trends with Average True Range (ATR)","text":"

This is a trading strategy called \"Volatility Trends ATR\" implemented in Python using the PyAlgoTrading library. The strategy is based on the ATR indicator crossover.

Links

Jupyter Notebook for Indian Exchange (NSE)

"},{"location":"strategies/volatility_trend_atr/#volatility-trends-with-average-true-range-atr-indicator","title":"Volatility Trends with Average True Range (ATR) Indicator","text":"

In the ever-changing realm of stock trading, market volatility can be both an opportunity and a challenge. Traders and investors require a reliable instrument to gauge price fluctuations and devise informed strategies. The Average True Range (ATR) steps in as a robust technical indicator to fulfill this role. ATR delivers valuable insights into market volatility trends, equipping traders with the necessary tools to make calculated decisions in the stock market.

Here is a summary of ATR in the stock market: - The Average True Range (ATR), is a technical gauge designed to quantify a security's trading range over a specific time frame. Rather than simply tracking daily price changes, ATR calculates the \"true range,\" accounting for gaps between trading sessions.

"},{"location":"strategies/volatility_trend_atr/#strategy-overview","title":"Strategy Overview","text":"

The Average True Range (ATR) steps in as a robust technical indicator to fulfill this role. ATR delivers valuable insights into market volatility trends, equipping traders with the necessary tools to make calculated decisions in the stock market.

"},{"location":"strategies/volatility_trend_atr/#strategy-parameters","title":"Strategy Parameters","text":"

The following parameters can be configured for the strategy:

Name Default Value Expected Value Description TIME_PERIOD None greater than 0 Period (number of candles) by which ATR is calculated ATR_PREV_CANDLES_NUM None greater than 0 nth Previous candle ATR"},{"location":"strategies/volatility_trend_atr/#decision-calculation","title":"Decision Calculation","text":"

The get_trend_direction method calculates the ATR values for the volatility trend atr indicator using historical data of the instrument. It uses the talib.AROON function from the Talib library to calculate the values. It compares the ATR values with the atr of previous specified candle and determine the entry and exit actions. The method returns the ATR values for current candle.

"},{"location":"strategies/vwap_crossover/","title":"VWAP Crossover","text":"

This is a trading strategy called \"VWAP Crossover\" implemented in Python using the PyAlgoTrading library. The strategy is based on the crossover of the VWAP (Volume Weighted Average Price) indicator.

Links

Jupyter Notebook for Indian Exchange (NSE)

Jupyter Notebook for US Exchange (NASDAQ)

"},{"location":"strategies/vwap_crossover/#vwap-indicator","title":"VWAP indicator","text":"

In the stock market, VWAP stands for Volume-Weighted Average Price. VWAP is a trading indicator that calculates the average price at which a particular stock or security has traded throughout the day, taking into account both the price and the volume of each trade.

Here is a summary of VWAP in the stock market:

Fig.1 - IBM candle chart (top) with VWAP line (Blue), Volume chart with SMA line"},{"location":"strategies/vwap_crossover/#strategy-overview","title":"Strategy Overview","text":"

The strategy follows a simple rule based on the crossover of the VWAP indicator. When the price crosses above the VWAP, a buy signal is generated, and when the price crosses below the VWAP, a sell signal is generated. The strategy aims to capture potential trend reversals based on the VWAP.

"},{"location":"strategies/vwap_crossover/#strategy-parameters","title":"Strategy Parameters","text":"

No specific strategy parameters are mentioned in the code.

"},{"location":"strategies/vwap_crossover/#crossover-calculation","title":"Crossover Calculation","text":"

The get_crossover_value method calculates the VWAP from historical data and the crossover values for the VWAP of the instrument. The method returns the crossover values between close of hist data and vwap.

"},{"location":"strategies/strategy_guides/common_options_strategy/","title":"Options Strategy Structure","text":"

Links

"},{"location":"strategies/strategy_guides/common_options_strategy/#1-initial-steps","title":"1. Initial steps","text":""},{"location":"strategies/strategy_guides/common_options_strategy/#naming-a-class","title":"Naming a Class","text":"eg: For the above strategy name the class name would be:
StrategyOptionsEMACrossover(StrategyOptionsBaseV2)\n

Coding Conventions

* Make a class with the same name as the file name\n* Make sure the first letter of each word is in uppercase and the initials should be in uppercase as well.\n* If the class name includes indicator names like EMA, SMA, and VWAP the name should be in uppercase in the class name but not in the file name.\n* Every options strategy is a child class of the StrategyOptionsBaseV2 class.\n
"},{"location":"strategies/strategy_guides/common_options_strategy/#naming-your-strategy","title":"Naming your Strategy","text":"

This name will be displayed in your My Coded Strategies in Python Build Web, and it will also be the strategy_name when you are fetching all strategies in pyalgotrading. Inside your strategy class, you can write your first parameter as name.

name = 'options_ema_crossover'\n

"},{"location":"strategies/strategy_guides/common_options_strategy/#2-init-method","title":"2. Init method","text":"

This method gets called only once when the strategy is started.

"},{"location":"strategies/strategy_guides/common_options_strategy/#strategy-info","title":"Strategy info","text":"

In the init method add the line given below

super().__init__(*args, **kwargs)\n

"},{"location":"strategies/strategy_guides/common_options_strategy/#parameter-creation","title":"Parameter creation","text":"

Next, we assign the parameter values to the class variables of the same name as the parameters but in the lowercase format as shown below:

eg:

self.fresh_order_candle = self.strategy_parameters['FRESH_ORDER_CANDLE']\nself.start_time_hours = self.strategy_parameters['START_TIME_HOURS']\nself.start_time_minutes = self.strategy_parameters['START_TIME_MINUTES']\nself.end_time_hours = self.strategy_parameters['END_TIME_HOURS']\nself.end_time_minutes = self.strategy_parameters['END_TIME_MINUTES']\nself.no_of_strikes_away_ce = self.strategy_parameters['NO_OF_STRIKES_AWAY_CE']\nself.no_of_strikes_away_p = self.strategy_parameters['NO_OF_STRIKES_AWAY_PE']\nself._strike_direction_ce = self.strategy_parameters['STRIKES_DIRECTION_CE']\nself._strike_direction_pe = self.strategy_parameters['STRIKES_DIRECTION_PE']\nself.ema_period_one = self.strategy_parameters['EMA_PERIOD_ONE']\nself.ema_period_two = self.strategy_parameters['EMA_PERIOD_TWO']\nself.target_percentage = self.strategy_parameters['TARGET_PERCENTAGE']\nself.stoploss_percentage = self.strategy_parameters['STOPLOSS_PERCENTAGE']\nself.stoploss_range = self.strategy_parameters['STOPLOSS_RANGE']\nself.stoploss_order_count_allowed = self.strategy_parameters['STOPLOSS_ORDER_COUNT_ALLOWED']\n

Note

"},{"location":"strategies/strategy_guides/common_options_strategy/#start-time-and-end-time-creation","title":"Start time and End time creation","text":"

Adding Start and End time is useful when you want to define a timerange between which the strategy will be running each day. Add the below code to calculate the strategy start time and end time, from the strategy_parameters.

try:

    self.candle_start_time = time(hour=self.start_time_hours, minute=self.start_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting start hours and minutes... EXITING')\n    raise SystemExit\n
try:
    self.candle_end_time = time(hour=self.end_time_hours, minute=self.end_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting end time hours and minutes... EXITING')\n    raise SystemExit\n

"},{"location":"strategies/strategy_guides/common_options_strategy/#strategy-variables","title":"Strategy variables","text":"

We create our own strategy variables other than the strategy parameter variables which will be used throughout the strategy.

eg:

self.main_order = None            # We save the entry order in this variable\nself.stoploss_order = None        # We save the corresponding stoploss exit order of the entry order in this variable\n
We initialize the variables with a None value. !!! Note There could be more strategy variables required as per the strategy requirement.

"},{"location":"strategies/strategy_guides/common_options_strategy/#3-initialize-method","title":"3. Initialize method","text":"

Unlike the init method, this method gets called every day at the beginning of the day once the strategy is started.

Here the strategy variables that were initialized as None are again defined as dictionaries/lists except for the self.order_tag_manager. Create a reference for OrderTagManager as shown below:

self.order_tag_manager = OrderTagManager\n
"},{"location":"strategies/strategy_guides/common_options_strategy/#4-ordertagmanager","title":"4. OrderTagManager","text":"

The self.order_tag_manager is used to store/remove the entry/exit orders. The self.order_tag_manager has the following methods:

"},{"location":"strategies/strategy_guides/common_options_strategy/#add_order","title":"add_order","text":"
self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
"},{"location":"strategies/strategy_guides/common_options_strategy/#get_orders","title":"get_orders","text":"

eg:

self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
"},{"location":"strategies/strategy_guides/common_options_strategy/#remove_tags","title":"remove_tags","text":"

eg:

self.order_tag_manager.remove_tags(tags=entry_key)\n

Here the entry_key tag is removed from the OrderTagManager.

Note

When the tag is removed the order objects stored in that tag are also removed but the same order objects would still be present in order tags.

"},{"location":"strategies/strategy_guides/common_options_strategy/#remove_order","title":"remove_order","text":"

eg:

self.order_tag_manager.remove_order(main_order)\n
Here the main_order order object is removed from the OrderTagManager.

Note

The order object will be removed from all the tags ta

"},{"location":"strategies/strategy_guides/common_options_strategy/#get_internals","title":"get_internals","text":"
Returns the values i.e. both the entry and exit orders stored inside the tags list.\n
"},{"location":"strategies/strategy_guides/common_options_strategy/#5-child-instruments-calculation","title":"5. Child instruments calculation","text":""},{"location":"strategies/strategy_guides/common_options_strategy/#get_ltp","title":"get_ltp","text":"

Fetch the ltp of the base instrument (instrument set while executing strategy)

ltp = self.broker.get_ltp(self.underlying_instrument)\n

"},{"location":"strategies/strategy_guides/common_options_strategy/#options_instruments_set_up_local","title":"options_instruments_set_up_local","text":"

Get the ATM ITM and OTM lists of the child instrument based on the LTP

self.options_instruments_set_up_local(self.underlying_instrument, tradingsymbol_suffix, ltp)\n

"},{"location":"strategies/strategy_guides/common_options_strategy/#get_child_instrument_details","title":"get_child_instrument_details","text":"

Select a child instrument from the lists of ATM, ITM, and OTM based on the strike direction and no of strikes given for the child instrument

child_instrument = self.get_child_instrument_details(self.underlying_instrument, tradingsymbol_suffix, strike_direction, no_of_strikes)\n

"},{"location":"strategies/strategy_guides/common_options_strategy/#6-entry-methods","title":"6. Entry Methods","text":""},{"location":"strategies/strategy_guides/common_options_strategy/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry","text":""},{"location":"strategies/strategy_guides/common_options_strategy/#strategy_enter_position","title":"strategy_enter_position","text":""},{"location":"strategies/strategy_guides/common_options_strategy/#7-exit-methods","title":"7. Exit Methods","text":""},{"location":"strategies/strategy_guides/common_options_strategy/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit","text":""},{"location":"strategies/strategy_guides/common_options_strategy/#strategy_exit_position","title":"strategy_exit_position","text":""},{"location":"strategies/strategy_guides/common_options_strategy/#8-other-common-methods","title":"8. Other common methods","text":"

There are other methods that are used in the strategy:

"},{"location":"strategies/strategy_guides/common_options_strategy/#check_and_place_stoploss_order","title":"check_and_place_stoploss_order","text":"

This method is called in the strategy_select_instruments_for_exit when our entry order is open, and we want to place a stoploss exit order for the same.

"},{"location":"strategies/strategy_guides/common_options_strategy/#set_all_none","title":"set_all_none","text":"

This method is called in the strategy_exit_position when our entry order has exited, and we want to remove the order object from the self.main_order variable.

"},{"location":"strategies/strategy_guides/common_options_strategy/#options_instruments_set_up_local_1","title":"options_instruments_set_up_local","text":"

This method is called in the strategy_select_instruments_for_entry to fetch the ATM, ITM, and OTM lists of the child instruments based on the LTP of the base instrument.

"},{"location":"strategies/strategy_guides/common_options_strategy/#get_child_instrument_details_1","title":"get_child_instrument_details","text":"

This method is called in the strategy_select_instruments_for_entry to fetch a single child instrument based on the no of strikes and strike direction.

"},{"location":"strategies/strategy_guides/common_options_strategy/#9-cleanup","title":"9. Cleanup","text":"
  1. Add comments and docstrings wherever possible to improve code readability.
  2. Once the strategy is completed you can optimize imports, give proper indentation and proper formatting to the strategy code and remove unwanted imports, variables, and methods before delivering the code.
"},{"location":"strategies/strategy_guides/common_options_strategy/#10-check-out-our-docs-for-developed-options-strategies","title":"10. Check out our docs for developed Options strategies","text":"

Tip

To know more about a strategy from our given template, simply check the first line of comment in the code of that specific strategy.

"},{"location":"strategies/strategy_guides/common_regular_strategy/","title":"Regular Strategy Structure","text":"

Links

"},{"location":"strategies/strategy_guides/common_regular_strategy/#1-initial-steps","title":"1. Initial steps","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#naming-a-class","title":"Naming a Class","text":"eg: For the above strategy name the class name would be:
StrategyFuturesEMACrossover(StrategyBase)\n

Coding Conventions

* Make a class with the same name as the file name\n* Make sure the first letter of each word is in uppercase and the initials should be in uppercase as well.\n* If the class name includes indicator names like EMA, SMA, and VWAP the name should be in uppercase in the class name but not in the file name.\n* Every strategy is a child class of the StrategyBase class.\n
"},{"location":"strategies/strategy_guides/common_regular_strategy/#naming-your-strategy","title":"Naming your Strategy","text":"

This name will be displayed in your My Coded Strategies in Python Build Web, and it will also be the strategy_name when you are fetching all strategies in pyalgotrading. Inside your strategy class, you can write your first parameter as name.

name = 'futures_ema_crossover'\n

"},{"location":"strategies/strategy_guides/common_regular_strategy/#2-init-method","title":"2. Init method","text":"

This method gets called only once when the strategy is started.

"},{"location":"strategies/strategy_guides/common_regular_strategy/#strategy-info","title":"Strategy info","text":"

In the init method add the line given below

super().__init__(*args, **kwargs)\n

"},{"location":"strategies/strategy_guides/common_regular_strategy/#parameter-creation","title":"Parameter creation","text":"

Next we assign the parameter values to the class variables of the same name as the parameters but in the lowercase format, as shown below:

eg:

self.fresh_order_candle = self.strategy_parameters['FRESH_ORDER_CANDLE']\nself.start_time_hours = self.strategy_parameters['START_TIME_HOURS']\nself.start_time_minutes = self.strategy_parameters['START_TIME_MINUTES']\nself.end_time_hours = self.strategy_parameters['END_TIME_HOURS']\nself.end_time_minutes = self.strategy_parameters['END_TIME_MINUTES']\nself.ema_period_one = self.strategy_parameters['EMA_PERIOD_ONE']\nself.ema_period_two = self.strategy_parameters['EMA_PERIOD_TWO']\nself.target_percentage = self.strategy_parameters['TARGET_PERCENTAGE']\nself.stoploss_percentage = self.strategy_parameters['STOPLOSS_PERCENTAGE']\nself.stoploss_range = self.strategy_parameters['STOPLOSS_RANGE']\nself.stoploss_order_count_allowed = self.strategy_parameters['STOPLOSS_ORDER_COUNT_ALLOWED']\n

Note

"},{"location":"strategies/strategy_guides/common_regular_strategy/#start-time-and-end-time-creation","title":"Start time and End time creation","text":"

Adding Start and End time is useful when you want to define a timerange between which the strategy will be running each day. Add the below code to calculate the strategy start time and end time, from the strategy_parameters. try:

    self.candle_start_time = time(hour=self.start_time_hours, minute=self.start_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting start hours and minutes... EXITING')\n    raise SystemExit\n
try:
    self.candle_end_time = time(hour=self.end_time_hours, minute=self.end_time_minutes)\nexcept ValueError:\n    self.logger.fatal('Error converting end time hours and minutes... EXITING')\n    raise SystemExit\n

"},{"location":"strategies/strategy_guides/common_regular_strategy/#strategy-variables","title":"Strategy variables","text":"

We create our own strategy variables other than the strategy parameter variables which will be used throughout the strategy.

eg: self.order_tag_manager = None

We initialize the variables with a None value.

Note

There could be more strategy variables required as per the strategy requirement.\n
"},{"location":"strategies/strategy_guides/common_regular_strategy/#3-initialize-method","title":"3. Initialize method","text":"

Unlike the init method, this method gets called every day at the beginning of the day once the strategy is started.

Here the strategy variables that were initialized as None are again defined as dictionaries/lists except for the self.order_tag_manager. Create a reference for OrderTagManager as shown below:

self.order_tag_manager = OrderTagManager\n
"},{"location":"strategies/strategy_guides/common_regular_strategy/#4-ordertagmanager","title":"4. OrderTagManager","text":"

The self.order_tag_manager is used to store/remove the entry/exit orders. The self.order_tag_manager has the following methods:

"},{"location":"strategies/strategy_guides/common_regular_strategy/#add_order","title":"add_order","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#get_orders","title":"get_orders","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#remove_tags","title":"remove_tags","text":"

Note

When the tag is removed the order objects stored in that tag are also removed but the same order objects would still be present in the order tags.

"},{"location":"strategies/strategy_guides/common_regular_strategy/#remove_order","title":"remove_order","text":"
self.order_tag_manager.remove_order(main_order)\n

Here the main_order order object is removed from the OrderTagManager.

Note

The order object will be removed from all the tags ta

"},{"location":"strategies/strategy_guides/common_regular_strategy/#get_internals","title":"get_internals","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#5-entry-methods","title":"5. Entry Methods","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#strategy_enter_position","title":"strategy_enter_position","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#6-exit-methods","title":"6. Exit Methods","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit:","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#strategy_exit_position","title":"strategy_exit_position","text":""},{"location":"strategies/strategy_guides/common_regular_strategy/#7-other-common-methods","title":"7. Other common methods","text":"

There are other methods that are used in the strategy:

"},{"location":"strategies/strategy_guides/common_regular_strategy/#check_and_place_stoploss_order","title":"check_and_place_stoploss_order","text":"

This method is called in the strategy_select_instruments_for_exit when our entry order is open, and we want to place a stoploss exit order for the same.

"},{"location":"strategies/strategy_guides/common_regular_strategy/#set_all_none","title":"set_all_none","text":"

This method is called in the strategy_exit_position when our entry order has exited, and we want to remove the order object from the self.main_order variable.

"},{"location":"strategies/strategy_guides/common_regular_strategy/#8-cleanup","title":"8. Cleanup","text":"
  1. Add comments and docstrings wherever possible to improve code readability.
  2. Once the strategy is completed you can optimize imports, give proper indentation and proper formatting to the strategy code and remove unwanted imports, variables, and methods before delivering the code.
"},{"location":"strategies/strategy_guides/common_regular_strategy/#10-check-out-our-docs-for-developed-regular-strategies","title":"10. Check out our docs for developed Regular strategies","text":"

Tip

To know more about a strategy from our given template, simply check the first line of comment in the code of that specific strategy.

"},{"location":"strategies/strategy_guides/common_strategy_guide/","title":"Common Strategy Building Guide","text":""},{"location":"strategies/strategy_guides/common_strategy_guide/#understanding-the-strategy-structure","title":"Understanding the Strategy Structure","text":"

The strategy code is basically a Python Class, with its Base Class as StrategyBase (for regular strategies) or StrategyBaseOptionsV2 (for options strategies). In this documentation we will focus on a regular strategy called \u2018EMA Regular Order\u2019 - a strategy which gives BUY and SELL signals based on two EMA indicators and takes new-entry & previous-exit at every crossover. We also will be discussing about an options strategy called \"Options Bear Call Ladder Strategy\" - strategy which uses 3 legs to optimize the risk and returns of the options. Inside the strategy class there are many methods that could be divided into 2 different sections: Mandatory Methods: Initialization Methods, 4-Core Loop Methods & Optional Methods: Algorithmic Calculation Methods & Miscellaneous Methods. These sections are explained briefly below.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#mandatory-functions","title":"Mandatory Functions:","text":""},{"location":"strategies/strategy_guides/common_strategy_guide/#initialization-methods","title":"Initialization Methods","text":"

In this section, you will have the Strategy Class\u2019 \u201cinit\u201d method (a.k.a. Constructor). This method will extract the Strategy\u2019s Configured Parameters and save them in the different variables. There is another method in this section called \u201cinitialization\u201d, which will be called at the start of every trading day that will occur inside the timeline for which you are executing the strategy.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#4-core-loop-methods","title":"4 Core Loop Methods","text":"

These are the main methods that will be called by the AlgoBulls Core in a sequence for every candle (candle is the minimum time range for which the Open, High, Low and Close values of that instrument are available. Basically it is a representation of a time period and the data corresponds to the trades executed during that period). All the logic design methods are called inside these Core Methods, along with the helping methods.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#optional-function","title":"Optional Function","text":""},{"location":"strategies/strategy_guides/common_strategy_guide/#algorithmic-calculations-methods","title":"Algorithmic Calculations Methods","text":"

This section contains the methods that are defined by the user. These are not mandatory but good to keep your code organized and simple. Their main purpose will be to perform operations on historical data or LTP data of the selected instrument. Based on the results of these operations, it needs to decide whether it should Buy, Sell or take no action on the instrument. Apart from decision making, some of the other methods can also be useful to calculate the stop loss or target price for a trade. Point being, the purpose of these methods are totally dependent on the application of the user.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#miscellaneous-methods","title":"Miscellaneous Methods","text":"

These are handy methods that are created by a team of expert strategy developers and they are already a part of the base class. These methods do a lot of heavy lifting under the hood and can be used here for various purposes like getting the latest price of a stock, placing an order etc. These methods are not always necessary to be used and are generally a part of other methods mentioned above.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#working-flow-of-the-strategy","title":"Working Flow of the Strategy","text":"

Below Diagram is Sample Diagram on how the strategy execution engine works. Blocks in green are the mandatory methods that need to be implemented for every strategy.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#setting-up-imports-and-environment","title":"Setting Up: Imports and Environment","text":"

Before we dive into building of a strategy we need to fist setup our workspace depending the tool we are using. The available tools for creating a workspace of strategy are Pyalgotrading and Python Build Web.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#pyalgotrading","title":"Pyalgotrading","text":"

If you're coding on your local machine, I recommend setting up a virtual environment and installing the \"pyalgotrading\" Python package to keep things organised.

pip3 install pyalgotrading\n
Once you've got it installed, it's time to bring in the magic. Import the package and its constants into your Python file where your trading strategy will take shape.

from pyalgotrading.algobulls import AlgoBullsConnection\nfrom pyalgotrading.strategy import *\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#python-build-web","title":"Python Build Web","text":"

Now, if you prefer a web-based approach, we've got you covered. Head over to the \"Code New Strategy\" section on the Python Build page of the AlgoBulls website. Here, you can craft your strategy without the need to import any classes or packages. The choice is yours \u2013 flexibility at its best.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#strategy-code-creation-lets-get-started","title":"Strategy Code Creation: Let's Get Started","text":"

With the groundwork laid, it's time to create your strategy class. Be sure to choose the appropriate base class for your strategy. For regular equity strategies, the base class is StrategyBase while for options strategies, it's StrategyOptionsBaseV2.

Examples:

RegularOptions
class MovingAverageCrossoverV2(StrategyBase):\n    name = 'Moving Average Crossover V2'\n
class StrategyOptionsBearCallLadder(StrategyOptionsBaseV2):\n    name = 'Options Bear Call Ladder Template'\n

Feel free to get creative with your class name, but it's good practice to make it unique among your strategy class names. Below this declaration, we set the strategy's name.

For Pyalgotrading users

If you are uploading the strategy via pyalgotrading functions, then this name parameter's value will be the name of the strategy. That means this name will be displayed in My Coded Strategies section in Python Build.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#initialization-functions","title":"Initialization Functions","text":""},{"location":"strategies/strategy_guides/common_strategy_guide/#init","title":"init()","text":"

Every great trading strategy starts with a solid foundation \u2013 the constructor method, also known as the \"init\" method. Here's what it looks like:

def __init__(self, *args, **kwargs):\n    super().__init__(*args, **kwargs)\n
Within this method, you extract the parameters provided by the user. These user-defined parameters are stored in a dictionary called \"self.strategy_parameters.\" Here's how you can access these values:

self.timeperiod1 = self.strategy_parameters['TIMEPERIOD1']\nself.timeperiod2 = self.strategy_parameters['TIMEPERIOD2']\n
Feel free to initialise other variables here, such as self.main_order, self.number_of_allowed_expiry_dates, self.transaction_type_map and more.

Example: This is how the declaration of class along with its constructor would look like.

RegularOptions
class StrategyEMARegularOrder(StrategyBase):\n    name = 'EMA Regular Order Strategy'\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n        self.timeperiod1 = self.strategy_parameters['TIMEPERIOD1']\n        self.timeperiod2 = self.strategy_parameters['TIMEPERIOD2']\n\n        self.main_order_map = None\n
class StrategyOptionsBearCallLadder(StrategyOptionsBaseV2):\n    name = 'Options Bear Call Ladder Template'\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n        # Parameters (currently set with default values, can be overridden from the Parameters Configuration Pane)\n        self._leg_one_transaction_type = self.strategy_parameters.get('LEG_ONE_TRANSACTION_TYPE', 1)  # BUY: 1 | SELL: 2\n        self._leg_one_tradingsymbol_suffix = self.strategy_parameters.get('LEG_ONE_TRADING_SYMBOL_SUFFIX', 1)  # CE: 1 | PE: 2\n        self._leg_one_strike_direction = self.strategy_parameters.get('LEG_ONE_STRIKE_DIRECTION', 1)  # ITM: 0| ATM: 1| OTM: 2\n        self._leg_one_number_of_strikes = self.strategy_parameters.get('LEG_ONE_NUMBER_OF_STRIKES', 0)\n\n        self._leg_two_transaction_type = self.strategy_parameters.get('LEG_TWO_TRANSACTION_TYPE', 1)  # BUY: 1 | SELL: 2\n        self._leg_two_tradingsymbol_suffix = self.strategy_parameters.get('LEG_TWO_TRADING_SYMBOL_SUFFIX', 1)  # CE: 1 | PE: 2\n        self._leg_two_strike_direction = self.strategy_parameters.get('LEG_TWO_STRIKE_DIRECTION', 2)  # ITM: 0| ATM: 1| OTM: 2\n        self._leg_two_number_of_strikes = self.strategy_parameters.get('LEG_TWO_NUMBER_OF_STRIKES', 2)\n\n        self._leg_three_transaction_type = self.strategy_parameters.get('LEG_THREE_TRANSACTION_TYPE', 2)  # BUY: 1 | SELL: 2\n        self._leg_three_tradingsymbol_suffix = self.strategy_parameters.get('LEG_THREE_TRADING_SYMBOL_SUFFIX', 1)  # CE: 1 | PE: 2\n        self._leg_three_strike_direction = self.strategy_parameters.get('LEG_THREE_STRIKE_DIRECTION', 0)  # ITM: 0| ATM: 1| OTM: 2\n        self._leg_three_number_of_strikes = self.strategy_parameters.get('LEG_THREE_NUMBER_OF_STRIKES', 2)\n\n        # Maps\n        self.transaction_type_map = {1: \"BUY\", 2: \"SELL\"}\n        self.tradingsymbol_suffix_map = {1: \"CE\", 2: \"PE\"}\n        self.strike_direction_map = {0: OptionsStrikeDirection.ITM, 1: OptionsStrikeDirection.ATM, 2: OptionsStrikeDirection.OTM}\n\n        # Variables\n        self.number_of_allowed_expiry_dates = 1\n        self.instruments_done_for_the_day = None\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#initialize","title":"initialize()","text":"

The \"initialize\" method is your strategy's workspace, where you get everything ready for a fresh trading day. It's called at the start of each trading day, allowing you to reset variables, set up your tools, and perform any other tasks to ensure your strategy is primed and ready.

Example:

Examples:

RegularOptions
def initialize(self):\n    self.main_order_map = {}\n
def initialize(self):\n    super().initialize()\n    self.instruments_done_for_the_day = []\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#algorithmic-calculation-functions","title":"Algorithmic Calculation Functions","text":""},{"location":"strategies/strategy_guides/common_strategy_guide/#get_decision","title":"get_decision()","text":"

Now, let's dive into the heart of your strategy \u2013 the \"get_decision\" method. This method is where the magic happens, where you decide when to enter or exit a trade, set stop losses, and target prices. Here's how it works: Historical data of the instrument up to a certain point in your strategy is collected using:

By combining these calculated values with historical data, you can make informed decisions about when to initiate or close a trade. Additionally, you can use this information to compute potential target prices or set stop losses. AlgoBulls' Python Build empowers you to navigate the complexities of options trading with ease.

Example:

This is how an ideal get_decision() function would look like. This example is from RSI Crossover Strategy.

def get_crossover_value(self, instrument):\n    hist_data = self.get_historical_data(instrument)\n\n    rsi_value = talib.RSI(hist_data['close'],    timeperiod=self.time_period)\n\n    oversold_list = [self.oversold_value] * rsi_value.size\n    overbought_list = [self.overbought_value] * rsi_value.size\n\n    oversold_crossover_value = self.utils.crossover(rsi_value, oversold_list)\n    overbought_crossover_value = self.utils.crossover(rsi_value, overbought_list)\n\n    return oversold_crossover_value, overbought_crossover_value\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#miscellaneous-functions","title":"Miscellaneous Functions","text":""},{"location":"strategies/strategy_guides/common_strategy_guide/#get_child_instrument_details","title":"get_child_instrument_details()","text":"

The get_child_instrument_details function is at your disposal. It takes several parameters:

This function calls two other functions: self.get_allowed_expiry_dates() and get_options_instrument_with_strike_direction().

Example: This is how the function looks ideally. This example was taken from \u201cOptions Bear Call Strategy\u201d from ready templates.

    def get_child_instrument_details(self, base_instrument, tradingsymbol_suffix, strike_direction, no_of_strikes):\n        expiry_date = self.get_allowed_expiry_dates()[0]\n        child_instrument = self.get_options_instrument_with_strike_direction(base_instrument, expiry_date, tradingsymbol_suffix, strike_direction, no_of_strikes)\n        return child_instrument\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#get_allowed_expiry_dates","title":"get_allowed_expiry_dates()","text":"

In options strategies, the get_allowed_expiry_dates function plays a vital role. It doesn't require parameters; instead, it relies on the number_of_allowed_expiry_dates variable defined in the constructor method.

In essence, this function helps you select the appropriate expiry date based on the value you assign to number_of_allowed_expiry_dates variable.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#get_options_instrument_with_strike_direction","title":"get_options_instrument_with_strike_direction()","text":"

This function is a key player in options strategies, taking parameters such as:

"},{"location":"strategies/strategy_guides/common_strategy_guide/#options_instruments_set_up_local","title":"options_instruments_set_up_local()","text":"

Now, let's talk about a crucial piece of the options strategy puzzle \u2013 options_instruments_set_up_local. This function creates local instances of all available child instruments based on specified parameters:

Once executed, this function sets up and stores local instances of child instruments matching your criteria. These instances become valuable assets for further analysis or operations, including utilising the \"get_child_instrument_details\" function.

Example: This is how this function looks ideally. This example was taken from \u201cOptions Bear Call Ladder\u201d from ready templates.

def options_instruments_set_up_local(self, base_instrument, tradingsymbol_suffix, current_close, direction=OptionsInstrumentDirection.EXACT):\n        expiry_dates = self.get_allowed_expiry_dates()\n        for expiry_date in expiry_dates:\n            self.options_instruments_set_up(base_instrument, direction, expiry_date, tradingsymbol_suffix, current_close)\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#options_instruments_set_up","title":"options_instruments_set_up()","text":"

The final piece of the puzzle is \"options_instruments_set_up.\" This function takes parameters like:

Now, let's talk about the engine that drives your strategy \u2013 the core loop functions.

These include \"strategy_select_instruments_for_entry\", \"strategy_enter_position\", \"strategy_select_instruments_for_exit\" and \"strategy_exit_position\" These functions are called within a loop from the AlgoBulls core until an Exit Event for the strategy occurs.

"},{"location":"strategies/strategy_guides/common_strategy_guide/#the-4-core-loop-functions","title":"The 4 Core Loop Functions","text":""},{"location":"strategies/strategy_guides/common_strategy_guide/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry()","text":"

This function takes parameters:

Example: This function would ideally look like this. This example was taken from \u201cOptions Straddle\u201d from Ready Templates.

Examples:

RegularOptions
def strategy_select_instruments_for_entry(self, candle, instruments_bucket):\n    selected_instruments, meta = [], []\n\n    for instrument in instruments_bucket:\n        crossover = self.get_decision(instrument)\n        action_constants = {1: 'BUY', -1: 'SELL'}\n\n        if crossover in [-1, 1]:\n            selected_instruments.append(instrument)\n            meta.append({'action': action_constants[crossover]})\n\n    return selected_instruments, meta\n
def strategy_select_instruments_for_entry(self, candle, instruments_bucket):\n    selected_instruments, meta = [], []\n\n    for instrument in instruments_bucket:\n        if instrument not in self.instruments_done_for_the_day:\n            self.instruments_done_for_the_day.append(instrument)\n            ltp = self.broker.get_ltp(instrument)\n\n            self.options_instruments_set_up_local(instrument, \"CE\", ltp)\n            self.options_instruments_set_up_local(instrument, \"PE\", ltp)\n\n            leg_wise_list = [('LEG_ONE', self._leg_one_tradingsymbol_suffix, self._leg_one_strike_direction, self._leg_one_number_of_strikes, self._leg_one_transaction_type),\n                             ('LEG_TWO', self._leg_two_tradingsymbol_suffix, self._leg_two_strike_direction, self._leg_two_number_of_strikes, self._leg_two_transaction_type),\n                             ('LEG_THREE', self._leg_three_tradingsymbol_suffix, self._leg_three_strike_direction, self._leg_three_number_of_strikes, self._leg_three_transaction_type)]\n\n            for leg_number, tradingingsymbol_suffix, strike_direction, number_of_strikes, transaction_type in leg_wise_list:\n                self.logger.info(f'Processing {leg_number}...')\n                child_instrument = self.get_child_instrument_details(instrument, self.tradingsymbol_suffix_map[tradingingsymbol_suffix], self.strike_direction_map[strike_direction], number_of_strikes)\n                selected_instruments.append(child_instrument)\n                meta.append({'base_instrument': instrument, 'action': self.transaction_type_map[transaction_type]})\n\n    return selected_instruments, meta\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#strategy_enter_position","title":"strategy_enter_position()","text":"

This function takes parameters:

Here, you place orders for the selected instruments, updating them in \"self.main_order\" for easy access in exit functions.

Example: This function would ideally look like this. This example was taken from \u201cOptions Straddle\u201d from Ready Templates.

Examples:

RegularOptions
def strategy_enter_position(self, candle, instrument, meta):\n    self.main_order_map[instrument] = _ = self.broker.OrderRegular(instrument, meta['action'], quantity=self.number_of_lots * instrument.lot_size)\n    return _\n
def strategy_enter_position(self, candle, instrument, sideband_info):\n    _ = self.broker.OrderRegular(instrument, sideband_info['action'], quantity=self.number_of_lots * instrument.lot_size)\n    return _\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit()","text":"

Similar to entry, this function takes parameters:

The function iterates through the instrument bucket, checking if the instrument is present in \"self.main_order\" and whether its exit condition is satisfied. Instruments meeting exit conditions are added to the selected instruments list, along with their respective actions and meta-information.

Example: This function should ideally look like this. This example was taken from \u201cEMA Crossover Strategy\u201d.

    def strategy_select_instruments_for_exit(self, candle, instruments_bucket):\n        selected_instruments, meta = [], []\n\n        for instrument in instruments_bucket:\n            if self.main_order_map.get(instrument) is not None:\n                crossover = self.get_decision(instrument)\n\n                if crossover in [1, -1]:\n                    selected_instruments.append(instrument)\n                    meta.append({'action': 'EXIT'})\n\n        return selected_instruments, meta\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#strategy_exit_position","title":"strategy_exit_position()","text":"

Finally, this function takes parameters:

Here, you place orders for the selected instruments, removing them from \"self.main_order\" to prepare for the next iteration of the AlgoBulls core loop.

Example: This function should ideally look like this. This example was taken from \u201cEMA Crossover Strategy\u201d.

    def strategy_exit_position(self, candle, instrument, meta):\n    if meta['action'] == 'EXIT':\n        self.main_order_map[instrument].exit_position()\n        self.main_order_map[instrument] = None\n        return True\n    return False\n
"},{"location":"strategies/strategy_guides/structure/","title":"Code Structure of Strategy","text":"

Coding Prerequisites

"},{"location":"strategies/strategy_guides/structure/#methods","title":"Methods","text":""},{"location":"strategies/strategy_guides/structure/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry()","text":"

This function helps you choose which trading instruments you want your strategy to work with. The system will use this function to go through each instrument one by one, at each candle's time. You get to write code that decides whether to place an order for a specific instrument or not.

"},{"location":"strategies/strategy_guides/structure/#strategy_enter_position","title":"strategy_enter_position()","text":"

This function is where you can place orders for the instruments you selected earlier. It's executed for each instrument you picked in the previous function.

"},{"location":"strategies/strategy_guides/structure/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit()","text":"

After you've entered a position for an instrument, this function is called for each of those instruments at each candle interval. You can use it to decide whether an instrument should be exited from the position.

"},{"location":"strategies/strategy_guides/structure/#strategy_exit_position","title":"strategy_exit_position()","text":"

In this function, you can close or exit positions for the instruments you marked for exiting in the previous function. It's done instrument by instrument.

"},{"location":"strategies/strategy_guides/structure/#supporting-methods","title":"Supporting Methods","text":"

You have the following supporting methods:

"},{"location":"strategies/strategy_guides/structure/#init","title":"init()","text":"

This method is like a starter for your strategy. It checks if the values you give it make sense and sets up some useful information for your strategy to use.

"},{"location":"strategies/strategy_guides/structure/#initialize","title":"initialize()","text":"

This method is called when your strategy begins, both at the very start and at the beginning of each trading day. It's like setting up your strategy's workspace and giving your tools a starting position.

"},{"location":"strategies/strategy_guides/structure/#name","title":"name()","text":"

This method gives your strategy a special name. It's like giving your strategy a unique nickname.

"},{"location":"strategies/strategy_guides/structure/#versions_supported","title":"versions_supported()","text":"

This method lets you specify which version of the AlgoBulls Platform your strategy works well with. It's like saying, \"My strategy is ready for this specific version of the platform.\"

"},{"location":"strategies/strategy_guides/structure/#utility-functions","title":"Utility Functions","text":"

You have the following utility function to be used in this strategy :

Links

"},{"location":"strategies/strategy_guides/structure/#get_crossover_value","title":"get_crossover_value()","text":"This handy function calculates something called the \"crossover value\" for you. It's like having a calculator that figures out this specific value for your strategy."},{"location":"strategies/strategy_guides/structure/#flowchart","title":"Flowchart","text":"

Once you create your own strategy or use a ready strategy from the pyalgostrategypool package, this is how it works internally on the AlgoBulls Core Trading Engine.

"},{"location":"support/support_pyalgo/","title":"Strategy Support - pyalgotrading","text":"

In this dedicated section, you'll find everything you need to receive the support you deserve for pyalgotrading. Whether it's troubleshooting an issue or seeking clarification, we've got you covered every step of the way. Requesting Support from pyalgotrading Module:

If you're looking to raise a support request from pyalgotrading module, follow these simple steps: - Start by executing your strategy from the pyalgotrading module. - Next, navigate to the \"My Coded Strategies\" section in python build web.

My Coded Strategies: This section displays all the strategies you've created or modified. It includes both new and updated strategies.

From this section, select the strategy you're experiencing issues with.

Need Support: If you require assistance with a specific strategy, you can raise a support request from here. Please ensure that your strategy is present in the My Coded Strategies section.

After clicking on Need Support, you'll see a popup window. Here, select the strategy for which you need assistance and explain you issue in brief.

Then, click the Submit button. Our support team will actively assist you with any issues you're facing.

"},{"location":"support/support_pybuild/","title":"Strategy Support - Python Build Web","text":"

Welcome to the realm of unparalleled support at AlgoBulls, where your algorithmic trading journey takes centre stage. Whether you're navigating the Python Build Web or harnessing the power of pyalgotrading, our commitment to your success remains unwavering. The Python Build Support page is your gateway to a world where every query, every challenge is met with expertise and dedication. We understand that your experience matters, and so does every line of code you craft.

"},{"location":"support/support_pybuild/#steps-to-get-the-support-you-need","title":"Steps to get the support you need.","text":""},{"location":"support/support_pybuild/#choose-your-strategy","title":"Choose your strategy","text":""},{"location":"support/support_pybuild/#need-support","title":"Need Support","text":""}]} \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index 214a0077b67ba7ed9ab8335a4a8660b2a5b9944e..2f72253d2e065a2071226a24161589db46579e5a 100644 GIT binary patch delta 14 Vcmcc4dYzS3zMF%iek1E8CIBN@1c3km delta 14 Vcmcc4dYzS3zMF$XX(Q_;CIBIb1S9|e