diff --git a/pyalgotrad/imgs/developer_key.png b/pyalgotrad/imgs/developer_key.png index b8b854e0..c98f13b3 100644 Binary files a/pyalgotrad/imgs/developer_key.png and b/pyalgotrad/imgs/developer_key.png differ diff --git a/pyalgotrad/imgs/purchase_plan.png b/pyalgotrad/imgs/purchase_plan.png index 67476cdc..01aec5c5 100644 Binary files a/pyalgotrad/imgs/purchase_plan.png and b/pyalgotrad/imgs/purchase_plan.png differ diff --git a/pyalgotrad/prerequisites/index.html b/pyalgotrad/prerequisites/index.html index 39e99a7f..f53946cb 100644 --- a/pyalgotrad/prerequisites/index.html +++ b/pyalgotrad/prerequisites/index.html @@ -1778,15 +1778,15 @@

Prerequisites
  • AlgoBulls Account

    -

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

    +

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

  • Developer Key

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

    diff --git a/search/search_index.json b/search/search_index.json index d5875d0f..f1a5215d 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:

    • Analyze Structure: Study code structure, including strategy definition, condition setting, and action execution.
    • Modify and Experiment: Once comfortable with examples, customise them to your preferences. Adjust parameters, conditions, and actions to observe their impact on trading outcomes.

    • Learn Strategies: Each example represents a different trading approach, like trend-following or mean-reversion. Studying these examples introduces you to various trading strategies and their underlying principles.

    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:

    • Code Examples: Real code snippets showcasing how to implement specific strategies, functions, and techniques using Python Build.
    • Python Cookbook for Algorithmic Trading: A Python Cookbook for Algorithmic Trading, explaining in-depth about strategy creation and execution from scratch using Python. Explore the technical content of the book on GitHub.
    "},{"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":"
    • The Cumulative Returns chart illustrates how our strategy's returns value has evolved over time in percentage.
    • Positive values indicate gains, while negatives reflect losses. Bigger positive returns are more favourable.
    • Keep in mind, this chart focuses on gains and losses, excluding risk and timing considerations.
    • There are 2 sub categories of cumulative returns chart depending on the scale we are using. One is normal scaled and other is log scaled
    "},{"location":"analytics/pyalgotrading_analytics/#end-of-year-returns-eoy","title":"End of Year Returns (EoY)","text":"
    • The End of Year Returns chart showcases our strategy's annual performance as a percentage.
    • It quantifies its overall performance, considering gains or losses throughout each year.
    "},{"location":"analytics/pyalgotrading_analytics/#distributions-of-monthly-returns-histogram","title":"Distributions of Monthly Returns (Histogram)","text":"
    • In the Monthly Returns Distribution Histogram, we see the frequency distribution of different levels of returns over consecutive months.
    • This histogram helps us understand the range and patterns in monthly returns, shedding light on our strategy's volatility and performance trends.
    "},{"location":"analytics/pyalgotrading_analytics/#daily-returns","title":"Daily Returns","text":"
    • The Daily Returns Chart portrays the percentage change in our strategy's returns between trading days.
    • It provides insights into short-term volatility, trend analysis, and risk assessment.
    "},{"location":"analytics/pyalgotrading_analytics/#rolling-volatility-6-months","title":"Rolling Volatility (6 months)","text":"
    • A Rolling Volatility (6 months) Plot showcases the changing volatility of an investment over time using a rolling window of six months.
    • This plot reveals how the investment's price fluctuations vary as the window moves across the dataset.
    • It provides insights into short-term volatility patterns, helping investors understand how the investment's risk level evolves in response to different market conditions.
    "},{"location":"analytics/pyalgotrading_analytics/#rolling-sharpe-6-months","title":"Rolling Sharpe (6 months)","text":"
    • A Rolling Sharpe (6 months) Plot illustrates the dynamic changes in the Sharpe ratio over time using a rolling window of six months.
    • The plot shows how the risk-adjusted performance of an investment fluctuates as the window moves through the dataset.
    • This visualization helps investors understand how the Sharpe ratio varies with changing market conditions and provides insights into the investment's consistency and risk-return trade-offs over short-term periods.
    "},{"location":"analytics/pyalgotrading_analytics/#rolling-sortino-6-months","title":"Rolling Sortino (6 months)","text":"
    • A Rolling Sortino (6 months) Plot visualizes the variation in the Sortino ratio over time using a rolling window of six months.
    • This plot demonstrates how the investment's risk-adjusted performance, considering only downside volatility, changes as the window progresses through the data.
    • It offers insights into how the Sortino ratio evolves with market conditions, helping investors assess the investment's ability to generate favorable risk-adjusted returns over short-term intervals.
    "},{"location":"analytics/pyalgotrading_analytics/#worst-5-drawdown-periods","title":"Worst 5 Drawdown Periods","text":"
    • A Worst 5 Drawdown Periods plot displays the top five periods during which the strategy experienced the largest declines from peak to trough.
    • This visualization helps strategists understand the most significant loss-making episodes in the strategy's run.
    • It shows the magnitude and duration of these drawdowns, providing insights into the strategy's risk and potential vulnerabilities.
    "},{"location":"analytics/pyalgotrading_analytics/#underwater-plot","title":"Underwater Plot","text":"
    • The Underwater Plot visually narrates our strategy's performance concerning its past peaks.
    • It showcases how much our returns value has dropped from its highest point over time.
    • This aids in visualising periods of drawdown and recovery, offering insights into historical risk and resilience.
    "},{"location":"analytics/pyalgotrading_analytics/#monthly-returns-heatmap","title":"Monthly Returns (Heatmap)","text":"
    • The Monthly Returns Heatmap offers a colour-coded view of our strategy's performance across months.
    • Shades of green indicate positive returns, while shades of red signify losses.
    • This visual tool helps spot trends and patterns, aiding in identifying strong and weak performance periods.
    "},{"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":"
    • You can run your strategies on American exchanges like NASDAQ or NYSE.
    • It helps you access the historical data as well as live data of all the stocks from Alpaca.
    • It will also help you backtest, paper trade and live trade on AlgoBulls.
    "},{"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.

    • OAuth Method: Follow the simple steps mentioned here to connect using OAuth.
    • Non-OAuth Method: For the Non-OAuth method, you can follow the steps mentioned here.

    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":"
    • Navigate to the Broking Detailspage on the AlgoBulls platform.
    • Here you will see all the brokers you have connected and their current statuses.
    "},{"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":"
    • Click on Add Broker.
    "},{"location":"brokers/connecting_alpaca/#search-for-alpaca","title":"Search for Alpaca","text":"
    • On the pop-up window that appears, you have a search bar for finding your desired broker.

    • Type Alpaca in the search dialog box

    • Click on Alpaca Paper (OAuth) for choosing your Alpaca Paper Account.
    • Click on Alpaca Live (OAuth) for choosing your Alpaca Live Account.

    "},{"location":"brokers/connecting_alpaca/#provide-permission","title":"Provide Permission","text":"
    • After clicking on Alpaca Paper (OAuth) or Alpaca Live (OAuth), you will be redirected to the Alpaca website for permission.
    • You will be asked to login if you are not already logged in.
    • On the dialog box that appears, click Allow. This will bind your Alpaca account with the AlgoBulls account.
    • On successful authorisation, you will be redirected to the AlgoBulls platform and you will be able to see your broker on the Broking Detailspage.

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

    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":"
    • Go the the official Alpaca website
    • Click on sign up for free.
    • Follow the steps there and add your details to create the account.
    "},{"location":"brokers/non_auth_alpaca/#api-keys","title":"API keys","text":"
    • After creating your account, login to access the homepage.
    • Click on View API Keys on the right side under the Quick Trade block.
    • Click on regenerate to create API and Secret Key.
    • On regenerating, you will get fresh API keys under the Key section and a secret key under the Secret section.
    "},{"location":"brokers/non_auth_alpaca/#add-broker","title":"Add Broker","text":"
    • Click on Add Broker.
    "},{"location":"brokers/non_auth_alpaca/#search-for-alpaca-non-oauth","title":"Search for Alpaca Non-OAuth","text":"
    • On the pop-up window that appears, you have a search bar for finding your desired broker..
    • Type Alpacain the search box and choose Alpaca Non-OAuth from the search results.
    "},{"location":"brokers/non_auth_alpaca/#provide-api-and-secret-key","title":"Provide API And Secret key","text":"
    • After clicking Alpaca Non-OAuth, you will see a dialog box requesting your API and Secret key.
    • Enter your keys there and click Confirm to bind Alpaca with your AlgoBulls account.
    • On successful authorisation, you will be redirected to the AlgoBulls platform and you will be able to see your broker on the Broking Details page.
    "},{"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":"
    • Parameter Name: broker_commission_percentage
    • Type: float
    • Default Value: None
    • Definition: Brokerage is the fee charged by your broker for executing a trade. It's usually a percentage of the trade value. The broker_commission_percentage parameter lets you specify the brokerage fee as a percentage.
    • Explanation: Brokers charge a fee for executing your trades, and this fee is often a percentage of your trade amount. You can adjust this parameter to match the fees your broker charges.

    • Parameter Name: broker_commission_price

    • Type: float
    • Default Value: None
    • Definition: The broker_commission_price parameter allows you to specify a fixed broker fee per trade. This fee is added on top of the percentage-based brokerage. It accounts for any flat fees associated with your trades.
    • Explanation: In addition to the percentage-based fees, some brokers charge a fixed fee for every trade. Use this parameter to include those fixed fees in your backtesting calculations.
    "},{"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.

    • Note: When both broker_commission_percentage and broker_commission_price are provided, the function will automatically calculate the brokerage cost using both parameters and select the option that results in the lower brokerage cost. This ensures that you pay the minimum brokerage fees for your trades.
    "},{"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":"
    • Powered by the AlgoBulls Platform
    • Everything related to Algorithmic Trading Strategies!
      • Free pool of Strategies are available at pyalgostrategypool!
      • Create & upload strategies easily on the cloud
      • Support for all 150+ Technical Indicators provided by TA-Lib
      • Support for multiple candlesticks patterns - Japanese OHLC, Renko, Heikin-Ashi, Linebreak
      • Support for multiple candle intervals - 1 minute, 3 minutes, 5 minutes, 10 minutes, 15 minutes, 30 minutes, 1 hour, 1 day.
      • Support for Regular Orders, Bracket Orders and Cover Orders
      • Support for MARKET, LIMIT, STOPLOSS-LIMIT, STOPLOSS-MARKET orders
      • Support for INTRADAY and DELIVERY orders
    • Support for Backtesting
    • Support for Paper Trading
    • Support for Live Trading / Real Trading
    • Support for multiple brokers for Live Trading. Check list of supported brokers here.
    • Real-time Logs for Backtesting, Paper Trading, Live Trading
    • Multiple real-time Reports available for Backtesting, Paper Trading and Live Trading:
      • Profit-&-Loss report (P&L report)
      • Statistics Report
      • Order History Log for each order with state transitions & timestamps
      • Detailed analytics with charts
    • Support for calculating Slippage
    • Support for calculating Brokerage
    • Support for importing external P&L table and generating analytics on the same
    • Plot Candlestick charts using plotly.py

    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":"
    • Bug Reporting / New Feature Request: Create a new issue on GitHub.
    • Engage in Discussion: Join fellow developers on the discussion forum.
    • Discussion Community: Join fellow algotrading ninjas on the discussion Slack
    • Additional Support: For further help, contact support@algobulls.com.
    "},{"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:

    • Step 1: Activate the Advanced Developer Plan from the Pricing menu.
    • Step 2: Get the Developer Key from the Settings section.

    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

    • It is a good idea to set up a virtual environment first while installing Python 3.10.
    • Once Python is installed, most packages are easily installed in your venv using pip install command
    "},{"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:

    • PyCharm
    • VS Code
    "},{"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

    • SELL Entry positions are allowed only if the strategy is running for INTRADAY. DELIVERY strategies do not allow SELL as entry positions. This is taken care of in the elif part.
    • The strategy_select_instruments_for_entry method is called once for every candle time. For Instance, if you submit a job with the candle time as 15 minutes, then this method will be called once for every 15 minute candle.
    • The actual Entry position (BUY/SELL) is not entered here. Here, only the instrument is selected based on the crossover value with the proper action mentioned in the meta. The Entry position will be taken in the next method below.
    • The meta contains a very versatile dictionary object. You may use it to pass any other additional information that you wish.
    "},{"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:

    • price - If you want to BUY at the market price (Last Traded Price) or LTP, then just fetch the LTP using get_ltp as shown in the code above. Store the value in ltp and pass it to price.
    • stoploss_trigger, target_trigger and trailing_stoploss_trigger - You can calculate these using the ltp and the values you will pass through the job that you will submit. The parameters will be caught as self.stoploss, self.target and self.trailing_stoploss.

    Note

    • If you plan to use Bracket Order instead of Regular Orders, then create a separate Python file for it, say strategy_sma_bracket_order.py. You can also change the class name as StrategySMABracketOrder. There will be changes in the entry and exit methods also.
    • The strategy_enter_position method is called once for every instrument. For instance, you want to run this strategy for 5 instruments. Say that the strategy_select_instruments_for_entry method selects 3 instruments for ENTRY positions (BUY/SELL). Then, the strategy_enter_position method will be called thrice, once for each instrument respectively within the candle time frame (say, 15 minutes).
    "},{"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

    • The actual Exit position (BUY/SELL) is not entered here. Here, only the instrument is selected based on the crossover value with the proper action mentioned in the meta. The Exit position will be taken in the next method below.
    • The meta contains a very versatile dictionary object. You may use it to pass any other additional information that you wish.
    • Whenever a new trading day starts, the strategy_select_instruments_for_exit is called first. This is very important for DELIVERY strategies. Many instruments might be holding in an Entry Position at the end of the previous trading day, and they might be eligible for exit at the start of the new trading day.
    "},{"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

    • The order of values passed to the crossover method of the utils package is very important.
    • Example: you have 2 SMA values, 5 and 12. The strategy describes that there should be an BUY Entry Position when SMA(5) cuts SMA(12) upwards (crossover value should be 1).
    • In this case, if you mistakenly pass SMA(12) value first and SMA(5) value next to the crossover function, the answer you will get is -1 (Cut downwards).
    • Though, the crossover value is correct, the strategy is expecting to BUY at crossover 1 as per the code, which will not work now.
    • Therefore, the strategy will work correctly only if you pass SMA(5) first and then SMA(12) to the crossover function, thus making the order of parameters passed an important point to be aware of, while coding the strategy.
    "},{"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":"
    • The Cumulative Returns chart illustrates how our strategy's returns value has evolved over time in percentage.
    • Positive values indicate gains, while negatives reflect losses. Bigger positive returns are more favourable.
    • Keep in mind, this chart focuses on gains and losses, excluding risk and timing considerations.
    • There are 2 sub categories of cumulative returns chart depending on the scale we are using. One is normal scaled and other is log scaled
    "},{"location":"pyalgotrad/pyalgotrading_analytics/#end-of-year-returns-eoy","title":"End of Year Returns (EoY)","text":"
    • The End of Year Returns chart showcases our strategy's annual performance as a percentage.
    • It quantifies its overall performance, considering gains or losses throughout each year.
    "},{"location":"pyalgotrad/pyalgotrading_analytics/#distributions-of-monthly-returns-histogram","title":"Distributions of Monthly Returns (Histogram)","text":"
    • In the Monthly Returns Distribution Histogram, we see the frequency distribution of different levels of returns over consecutive months.
    • This histogram helps us understand the range and patterns in monthly returns, shedding light on our strategy's volatility and performance trends.
    "},{"location":"pyalgotrad/pyalgotrading_analytics/#daily-returns","title":"Daily Returns","text":"
    • The Daily Returns Chart portrays the percentage change in our strategy's returns between trading days.
    • It provides insights into short-term volatility, trend analysis, and risk assessment.
    "},{"location":"pyalgotrad/pyalgotrading_analytics/#rolling-volatility-6-months","title":"Rolling Volatility (6 months)","text":"
    • A Rolling Volatility (6 months) Plot showcases the changing volatility of an investment over time using a rolling window of six months.
    • This plot reveals how the investment's price fluctuations vary as the window moves across the dataset.
    • It provides insights into short-term volatility patterns, helping investors understand how the investment's risk level evolves in response to different market conditions.
    "},{"location":"pyalgotrad/pyalgotrading_analytics/#rolling-sharpe-6-months","title":"Rolling Sharpe (6 months)","text":"
    • A Rolling Sharpe (6 months) Plot illustrates the dynamic changes in the Sharpe ratio over time using a rolling window of six months.
    • The plot shows how the risk-adjusted performance of an investment fluctuates as the window moves through the dataset.
    • This visualization helps investors understand how the Sharpe ratio varies with changing market conditions and provides insights into the investment's consistency and risk-return trade-offs over short-term periods.
    "},{"location":"pyalgotrad/pyalgotrading_analytics/#rolling-sortino-6-months","title":"Rolling Sortino (6 months)","text":"
    • A Rolling Sortino (6 months) Plot visualizes the variation in the Sortino ratio over time using a rolling window of six months.
    • This plot demonstrates how the investment's risk-adjusted performance, considering only downside volatility, changes as the window progresses through the data.
    • It offers insights into how the Sortino ratio evolves with market conditions, helping investors assess the investment's ability to generate favorable risk-adjusted returns over short-term intervals.
    "},{"location":"pyalgotrad/pyalgotrading_analytics/#worst-5-drawdown-periods","title":"Worst 5 Drawdown Periods","text":"
    • A Worst 5 Drawdown Periods plot displays the top five periods during which the strategy experienced the largest declines from peak to trough.
    • This visualization helps strategists understand the most significant loss-making episodes in the strategy's run.
    • It shows the magnitude and duration of these drawdowns, providing insights into the strategy's risk and potential vulnerabilities.
    "},{"location":"pyalgotrad/pyalgotrading_analytics/#underwater-plot","title":"Underwater Plot","text":"
    • The Underwater Plot visually narrates our strategy's performance concerning its past peaks.
    • It showcases how much our returns value has dropped from its highest point over time.
    • This aids in visualising periods of drawdown and recovery, offering insights into historical risk and resilience.
    "},{"location":"pyalgotrad/pyalgotrading_analytics/#monthly-returns-heatmap","title":"Monthly Returns (Heatmap)","text":"
    • The Monthly Returns Heatmap offers a colour-coded view of our strategy's performance across months.
    • Shades of green indicate positive returns, while shades of red signify losses.
    • This visual tool helps spot trends and patterns, aiding in identifying strong and weak performance periods.
    "},{"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:

    • Your strategy is already uploaded on the AlgoBulls account and you want to search or select it

    OR

    • You have saved the strategy from the AlgoBulls Website
    "},{"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":"
    • Make sure you have an active working AlgoBulls account ready to go!
    • Open a Jupyter Notebook.
    • If you have coded the strategy yourself and not used a ready strategy from the pyalgostrategypool package, then make sure your strategy file (.py) and the Jupyter Notebook are in the same folder.
    "},{"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.

    • Import a ready strategy

      from pyalgostrategypool.strategy_ema_regular_order import StrategyEMARegularOrder\n

    • Import your own strategy

      from strategy_sma_regular_order import StrategySMARegularOrder\n

    "},{"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":"
    • Search your strategy using strategy name. Make sure you have the strategy with given name in your AlgoBulls Account.
          strategy_name = 'Exponential Moving Averages Crossover'\n    strategy_code, strategy_name = all_strategies_df.loc[all_strategies_df['strategyName'] == strategy_name].iloc[0]        \n
    • Search your strategy using strategy code. Make sure you have the strategy with given code in your AlgoBulls Account.
      strategy_code = 'afd6214c5db94dbeae7502e861fa4ffc'\nstrategycode, strategyname = all_strategies_df.loc[all_strategies_df['strategyCode'] == strategy_code].iloc[0]\n
    "},{"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":"
    • Parameter Name: slippage_percent
    • Type: float
    • Default Value: None
    • Definition: Slippage is the difference between the expected execution price of a trade and the actual execution price. It often occurs due to market volatility and the time it takes to execute an order. Slippage can have a significant impact on trading results, and this parameter allows you to simulate it.
    • Explanation: Imagine you're trading and placing an order at a specific price, but the market moves quickly. Slippage accounts for the price difference between what you expected and what you actually get. Use this parameter to make your backtesting experience more realistic.
    "},{"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:

    • Backtesting
    • Paper Trading
    • Real Trading
    "},{"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

    • Keep a unique file name
    • Make sure that the file name is in lowercase and that each word is separated with an underscore '_' as shown above.

    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

    • There are 2 variations when fetching logs:
      • Progressive Logs (print_live_logs = True): will show progress bar and update the latest logs as the strategy is executed
      • Complete Logs (print_live_logs = False): will fetch logs after strategy is executed.(It wont update the latest logs, unless called manually again)

    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

    • Order History for Real Trading is not supported by brokers.
    • Order History for Backtesting, Paper Trading and Real Trading is supported by the AlgoBulls Virtual Brokers.
    "},{"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:

    • Coding the complete strategy from the Create page.

    OR

    • Picking up a ready strategy from the pyalgostrategypool package.
    "},{"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":"
    • Make sure you have an active working AlgoBulls account ready to go!
    • Open a Jupyter Notebook.
    • If you have coded the strategy yourself and not used a ready strategy from the pyalgostrategypool package, then make sure your strategy file (.py) and the Jupyter Notebook are in the same folder.
    "},{"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
    • Import a ready strategy

      from pyalgostrategypool.strategy_ema_regular_order import StrategyEMARegularOrder\n

    • Import your own strategy

      from strategy_sma_regular_order import StrategySMARegularOrder\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

    • Code Structure of Strategy (workflow of a strategy)
    "},{"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

    • The parameter names and the number of parameters may change for different strategies.
    "},{"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":"
    • Stores the order object for the given tags. eg:
    self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
    • Here the _order is the order object stored inside the OrderTagManager for the tags base_inst_str and entry_key.
    "},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#get_orders","title":"get_orders","text":"
    • Retrieve the order(s) for the given tags.

    eg:

    self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
    • Here the order object retrieved from the OrderTagManager for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER and entry_key
    "},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#remove_tags","title":"remove_tags","text":"
    • Removes the tags stored in the OrderTagManager along with the orders related stored in that tag

    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":"
    • Remove the order(s) from the OrderTagManager for the given tag(s).

    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":"
    • In this method we process each instrument in the instruments bucket, if there is some entry condition to be checked then we create a get_entry_decision method that calculates the entry condition like a crossover or compares the latest value of the OHLC data or indicator data.

    • When the order has to be placed we add the instrument to selectd_instruments_bucket and additional data related to the instrument that will be required while placing to the sideband_info. This information is passed to the strategy_enter_position method

    "},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#strategy_enter_position","title":"strategy_enter_position","text":"
    • Here is where we actually place the entry order for which we calculate the quantity for the order to be placed. If the order is placed successfully we save the order in a class variable such that we can access the order object via the variable in the exit methods.
    "},{"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":"
    • This method is called before the entry methods because in the case of delivery strategy we want to resume and exit previous day orders before we can place new entry orders.
    • Here we place stoploss exit orders, target exit orders, and check for exit conditions for the open entry orders.
    "},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#strategy_exit_position","title":"strategy_exit_position","text":"
    • Here is where we actually place the exit order for where we exit the order which was placed during entry. If the order is placed successfully we clear the order in a class variable such that we can add new orders to the vacant place in variable in the entry methods.
    "},{"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":"
    • Options Bear Call Ladder
    • Options Bear Put Ladder
    • Options Bull Call Ladder
    • Options Bull Put Ladder
    • Options Long Iron Butterfly
    • Options Straddle
    • Options Strangle

    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

    • Code Structure of Strategy (workflow of a strategy)
    "},{"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

    • The parameter names and the number of parameters may be different for different strategies.
    "},{"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":"
    • Stores the order object for the given tags. eg:
      self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
    • Here the _order is the order object stored inside the OrderTagManager for the tags base_inst_str and entry_key.
    "},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#get_orders","title":"get_orders","text":"
    • Retrieve the order(s) for the given tags. eg:
      self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
    • Here the order object retrieved from the OrderTagManager for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER and entry_key
    "},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#remove_tags","title":"remove_tags","text":"
    • Removes the tags stored in the OrderTagManager along with the orders related stored in that tag 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 the order tags.

    "},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#remove_order","title":"remove_order","text":"
    • Remove the order(s) from the OrderTagManager for the given tag(s). 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_regular_strategy/#get_internals","title":"get_internals","text":"
    • Returns the values i.e. both the entry and exit orders stored inside the tags list.
    "},{"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":"
    • In this method we process each instrument in the instruments bucket, if there is some entry condition to be checked then we create an get_entry_decision method that calculates the entry condition like a crossover or compares the latest value of the OHLC data or indicator data.

    • When the order has to be placed we add the instrument to selected_instruments_bucket and additional data related to the instrument that will be required while placing to the sideband_info. This information is passed to the strategy_enter_position method

    "},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#strategy_enter_position","title":"strategy_enter_position","text":"
    • Here is where we actually place the entry order for which we calculate the quantity for the order to be placed. If the order is placed successfully we save the order in a class variable such that we can access the order object via the variable in the exit methods.
    "},{"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":"
    • This method is called before the entry methods because in the case of delivery strategy we want to resume and exit previous day orders before we can place new entry orders.
    • Here we place stoploss exit orders, target exit orders, and check for exit conditions for the open entry orders.
    "},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#strategy_exit_position","title":"strategy_exit_position","text":"
    • Here is where we actually place the exit order for where we exit the order which was placed during entry. If the order is placed successfully we clear the order in a class variable such that we can add new orders to the vacant place in variable in the entry methods.
    "},{"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":"
    • Aroon Crossover
    • Bollinger Bands
    • EMA Crossover
    • Inverse EMA Scalping
    • Reverse RSI
    • Stochastic Crossover
    • VWAP Crossover

    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

    • For pyalgotrading check here.
    • For Python Build Web check here.
    "},{"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

    • Strategy Structure (regular)
    • Strategy Structure (options)
    "},{"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":"
    • The Cumulative Returns chart illustrates how our strategy's returns value has evolved over time in percentage.
    • Positive values indicate gains, while negatives reflect losses. Bigger positive returns are more favourable.
    • Keep in mind, this chart focuses on gains and losses, excluding risk and timing considerations.
    • There are 2 sub categories of cumulative returns chart depending on the scale we are using. One is normal scaled and other is log scaled
    "},{"location":"python_build/pyalgotrading_analytics/#end-of-year-returns-eoy","title":"End of Year Returns (EoY)","text":"
    • The End of Year Returns chart showcases our strategy's annual performance as a percentage.
    • It quantifies its overall performance, considering gains or losses throughout each year.
    "},{"location":"python_build/pyalgotrading_analytics/#distributions-of-monthly-returns-histogram","title":"Distributions of Monthly Returns (Histogram)","text":"
    • In the Monthly Returns Distribution Histogram, we see the frequency distribution of different levels of returns over consecutive months.
    • This histogram helps us understand the range and patterns in monthly returns, shedding light on our strategy's volatility and performance trends.
    "},{"location":"python_build/pyalgotrading_analytics/#daily-returns","title":"Daily Returns","text":"
    • The Daily Returns Chart portrays the percentage change in our strategy's returns between trading days.
    • It provides insights into short-term volatility, trend analysis, and risk assessment.
    "},{"location":"python_build/pyalgotrading_analytics/#rolling-volatility-6-months","title":"Rolling Volatility (6 months)","text":"
    • A Rolling Volatility (6 months) Plot showcases the changing volatility of an investment over time using a rolling window of six months.
    • This plot reveals how the investment's price fluctuations vary as the window moves across the dataset.
    • It provides insights into short-term volatility patterns, helping investors understand how the investment's risk level evolves in response to different market conditions.
    "},{"location":"python_build/pyalgotrading_analytics/#rolling-sharpe-6-months","title":"Rolling Sharpe (6 months)","text":"
    • A Rolling Sharpe (6 months) Plot illustrates the dynamic changes in the Sharpe ratio over time using a rolling window of six months.
    • The plot shows how the risk-adjusted performance of an investment fluctuates as the window moves through the dataset.
    • This visualization helps investors understand how the Sharpe ratio varies with changing market conditions and provides insights into the investment's consistency and risk-return trade-offs over short-term periods.
    "},{"location":"python_build/pyalgotrading_analytics/#rolling-sortino-6-months","title":"Rolling Sortino (6 months)","text":"
    • A Rolling Sortino (6 months) Plot visualizes the variation in the Sortino ratio over time using a rolling window of six months.
    • This plot demonstrates how the investment's risk-adjusted performance, considering only downside volatility, changes as the window progresses through the data.
    • It offers insights into how the Sortino ratio evolves with market conditions, helping investors assess the investment's ability to generate favorable risk-adjusted returns over short-term intervals.
    "},{"location":"python_build/pyalgotrading_analytics/#worst-5-drawdown-periods","title":"Worst 5 Drawdown Periods","text":"
    • A Worst 5 Drawdown Periods plot displays the top five periods during which the strategy experienced the largest declines from peak to trough.
    • This visualization helps strategists understand the most significant loss-making episodes in the strategy's run.
    • It shows the magnitude and duration of these drawdowns, providing insights into the strategy's risk and potential vulnerabilities.
    "},{"location":"python_build/pyalgotrading_analytics/#underwater-plot","title":"Underwater Plot","text":"
    • The Underwater Plot visually narrates our strategy's performance concerning its past peaks.
    • It showcases how much our returns value has dropped from its highest point over time.
    • This aids in visualising periods of drawdown and recovery, offering insights into historical risk and resilience.
    "},{"location":"python_build/pyalgotrading_analytics/#monthly-returns-heatmap","title":"Monthly Returns (Heatmap)","text":"
    • The Monthly Returns Heatmap offers a colour-coded view of our strategy's performance across months.
    • Shades of green indicate positive returns, while shades of red signify losses.
    • This visual tool helps spot trends and patterns, aiding in identifying strong and weak performance periods.
    "},{"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":"
    • Here you can select the allowed exchanges from the drop box given on the left (eg: NASDAQ, NYSE, NSE etc.)
    • Once you have selected the exchange you can search the instrument in the search-box right beside it
    "},{"location":"python_build/python-build-config-parameters/#strategy-settings","title":"Strategy Settings","text":"
    • Here you can select the candle size, it is the size of candle on which you are running your strategy is going to be executed
    • You can even select the mode i.e. INTRADAY or DELIVERY
    "},{"location":"python_build/python-build-config-parameters/#order-settings","title":"Order Settings","text":"
    • You can adjust your orders, on how they will act when the strategy is 'Resumed' or strategy is 'Exited'
    • Resume Positions from Start: If you have previous trades in your strategy, you can resume your strategy without deleting or overwriting them. Only applicable for DELIVERY mode.
    • Exit Intraday Orders on Stop: If checked, strategy will square-off positions automatically at the end of each trading day.
    • Max Order Count: Maximum number of orders your strategy will execute per day. Once this limit is completed for the day, all BUY/SELL signals for new orders would be automatically ignored.
    • Crossover Accuracy Decimal: When running a crossover strategy, the number of decimals of the underlying indicators to be taken do decide an upward cut, downward cut or no cut.
    • Credit Exposure Factor: Applicable only for Live Trading. Use this to set the exposure limit given by your broker. System will take available funds as 'current fund balance X credit exposure factor' for executing the strategy
    "},{"location":"python_build/python-build-config-parameters/#user-parameters","title":"User Parameters","text":"
    • Use this option to pass various values of the strategy parameters from outside, without changing the code base for every execution. They are accessible as a dictionary called strategy_parameters inside your strategy class' constructor method.
    • You can customize/create your own parameters for the strategy. Click on +Add New Parameter to begin adding them. They should match with the parameters you have defined in your Python class.

    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.

    • Advanced Python Build Plan: Develop your own Algorithmic Trading Strategy for Free along with Analytics support, concurrent Strategy Executions, Professional Support, and more.

    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

    • Code Structure of Strategy (workflow of a strategy)
    "},{"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

    • The parameter names and the number of parameters may change for different strategies.
    "},{"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":"
    • Stores the order object for the given tags. eg:
    self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
    • Here the _order is the order object stored inside the OrderTagManager for the tags base_inst_str and entry_key.
    "},{"location":"python_build/strategy_guides/common_options_strategy/#get_orders","title":"get_orders","text":"
    • Retrieve the order(s) for the given tags.

    eg:

    self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
    • Here the order object retrieved from the OrderTagManager for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER and entry_key
    "},{"location":"python_build/strategy_guides/common_options_strategy/#remove_tags","title":"remove_tags","text":"
    • Removes the tags stored in the OrderTagManager along with the orders related stored in that tag

    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":"
    • Remove the order(s) from the OrderTagManager for the given tag(s).

    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":"
    • In this method we process each instrument in the instruments bucket, if there is some entry condition to be checked then we create a get_entry_decision method that calculates the entry condition like a crossover or compares the latest value of the OHLC data or indicator data.

    • When the order has to be placed we add the instrument to selectd_instruments_bucket and additional data related to the instrument that will be required while placing to the sideband_info. This information is passed to the strategy_enter_position method

    "},{"location":"python_build/strategy_guides/common_options_strategy/#strategy_enter_position","title":"strategy_enter_position","text":"
    • Here is where we actually place the entry order for which we calculate the quantity for the order to be placed. If the order is placed successfully we save the order in a class variable such that we can access the order object via the variable in the exit methods.
    "},{"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":"
    • This method is called before the entry methods because in the case of delivery strategy we want to resume and exit previous day orders before we can place new entry orders.
    • Here we place stoploss exit orders, target exit orders, and check for exit conditions for the open entry orders.
    "},{"location":"python_build/strategy_guides/common_options_strategy/#strategy_exit_position","title":"strategy_exit_position","text":"
    • Here is where we actually place the exit order for where we exit the order which was placed during entry. If the order is placed successfully we clear the order in a class variable such that we can add new orders to the vacant place in variable in the entry methods.
    "},{"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":"
    • Options Bear Call Ladder
    • Options Bear Put Ladder
    • Options Bull Call Ladder
    • Options Bull Put Ladder
    • Options Long Iron Butterfly
    • Options Straddle
    • Options Strangle

    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

    • Code Structure of Strategy (workflow of a strategy)
    "},{"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

    • The parameter names and the number of parameters may be different for different strategies.
    "},{"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":"
    • Stores the order object for the given tags. eg:
      self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
    • Here the _order is the order object stored inside the OrderTagManager for the tags base_inst_str and entry_key.
    "},{"location":"python_build/strategy_guides/common_regular_strategy/#get_orders","title":"get_orders","text":"
    • Retrieve the order(s) for the given tags. eg:
      self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
    • Here the order object retrieved from the OrderTagManager for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER and entry_key
    "},{"location":"python_build/strategy_guides/common_regular_strategy/#remove_tags","title":"remove_tags","text":"
    • Removes the tags stored in the OrderTagManager along with the orders related stored in that tag 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 the order tags.

    "},{"location":"python_build/strategy_guides/common_regular_strategy/#remove_order","title":"remove_order","text":"
    • Remove the order(s) from the OrderTagManager for the given tag(s). 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_regular_strategy/#get_internals","title":"get_internals","text":"
    • Returns the values i.e. both the entry and exit orders stored inside the tags list.
    "},{"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":"
    • In this method we process each instrument in the instruments bucket, if there is some entry condition to be checked then we create an get_entry_decision method that calculates the entry condition like a crossover or compares the latest value of the OHLC data or indicator data.

    • When the order has to be placed we add the instrument to selected_instruments_bucket and additional data related to the instrument that will be required while placing to the sideband_info. This information is passed to the strategy_enter_position method

    "},{"location":"python_build/strategy_guides/common_regular_strategy/#strategy_enter_position","title":"strategy_enter_position","text":"
    • Here is where we actually place the entry order for which we calculate the quantity for the order to be placed. If the order is placed successfully we save the order in a class variable such that we can access the order object via the variable in the exit methods.
    "},{"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":"
    • This method is called before the entry methods because in the case of delivery strategy we want to resume and exit previous day orders before we can place new entry orders.
    • Here we place stoploss exit orders, target exit orders, and check for exit conditions for the open entry orders.
    "},{"location":"python_build/strategy_guides/common_regular_strategy/#strategy_exit_position","title":"strategy_exit_position","text":"
    • Here is where we actually place the exit order for where we exit the order which was placed during entry. If the order is placed successfully we clear the order in a class variable such that we can add new orders to the vacant place in variable in the entry methods.
    "},{"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":"
    • Aroon Crossover
    • Bollinger Bands
    • EMA Crossover
    • Inverse EMA Scalping
    • Reverse RSI
    • Stochastic Crossover
    • VWAP Crossover

    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

    • For pyalgotrading check here.
    • For Python Build Web check here.
    "},{"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

    • Strategy Structure (regular)
    • Strategy Structure (options)
    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebooks for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.

    Jupyter Notebook for US Exchange (NASDAQ)

    • Click here to view a working notebook for NASDAQ exchange in cloud. No installation required.
    • Click here to execute a working notebook for NASDAQ exchange in cloud. No installation required.
    "},{"location":"strategies/aroon_crossover/#aroon-indicator","title":"Aroon Indicator","text":"
    • In the stock market, Aroon refers to the Aroon indicator, which is a technical analysis tool used to measure the strength and direction of a trend. It consists of two lines, the Aroon-Up line and the Aroon-Down line.

    • The Aroon-Up line measures the number of periods since the highest price within a given period, while the Aroon-Down line measures the number of periods since the lowest price within a given period. The Aroon indicator ranges from 0 to 100, with values closer to 100 indicating a strong trend and values closer to 0 indicating a weak or non-existent trend.

    • Traders and investors use the Aroon indicator to identify potential trend reversals, assess the strength of a trend, and generate buy or sell signals. For example, when the Aroon-Up line crosses above the Aroon-Down line, it may suggest a bullish trend, while a cross below may indicate a bearish trend.

    • It is important to note that the Aroon indicator is just one of many tools used in technical analysis, and its effectiveness can vary depending on market conditions and other factors. It is often used in conjunction with other indicators and analysis techniques to make informed trading decisions.

    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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebooks for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.

    Jupyter Notebook for US Exchange (NASDAQ)

    • Click here to view a working notebook for NASDAQ exchange in cloud. No installation required.
    • Click here to execute a working notebook for NASDAQ exchange in cloud. No installation required.
    "},{"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:

    • The middle band is a moving average, while the upper and lower bands are calculated by adding/subtracting standard deviations from the middle band.
    • Bollinger Bands help assess price volatility and identify potential overbought or oversold market conditions.
    • A narrowing of the bands (Bollinger Squeeze) suggests low volatility, often followed by increased volatility and potential price breakout.
    • Touching or exceeding the upper band may indicate an overbought market, while touching or falling below the lower band may suggest an oversold market.
    • Price reversals can be observed when the price moves from one band to the other.
    • The upper and lower bands can act as dynamic support and resistance levels.
    • Bollinger Bands are used in combination with other indicators and analysis techniques to make trading decisions. They are not a standalone strategy but provide valuable insights when combined with other tools like the RSI.
    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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebooks for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.

    Jupyter Notebook for US Exchange (NASDAQ)

    • Click here to view a working notebook for NASDAQ exchange in cloud. No installation required.
    • Click here to execute a working notebook for NASDAQ exchange in cloud. No installation required.
    "},{"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:

    • An Exponential Moving Average is a type of moving average that assigns more weight to recent prices, making it more responsive to current market conditions.
    • Unlike the SMA, which gives equal weight to all data points, the EMA assigns exponentially decreasing weights to older data points.
    • The formula for calculating an EMA involves using a smoothing factor or multiplier that determines the weight given to the previous EMA value and the current price.
    • The most common period used for EMAs is 12 and 26 days, representing short-term and long-term trends, respectively.
    • EMAs are commonly used to identify trend direction, support and resistance levels, and potential entry or exit points.
    • When the price crosses above the EMA, it may signal a bullish trend, while a cross below the EMA may suggest a bearish trend.
    • The EMA is more responsive to price changes compared to the SMA, making it useful for short-term trading strategies.
    • EMAs are often used in conjunction with other technical indicators, such as the Moving Average Convergence Divergence (MACD), to generate trading signals.
    • Traders and investors use Exponential Moving Averages to smooth out price fluctuations, identify trend reversals, and determine potential support and resistance levels. They provide a visual representation of the average price over a specific period, with greater weight given to recent prices.
    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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebooks for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.

    Jupyter Notebooks for US Exchange (NASDAQ)

    • Click here to view a working notebook for NASDAQ exchange in cloud. No installation required.
    • Click here to execute a working notebook for NASDAQ exchange in cloud. No installation required.
    "},{"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:

    • Inverse EMA is calculated by applying the EMA formula in reverse, giving greater weight to older data points and less weight to recent prices.
    • Instead of smoothing out price fluctuations like the EMA, the Inverse EMA amplifies them, making it more responsive to historical data.
    • The formula for calculating Inverse EMA is similar to the EMA, but it uses a different smoothing factor or multiplier that assigns higher weight to older data points.
    • The Inverse EMA is primarily used to identify historical patterns and potential turning points in the market.
    • When the price crosses above the Inverse EMA, it may suggest a potential reversal from a downtrend to an uptrend, and vice versa when the price crosses below the Inverse EMA.
    • Inverse EMA is not as widely used as the EMA or other moving averages, and its applications may vary among traders and analysts.
    • Inverse EMA is a less commonly used variation of the Exponential Moving Average. While the EMA is designed to provide a smoothed average of recent prices, the Inverse EMA emphasizes historical data, potentially highlighting significant turning points in the market. Traders and analysts who utilize the Inverse EMA may incorporate it into their technical analysis toolkit to complement other indicators and gain insights into price reversals and historical patterns.
    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.
    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.
    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Options from Indian Exchange (NSE)

    • Click here to view a working notebook for options from NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for options from NSE exchange in cloud. No installation required.
    "},{"location":"strategies/options_bear_call_ladder/#bear-call-ladder","title":"Bear Call Ladder","text":"
    • In the stock market, an options bear call ladder is a strategy that involves buying and selling call options with different strike prices to profit from a moderate bearish outlook on the underlying asset. It is a complex strategy that combines both long and short call positions.

    • To create a bear call ladder, an investor typically does the following:

      1. Sells a lower strike call option.
      2. Buys two higher strike call options.
      3. Sells a final even higher strike call option.
    • The bear call ladder aims to generate a limited profit if the price of the underlying asset remains below the middle strike price at expiration. The strategy benefits from time decay and a moderate decrease in the price of the underlying asset.

    • The maximum profit potential of the bear call ladder is achieved when the price of the underlying asset is below the middle strike price at expiration. If the price declines further, the profit potential remains limited. However, if the price rises above the higher strike price, the strategy can result in losses.

    • The key feature of the bear call ladder is the combination of short call options, which generate premium income, and long call options, which provide protection against unlimited losses in case the price of the underlying asset rises sharply.

    • Traders implementing the bear call ladder strategy should carefully consider factors such as the strike prices, premium costs, and expiration date to assess their risk-reward profile. It's important to note that options trading involves risks, and traders should have a thorough understanding of the strategy and associated risks before employing it in the stock market.

    • Please be aware that options trading can be complex and involves significant risks. It is always recommended to consult with a qualified financial advisor or broker before engaging in options trading activities.

    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Options from Indian Exchange (NSE)

    • Click here to view a working notebook for options from NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for options from NSE exchange in cloud. No installation required.
    "},{"location":"strategies/options_bear_put_ladder/#bear-put-ladder","title":"Bear Put Ladder","text":"
    • In the stock market, an options bear put ladder is a strategy that combines buying and selling put options with different strike prices to profit from a moderate bearish view on the underlying asset. It involves a mix of long and short put positions.

    • To implement a bear put ladder strategy, an investor generally follows these steps:

      1. Buys a put option with a lower strike price.
      2. Sells two put options with higher strike prices.
      3. Buys a final put option with an even higher strike price.
    • The goal of the bear put ladder is to generate a limited profit if the price of the underlying asset remains below the middle strike price at expiration. The strategy benefits from time decay and a moderate decline in the price of the underlying asset.

    • The maximum profit potential is reached when the price of the underlying asset is below the middle strike price at expiration. If the price continues to decrease, the profit potential remains limited. However, if the price rises above the higher strike price, the strategy can result in losses.

    • The bear put ladder strategy combines short put options to generate premium income and long put options to provide protection against significant losses in case the price of the underlying asset declines substantially.

    • Traders implementing the bear put ladder strategy should consider factors such as the strike prices, premium costs, and expiration date to assess the risk-reward profile. It's crucial to have a comprehensive understanding of options trading and associated risks before employing this strategy in the stock market.

    • Keep in mind that options trading can be complex and involves substantial risks. It is advisable to consult with a qualified financial advisor or broker before engaging in options trading activities.

    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Options from Indian Exchange (NSE)

    • Click here to view a working notebook for options from NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for options from NSE exchange in cloud. No installation required.
    "},{"location":"strategies/options_bull_call_ladder/#bull-call-ladder","title":"Bull Call Ladder","text":"
    • In the stock market, an options bull call ladder is a strategy that involves buying and selling call options with different strike prices to profit from a moderate bullish outlook on the underlying asset. It is a complex strategy that combines both long and short call positions.

    • To create a bull call ladder, an investor typically does the following:

      1. Buys a lower strike call option.
      2. Sells two higher strike call options.
      3. Buys a final even higher strike call option.
    • The key feature of the bull call ladder is that it provides limited risk and potential for limited profit. The strategy is constructed in such a way that it can benefit from both a moderate rise in the price of the underlying asset and from time decay.

    • The profit potential of the bull call ladder is highest if the price of the underlying asset rises to the level of the middle strike price at expiration. In this case, the investor can achieve the maximum profit. If the price of the underlying asset rises above the middle strike price, the profit potential is limited.

    • On the other hand, if the price of the underlying asset remains below the lower strike price or declines, the strategy can result in losses. The maximum loss occurs if the price falls below the lower strike price.

    • The bull call ladder is a moderately bullish strategy that aims to benefit from both time decay and the potential for a moderate increase in the price of the underlying asset. Traders implementing this strategy should carefully consider factors such as the strike prices, premium costs, and expiration date to assess their risk-reward profile.

    • It is important to note that options trading involves risks, and traders should have a thorough understanding of the strategy and associated risks before employing it in the stock market.

    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Options from Indian Exchange (NSE)

    • Click here to view a working notebook for options from NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for options from NSE exchange in cloud. No installation required.
    "},{"location":"strategies/options_bull_put_ladder/#bull-put-ladder","title":"Bull Put ladder","text":"
    • In the stock market, an options bull put ladder is a strategy that involves buying and selling put options with different strike prices to profit from a moderate bullish outlook on the underlying asset. It is a complex strategy that combines both long and short put positions.

    • To create a bull put ladder, an investor typically does the following:

      1. Sells a higher strike put option.
      2. Buys two lower strike put options.
      3. Sells a final even lower strike put option.
    • The key feature of the bull put ladder is that it provides limited risk and potential for limited profit. The strategy is constructed in such a way that it can benefit from both a moderate rise in the price of the underlying asset and from time decay.

    • The profit potential of the bull put ladder is highest if the price of the underlying asset rises to the level of the middle strike price at expiration. In this case, the investor can achieve the maximum profit. If the price of the underlying asset rises above the middle strike price, the profit potential is limited.

    • On the other hand, if the price of the underlying asset remains above the higher strike price or increases, the strategy can result in losses. The maximum loss occurs if the price rises above the higher strike price.

    • The bull put ladder is a moderately bullish strategy that aims to benefit from both time decay and the potential for a moderate increase in the price of the underlying asset. Traders implementing this strategy should carefully consider factors such as the strike prices, premium costs, and expiration date to assess their risk-reward profile.

    • It is important to note that options trading involves risks, and traders should have a thorough understanding of the strategy and associated risks before employing it in the stock market.

    "},{"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":"
    • The transaction_type_map, tradingsymbol_suffix_map, and strike_direction_map dictionaries are used for mapping transaction types, trading symbol suffixes, and strike directions, respectively.

    • The strategy supports a single allowed expiry date, which can be modified for multiple expiry dates.

    • The strategy uses the get_options_instrument_with_strike_direction method from the base class to fetch child instruments.

    • The initialize method sets up the list of instruments processed for the day.

    • The options_instruments_set_up_local method sets up the Call and Put Options instruments for a given base instrument.

    • The strategy_select_instruments_for_entry method selects instruments for entry by setting up child instruments and appending them to the selected instruments list.

    • The strategy_enter_position method

    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)
    "},{"location":"strategies/options_long_iron_butterfly/#long-iron-butterfly","title":"Long Iron Butterfly","text":"
    • In the stock market, an options long iron butterfly is a complex strategy that involves buying two options with the same expiration date but different strike prices. It combines elements of both a bullish and bearish strategy and is designed to profit from low volatility in the underlying asset.

    • To create a long iron butterfly, an investor typically does the following:

      1. Buys an at-the-money (ATM) put option.
      2. Buys an ATM call option.
      3. Sells an out-of-the-money (OTM) put option with a lower strike price.
      4. Sells an OTM call option with a higher strike price.
    • The key feature of the long iron butterfly is that the sold options (OTM put and OTM call) help offset the cost of the purchased options (ATM put and ATM call). This results in a limited-risk, limited-reward strategy.

    • The strategy profits when the price of the underlying asset remains within a specific range, known as the \"profit zone.\" The profit zone is determined by the strike prices of the options involved in the strategy. If the price of the underlying asset is within this range at expiration, the investor can achieve the maximum profit.

    • However, if the price of the underlying asset moves significantly beyond the profit zone, the strategy can result in losses. The maximum loss occurs if the price falls below the lower strike price or rises above the higher strike price.

    • The long iron butterfly is commonly used when traders anticipate low volatility in the underlying asset. It is a neutral strategy that seeks to benefit from the passage of time and a decrease in implied volatility. Traders implementing this strategy should carefully analyze factors such as the strike prices, premium costs, and expiration date to determine their risk-reward profile.

    • It is important to note that options trading involves risks, and traders should have a thorough understanding of the strategy and associated risks before employing it in the stock market.

    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Options from Indian Exchange (NSE)

    • Click here to view a working notebook for options from NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.
    "},{"location":"strategies/options_straddle/#straddle-options","title":"Straddle Options","text":"
    • In the stock market, an options straddle is a strategy where an investor simultaneously purchases a call option and a put option with the same strike price and expiration date on a particular underlying asset, such as a stock. The purpose of this strategy is to profit from significant price movements in the underlying asset, regardless of whether the price goes up or down.

    • By using an options straddle, the investor is essentially betting on volatility rather than the direction of the price movement. If the price of the underlying asset experiences a substantial increase or decrease, either the call or put option will generate profits, offsetting any losses from the other option. The potential for profit is highest when there is a significant price swing, while the risk is limited to the cost of purchasing the options.

    • This strategy is often employed when traders anticipate an upcoming event or announcement that could cause significant market volatility, such as earnings reports or regulatory decisions. The goal is to take advantage of the resulting price movement, regardless of whether it is upward or downward.

    • It is important to note that options straddles can be risky as they require significant price movements to be profitable. If the price remains relatively stable, the trader may experience losses due to the cost of purchasing the options. Therefore, careful consideration of market conditions and risk management is crucial when implementing an options straddle strategy.

    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Options from Indian Exchange (NSE)

    • Click here to view a working notebook for options from NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for options from NSE exchange in cloud. No installation required.
    "},{"location":"strategies/options_strangle/#strangle-options","title":"Strangle Options","text":"
    • In the stock market, an options strangle is a strategy where an investor simultaneously buys or sells a call option and a put option on the same underlying asset but with different strike prices and the same expiration date. The purpose of this strategy is to profit from significant price volatility in the underlying asset.

    • Unlike an options straddle, which involves purchasing options at the same strike price, an options strangle involves selecting different strike prices. Typically, the investor buys an out-of-the-money call option (with a strike price above the current market price) and an out-of-the-money put option (with a strike price below the current market price).

    • The strategy aims to benefit from a significant price movement in either direction. If the price of the underlying asset moves significantly upwards, the call option can generate profits. Conversely, if the price moves significantly downwards, the put option can generate profits. The investor is essentially betting on increased price volatility rather than predicting the direction of the price movement.

    • Options strangles are commonly used when traders anticipate a substantial price movement but are unsure about the direction. This strategy allows for potential profits in either an upward or downward market scenario. However, it is important to note that options strangles can involve higher risks, as the underlying asset's price must move significantly to offset the cost of purchasing both options.

    • Traders employing options strangles should carefully consider factors such as the expected price volatility, the expiration date, and the costs associated with purchasing the options. Implementing risk management techniques and monitoring market conditions are essential when utilizing an options strangle strategy.

    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.

    Jupyter Notebook for US Exchange (NASDAQ)

    • Click here to view a working notebook for NASDAQ exchange in cloud. No installation required.
    • Click here to execute a working notebook for NASDAQ exchange in cloud. No installation required.
    "},{"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:

    • The Relative Strength Index (RSI) is a momentum oscillator that measures the speed and change of price movements.
    • It compares the magnitude of recent gains to recent losses over a specified period, typically 14 days, and generates a value between 0 and 100.
    • The RSI is calculated using a formula that involves averaging the upward price movements (gains) and the downward price movements (losses) over the chosen period.
    • A high RSI value (typically above 70) indicates that a stock is overbought, meaning it may have experienced a significant price increase and could be due for a correction or pullback.
    • Conversely, a low RSI value (typically below 30) suggests that a stock is oversold, indicating it may have experienced a significant price decline and could be poised for a potential rebound or upward move.
    • Traders often use RSI as a tool to identify potential trend reversals, as extreme RSI readings (above 70 or below 30) can signal a potential change in the direction of the price trend.
    • Additionally, traders may look for bullish or bearish divergences between the RSI and the price chart, which can provide further indications of a potential trend reversal.
    • The RSI is just one tool among many in technical analysis, and it is often used in conjunction with other indicators and analysis techniques to make more informed trading decisions.

    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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.
    "},{"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.

    • The RSI is an oscillator that measures the speed and change of price movements. RSI values above 70 typically indicate an overbought condition, signaling a potential price reversal to the downside. RSI values below 30 suggest an oversold condition, indicating a potential price reversal to the upside.

    • The essence of this strategy lies in the crossover of the MACD and RSI indicators. When the MACD generates a bullish crossover and the RSI confirms by being below 70 (not in an overbought condition), it could be an opportune time to consider a long (BUY) position.

    • Conversely, when the MACD produces a bearish crossover and the RSI is above 30 (not in an oversold condition), it may be a suitable moment to contemplate a short (SELL) position.

    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.

    Jupyter Notebook for US Exchange (NASDAQ)

    • Click here to view a working notebook for NASDAQ exchange in cloud. No installation required.
    • Click here to execute a working notebook for NASDAQ exchange in cloud. No installation required.
    "},{"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:

    • The Stochastic Oscillator measures the relationship between a security's closing price and its price range over a chosen period.
    • The indicator consists of two lines: %K and %D. %K represents the current closing price relative to the price range, while %D is a smoothed average of %K.
    • The Stochastic Oscillator is bound between 0 and 100. Readings above 80 are typically considered overbought, suggesting a potential price decline or correction. Readings below 20 are often considered oversold, indicating a potential price increase or rebound.
    • Traders use the Stochastic Oscillator to identify potential trend reversals, as overbought or oversold conditions can indicate a possible change in the direction of the price trend.
    • The indicator also generates bullish or bearish divergences, where the price trend and the Stochastic lines move in opposite directions, which can signal a potential trend reversal.
    • The Stochastic Oscillator has various trading strategies associated with it, such as crossovers, overbought/oversold levels, and divergences, which traders use to make buy or sell decisions.
    • It is important to note that the Stochastic Oscillator is a lagging indicator, meaning it may not provide precise timing for trade entries or exits. Therefore, it is often used in conjunction with other indicators and analysis techniques to confirm signals and improve the accuracy of trading decisions.
    • Overall, the Stochastic Oscillator is a widely used technical indicator in the stock market that helps traders assess price momentum, identify overbought and oversold conditions, and spot potential trend reversals. By analyzing the relationship between the closing price and price range, traders can gain insights into potential buying or selling opportunities.
    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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.
    "},{"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.

    • ATR serves as a reliable volatility indicator. It quantifies the market's propensity for price movement. Elevated ATR values indicate significant price fluctuations, while lower values suggest relative price stability.

    • ATR is adaptable to individual trading preferences. Traders can tailor the ATR period to match their specific trading style. For daily charts, a typical choice is the 14-day period, but adjustments can be made for shorter or longer timeframes, allowing for versatile application.

    • ATR provides a numerical value, and its magnitude corresponds to the extent of market volatility. Larger ATR values signal more significant trading opportunities, much like a roller coaster promising an exhilarating ride.

    • However, ATR isn't solely focused on turbulence. It effectively identifies periods of low volatility or consolidation in the market, signaling a need for caution or a potential shift in trading strategies.

    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.

    Jupyter Notebook for US Exchange (NASDAQ)

    • Click here to view a working notebook for NASDAQ exchange in cloud. No installation required.
    • Click here to execute a working notebook for NASDAQ exchange in cloud. No installation required.
    "},{"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:

    • VWAP is calculated by multiplying the price of each trade by the corresponding volume and then summing up these values over a specific time period. The total value is divided by the cumulative volume to obtain the average price.
    • The volume-weighted aspect of VWAP gives more weight to trades with higher volume, reflecting the significance of larger trades in the overall average price calculation.
    • VWAP is typically calculated on an intraday basis, such as the trading day or a specific session, and resets at the start of each new period.
    • Traders and investors use VWAP as a benchmark to assess whether their own trades are executed at a better or worse price compared to the average market price. It helps evaluate the quality of their execution and determine if they are buying or selling at a favorable price.
    • VWAP is commonly used by institutional traders who execute large orders as it helps them minimize market impact and avoid unfavorable executions. By comparing their execution price to VWAP, they can assess their performance and adjust their trading strategies accordingly.
    • In addition to being used as a benchmark, VWAP is also employed as a trading strategy. Some traders use VWAP as a reference point for making buy or sell decisions. For example, if the current price is above VWAP, it may be considered bullish, while a price below VWAP could be seen as bearish.
    • VWAP is often displayed as a line on intraday price charts, allowing traders to visually compare the current price to the average price. It can provide insights into the market's overall sentiment and potential support or resistance levels.
    • It is important to note that VWAP is a lagging indicator since it is based on historical data. Therefore, it is often used in combination with other indicators and analysis techniques to validate trade signals and make informed trading decisions.
    • Overall, VWAP is a widely used indicator in the stock market that provides a volume-weighted average price, serving as a benchmark for evaluating trade execution quality and as a reference point for trading decisions. By considering both price and volume, VWAP offers insights into market dynamics and helps traders assess their performance relative to the average market price.
    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

    • Code Structure of Strategy (workflow of a strategy)
    "},{"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

    • The parameter names and the number of parameters may change for different strategies.
    "},{"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":"
    • Stores the order object for the given tags. eg:
    self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
    • Here the _order is the order object stored inside the OrderTagManager for the tags base_inst_str and entry_key.
    "},{"location":"strategies/strategy_guides/common_options_strategy/#get_orders","title":"get_orders","text":"
    • Retrieve the order(s) for the given tags.

    eg:

    self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
    • Here the order object retrieved from the OrderTagManager for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER and entry_key
    "},{"location":"strategies/strategy_guides/common_options_strategy/#remove_tags","title":"remove_tags","text":"
    • Removes the tags stored in the OrderTagManager along with the orders related stored in that tag

    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":"
    • Remove the order(s) from the OrderTagManager for the given tag(s).

    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":"
    • In this method we process each instrument in the instruments bucket, if there is some entry condition to be checked then we create a get_entry_decision method that calculates the entry condition like a crossover or compares the latest value of the OHLC data or indicator data.

    • When the order has to be placed we add the instrument to selectd_instruments_bucket and additional data related to the instrument that will be required while placing to the sideband_info. This information is passed to the strategy_enter_position method

    "},{"location":"strategies/strategy_guides/common_options_strategy/#strategy_enter_position","title":"strategy_enter_position","text":"
    • Here is where we actually place the entry order for which we calculate the quantity for the order to be placed. If the order is placed successfully we save the order in a class variable such that we can access the order object via the variable in the exit methods.
    "},{"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":"
    • This method is called before the entry methods because in the case of delivery strategy we want to resume and exit previous day orders before we can place new entry orders.
    • Here we place stoploss exit orders, target exit orders, and check for exit conditions for the open entry orders.
    "},{"location":"strategies/strategy_guides/common_options_strategy/#strategy_exit_position","title":"strategy_exit_position","text":"
    • Here is where we actually place the exit order for where we exit the order which was placed during entry. If the order is placed successfully we clear the order in a class variable such that we can add new orders to the vacant place in variable in the entry methods.
    "},{"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":"
    • Options Bear Call Ladder
    • Options Bear Put Ladder
    • Options Bull Call Ladder
    • Options Bull Put Ladder
    • Options Long Iron Butterfly
    • Options Straddle
    • Options Strangle

    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

    • Code Structure of Strategy (workflow of a strategy)
    "},{"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

    • The parameter names and the number of parameters may be different for different strategies.
    "},{"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":"
    • Stores the order object for the given tags. eg:
      self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
    • Here the _order is the order object stored inside the OrderTagManager for the tags base_inst_str and entry_key.
    "},{"location":"strategies/strategy_guides/common_regular_strategy/#get_orders","title":"get_orders","text":"
    • Retrieve the order(s) for the given tags. eg:
      self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
    • Here the order object retrieved from the OrderTagManager for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER and entry_key
    "},{"location":"strategies/strategy_guides/common_regular_strategy/#remove_tags","title":"remove_tags","text":"
    • Removes the tags stored in the OrderTagManager along with the orders related stored in that tag 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 the order tags.

    "},{"location":"strategies/strategy_guides/common_regular_strategy/#remove_order","title":"remove_order","text":"
    • Remove the order(s) from the OrderTagManager for the given tag(s). 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_regular_strategy/#get_internals","title":"get_internals","text":"
    • Returns the values i.e. both the entry and exit orders stored inside the tags list.
    "},{"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":"
    • In this method we process each instrument in the instruments bucket, if there is some entry condition to be checked then we create an get_entry_decision method that calculates the entry condition like a crossover or compares the latest value of the OHLC data or indicator data.

    • When the order has to be placed we add the instrument to selected_instruments_bucket and additional data related to the instrument that will be required while placing to the sideband_info. This information is passed to the strategy_enter_position method

    "},{"location":"strategies/strategy_guides/common_regular_strategy/#strategy_enter_position","title":"strategy_enter_position","text":"
    • Here is where we actually place the entry order for which we calculate the quantity for the order to be placed. If the order is placed successfully we save the order in a class variable such that we can access the order object via the variable in the exit methods.
    "},{"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":"
    • This method is called before the entry methods because in the case of delivery strategy we want to resume and exit previous day orders before we can place new entry orders.
    • Here we place stoploss exit orders, target exit orders, and check for exit conditions for the open entry orders.
    "},{"location":"strategies/strategy_guides/common_regular_strategy/#strategy_exit_position","title":"strategy_exit_position","text":"
    • Here is where we actually place the exit order for where we exit the order which was placed during entry. If the order is placed successfully we clear the order in a class variable such that we can add new orders to the vacant place in variable in the entry methods.
    "},{"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":"
    • Aroon Crossover
    • Bollinger Bands
    • EMA Crossover
    • Inverse EMA Scalping
    • Reverse RSI
    • Stochastic Crossover
    • VWAP Crossover

    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:

    • Historical data is a time series data of open, high, low and close values of an instrument. These values are fetched at an interval same as that of the candle interval. The method given below fetches multiple historical data values till the current candle on which the strategy is executing. Historical data of the instrument up to a certain point in your strategy is collected using:
      hist_data = self.get_historical_data(instrument)\n
      Here the variable hist_data is a pandas.Dataframe object. A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional array, or a table with rows and columns. The hist_data Dataframe will have 4 columns named as : \u201copen\u201d, \u201chigh\u201d, \u201cclose\u201c and \u201clow\u201d. For every row there will be a unique timestamp and the difference between each timestamp is of candle interval.
    • To access all the values of one particular column from the hist_data, you can use the following syntax code. Remember the data type of the column fetched here is pandas.Series
      hist_data[\u2018<column_name>\u2019]\n
      Example:
      close = hist_data[\u2018close\u2019]\n
    • To access the O-H-L-C values of the current latest candle you can use the following code. This also tells us that the index -1 is for latest, -2 will be for second latest and so on. This also implies that index 0 will get the oldest data, index 1 will give second oldest data and so on.
      latest_ohlc = hist_data.iloc[-1]\n
    • Next, you analyse this historical data to determine trading signals and calculate indicator values. You can rely on functions from \"talib\" for this, as shown below:

      ema_x = talib.EMA(hist_data['close'], timeperiod=self.timeperiod1)\nema_y = talib.EMA(hist_data['close'], timeperiod=self.timeperiod2)\n
      As you can see, we have passed the \u201cclose\u201d column and a strategy parameter value called \u201cself.timeperiod1\u201d and \u201cself.timeperiod2\u201d to the talib function. Each of the talib functions require unique input values, some require pandas.Series, some require constants like integers and floats and some require both. To understand the working of each talib function, refer here.

    • In many strategies, the condition to buy or sell can be triggered based on the crossover direction of 2 signals/indicators. A crossover refers to an instance where an indicator and a price, or multiple indicators, overlap and cross one another. Crossovers are used in technical analysis to confirm patterns and trends such as reversals and breakouts, generating buy or sell signals accordingly. Below we have given an example of how to calculate the crossover of the 2 indicator values we had calculated above.

      crossover_value = self.utils.crossover(ema_x, ema_y)\n
      Here if crossover_value is 0 then the indicators ema_x and ema_y have not crossed. If it is 1 then indicator ema_x has crossed ema_y in upward direction. Similarly if it is -1 then indicator ema_x has crossed ema_y in downward direction

    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:

    • base_instrument: The foundation of your options strategy, often represented by an index.
    • tradingsymbol_suffix: Specifies whether the option should be a call option (CE) or a put option (PE), determining the trading symbol's suffix.
    • strike_direction: Defines the direction relative to the current strike price, with options like \"In The Money\" (ITM), \"Out of The Money\" (OTM), and \"At the Money\" (ATM).
    • no_of_strikes: Specifies how many strikes away from the current strike price the function should consider, setting the distance in strike prices within the chosen strike direction.

    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.

    • If number_of_allowed_expiry_dates is set to 1, the function returns the monthly expiry date.
    • If number_of_allowed_expiry_dates is set to 0, the function returns a weekly expiry date.

    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:

    • base_instrument: The foundation of your options strategy.
    • expiry_date: The expiry date of the child instrument, calculated using the \"get_allowed_expiry_dates\" function.
    • tradingsymbol_suffix: Specifies whether the option should be a call option (CE) or a put option (PE), helping identify the appropriate options.
    • strike_direction: Determines the direction in relation to the current strike price, offering options like \"In The Money\" (ITM), \"Out of The Money\" (OTM), and \"At the Money\" (ATM).
    • no_of_strikes: Specifies how many strikes away from the current strike price the function should consider, defining the distance in strike prices within the chosen strike direction.
    "},{"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:

    • base_instrument: The foundation of your options strategy, typically an index.
    • tradingsymbol_suffix: Specifies whether the child instrument should be a call option (CE) or a put option (PE), aiding in the identification of the appropriate options.
    • current_close (strike_price): The current price of the base instrument, also known as the strike price.
    • direction: Determines the direction in relation to the current strike price, helping select the child instrument (i.e., ATM, ITM, or OTM).

    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:

    • base_instrument: The foundation of your options strategy.
    • direction: Determines the direction in relation to the current strike price, helping select the child instrument (i.e., ATM, ITM, or OTM).
    • expiry_date: The expiry date of the child instrument, calculated using the \"get_allowed_expiry_dates\" function.
    • tradingsymbol_suffix: Specifies whether the child instrument should be a call option (CE) or a put option (PE), aiding in the identification of the appropriate options.
    • current_close: The current price of the base instrument, also known as the strike price.

    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:

    • candle: The current candle where the strategy is executing its algorithm.
    • instrument_bucket: A list of all the instruments provided by the user when starting the strategy. Here, you iterate through the instruments, calling \"self.get_decision()\" to determine actions for each. For options strategies, you can also use \"self.options_instruments_set_up_local()\" to set up child instruments for each base instrument. The selected instruments and their meta-information are returned by the function.

    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:

    • candle: The current candle where the strategy is executing its algorithm.
    • instrument: One of the instruments from the selected instruments list returned by \"strategy_select_instruments_for_entry.\"
    • meta: Meta-information of that particular instrument, aligning with the instrument from the meta list.

    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/#orderregular","title":"OrderRegular","text":"

    The self.broker.OrderRegular is used to place the entry/exit orders.

    "},{"location":"strategies/strategy_guides/common_strategy_guide/#parameters","title":"Parameters:","text":"
    • instrument: Instrument object on which to place the order.
    • action: Action to be taken, either 'BUY' or 'SELL'.
    • quantity: The quantity of the order, generally calculated as self.number_of_lots * instrument.lot_size.
    • order_variety: (Optional) Type of order. Default is MARKET order (BrokerOrderVarietyConstants.MARKET).
    • price: (Optional) The price at which the limit order will be placed.
    • trigger_price: (Optional) The trigger price for stop-loss orders.

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

    Market OrderLimit OrderStoploss Market OrderStoploss Limit Order
    self.broker.OrderRegular(\n    instrument,\n    action, \n    quantity \n    )\n
    self.broker.OrderRegular(\n    instrument, \n    action, \n    quantity, \n    order_variety=BrokerOrderVarietyConstants.LIMIT, \n    price=price \n    )\n
    self.broker.OrderRegular(\n    instrument, \n    action, \n    quantity, \n    order=order_variety=BrokerOrderVarietyConstants.STOPLOSS_MARKET, \n    trigger_price=trigger_price\n    )\n
    self.broker.OrderRegular(\n    instrument,  \n    action, \n    quantity,  \n    order_variety=BrokerOrderVarietyConstants.STOPLOSS_LIMIT, \n    price=price, \n    trigger_price=trigger_price\n)\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:

    • candle: The current candle where the strategy is executing its algorithm.
    • instrument_bucket: A list of all instruments provided by the user when starting the strategy.

    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:

    • candle: The current candle where the strategy is executing its algorithm.
    • instrument: One of the instruments from the selected instruments list returned by \"strategy_select_instruments_for_exit.\"
    • meta: Meta-information of that particular instrument, aligning with the instrument from the meta list.

    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 the \"EMA Crossover Strategy\". Here, we are telling the core to exit all positions:

    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
    If you want the strategy to place the exit order instead of letting the core handle it, then this is what the function should look like:
    def strategy_exit_position(self, candle, instrument, meta):\n    if meta['action'] == 'EXIT':\n        self.broker.OrderRegular(\n            instrument,\n            action,\n            quantity,\n            related_order=entry_order,\n            position=BrokerExistingOrderPositionConstants.EXIT\n            )\n        return True\n    return False\n

    Note

    • meta['action'] has to be opposite of the entry order's transaction type. For example: if the entry order is 'BUY', then meta['action'] should be 'SELL', and vice versa.
    • Pass the entry order object as the related_order parameter.
    • You can specify a lesser quantity if you want to partially exit your entry order. In case of partial exits, ensure that you return 'True' only if the quantity becomes zero after placing this order, else return 'False' for your intermediate/partial exits.
    "},{"location":"strategies/strategy_guides/fee/","title":"Frequently Encountered Errors","text":""},{"location":"strategies/strategy_guides/fee/#execution-time-exceeded-timeout_duration-duration-of-60-sec","title":"Execution time exceeded timeout_duration duration of 60 sec.","text":""},{"location":"strategies/strategy_guides/fee/#possible-causes","title":"Possible Causes","text":"
    • Historical Data Fetching Duration:

      Fetching historical data may take longer, especially if the duration is set to a large number of days.

    • Suboptimal Decision-Making Logic:

      The decision-making logic might be suboptimal, leading to increased processing time.

    • Sequential Execution Approach:

      A sequential approach of fetching historical data and then making the decisions in case of multiple instruments can contribute to delays.

    • Real-Time Calculations:

      If there are calculations that could be pre-conditioned or pre-calculated before the market opens, optimizing real-time calculations might help.

    "},{"location":"strategies/strategy_guides/fee/#solutions","title":"Solutions","text":"
    • Optimize Historical Data Fetching:

      Consider reducing the number of days for which historical data is fetched. A shorter duration, like 5 days, can be a reasonable compromise.

      @staticmethod\ndef get_historical_data_duration():\n    return 5\n
    • Optimize the Decision-Making logic:

      Revisit your strategy logic and check if any code block can be optimized.

    • Batch Processing for Decision-Making:

      In case of multiple instruments, lets say you are fetching the historical data for the instrument, and have implemented the decision-making logic for whether this instrument should get selected for order placement or not. Once this is done, you repeat the same process for the next instrument. Instead of a sequential approach, try fetching historical data for all instruments in one loop and then making decisions for all instruments in another loop.

    • Pre-Calculate Conditions:

      Identify conditions that can be pre-calculated before the market opens. Adjust the strategy start time to accommodate these pre-calculations. If certain conditions can be chcked before the market starts, set the trading start time of the strategy to a value before the market start time. Add specific checks inside the strategy to ensure that the actual order placement, etc. are executed after the market starts.

    "},{"location":"strategies/strategy_guides/fee/#no-data-in-charts","title":"No Data in Charts","text":""},{"location":"strategies/strategy_guides/fee/#description","title":"Description","text":"

    Encountering the \"NO data in charts\" error while running a strategy is a common issue. This problem arises when using a small quantity with very large funds. Limited visibility on charts due to large funds with a small quantity setting.

    "},{"location":"strategies/strategy_guides/fee/#possible-causes_1","title":"Possible Causes","text":"
    • Scale Discrepancy:

      The large fund amount may lead to extremely small values on the y-axis, which are not visible, causing charts to appear empty.

    • Default Quantity and Funds:

      Default quantity and funds settings, if not adjusted, may lead to similar issues with empty charts.

    "},{"location":"strategies/strategy_guides/fee/#solutions_1","title":"Solutions","text":"
    • Normalize Values:

      Normalize values by using larger quantities or scaling to ensure meaningful data display across various scenarios.

    • Adjust Default Settings:

      Consider adjusting default values to something more suitable for common scenarios. Charts displaying proper data with suitable funds and quantity settings

    "},{"location":"strategies/strategy_guides/fee/#openai-api-quota-depletion","title":"OpenAI API Quota Depletion","text":""},{"location":"strategies/strategy_guides/fee/#description_1","title":"Description","text":"

    The \"OpenAI API current quota exceeded\" error indicates that the current quota or available credits for the OpenAI API has been exhausted. This typically occurs when the allotted usage limit for the API key has been reached.

    "},{"location":"strategies/strategy_guides/fee/#possible-causes_2","title":"Possible Causes","text":"
    • Credit Depletion:

      The API key has utilized its entire quota or available credits.

    "},{"location":"strategies/strategy_guides/fee/#solutions_2","title":"Solutions","text":"
    • Purchase More Credits:

      To continue using the OpenAI API, consider purchasing additional credits or upgrading your plan to increase the quota. Click here to add more credits.

    • Alternative Key:

      If available, switch to a different API key that still has unused credits.

    "},{"location":"strategies/strategy_guides/how_to/","title":"How to","text":""},{"location":"strategies/strategy_guides/how_to/#fetch-last-traded-price-ltp-of-an-instrument","title":"Fetch Last Traded Price (LTP) of an Instrument","text":"

    To fetch the Last Traded Price (LTP) of any instrument, use the following method:

    self.broker.get_ltp(instrument)\n

    This method retrieves the last traded price of the specified instrument.

    "},{"location":"strategies/strategy_guides/how_to/#access-attributes-of-an-instrument-object","title":"Access Attributes of an Instrument Object","text":"

    An instrument object typically contains various attributes providing information about the instrument:

    • exchange: Exchange on which the instrument is listed.
    • expiry: Expiration date of the instrument (applicable for derivatives).
    • lot_size: Number of units in a single lot of the instrument.
    • strike_price: Strike price of the instrument (applicable for options).
    • segment: Trading segment of the instrument.
    • tradingsymbol: Unique trading symbol of the instrument.
    • tick_size: Minimum price movement (tick) of the instrument.

    To access these attributes, use the following notation:

    instrument.exchange\ninstrument.expiry\ninstrument.lot_size\ninstrument.strike_price\ninstrument.segment\ninstrument.tradingsymbol\ninstrument.tick_size\n
    "},{"location":"strategies/strategy_guides/how_to/#fetch-different-types-of-instruments","title":"Fetch Different Types of Instruments","text":"

    To fetch different types of instruments, use the get_instruments_filtered method:

    Method Signature:

    self.broker.get_instruments_filtered(segment, tradingsymbol_exact=None, tradingsymbol_prefix=None, tradingsymbol_suffix=None, expiry=None)\n
    Example:
    from datetime import date\ninstruments = self.broker.get_instruments_filtered(segment='NSE_FO', tradingsymbol_prefix='NIFTY', expiry=date(2024,01,04))\n

    This example fetches equity instruments with a trading symbol prefix of 'NIFTY' and an expiry date of 4th January, 2024.

    "},{"location":"strategies/strategy_guides/how_to/#access-attributes-of-an-order-object","title":"Access Attributes of an Order Object","text":"

    An order object typically contains various attributes providing information about the order:

    • entry_price: Entry price of the order.
    • id: AlgoBulls specific alphanumeric order ID.
    • instrument: Instrument for which the order is placed.
    • order_code: Code for the order type (INTRADAY/DELIVERY).
    • order_time: Time at which the order is placed.
    • order_transaction_type: Type of transaction (BUY/SELL).
    • order_type: Type of order (REGULAR/BRACKET/COVER).
    • order_variety: Variety of the order (MARKET, LIMIT, STOPLOSS_MARKET, STOPLOSS_LIMIT).
    • position: Position (ENTER/EXIT).
    • price: Price of the order.
    • quantity: Order quantity.
    • quantity_pending: Quantity that is currently pending.
    • trigger_price: Trigger price of the order.

    To access these attributes, use the following notation:

    order.entry_price\norder.id\norder.instrument\norder.order_code\norder.order_time\norder.order_transaction_type\norder.order_type\norder.order_variety\norder.position\norder.price\norder.quantity\norder.quantity_pending\norder.trigger_price\n

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

    Coding Prerequisites

    • For pyalgotrading check here.
    • For Python Build Web check here.
    "},{"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

    • Strategy Structure (regular)
    • Strategy Structure (options)
    "},{"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":"Support pyalgo","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":"Python Build Support","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":"
    • Log in to your AlgoBulls account and choose Python Build from the left-side menu.
    • From the Python Build Splash Screen, choose the My Coded Strategies section display card. This is the section that holds all your saved strategies, whether you have coded them from scratch or modified them from ready templates.
    • Click and open the strategy that you think requires our assistance.

    "},{"location":"support/support_pybuild/#need-support","title":"Need Support","text":"
    • In the chosen strategy, click on the Need Support button on the top right corner of the page.

    • From the pop-up window that appears, click on the Select Strategy dropdown and choose the name of your strategy.

    • Write your query in the Explain your query briefly dialog box. This will help our team to get the best solution for you.

    • Click the Submit button. Our team will reach out to you with the solution within 1-2 business days.

    "}]} \ 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:

    • Analyze Structure: Study code structure, including strategy definition, condition setting, and action execution.
    • Modify and Experiment: Once comfortable with examples, customise them to your preferences. Adjust parameters, conditions, and actions to observe their impact on trading outcomes.

    • Learn Strategies: Each example represents a different trading approach, like trend-following or mean-reversion. Studying these examples introduces you to various trading strategies and their underlying principles.

    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:

    • Code Examples: Real code snippets showcasing how to implement specific strategies, functions, and techniques using Python Build.
    • Python Cookbook for Algorithmic Trading: A Python Cookbook for Algorithmic Trading, explaining in-depth about strategy creation and execution from scratch using Python. Explore the technical content of the book on GitHub.
    "},{"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":"
    • The Cumulative Returns chart illustrates how our strategy's returns value has evolved over time in percentage.
    • Positive values indicate gains, while negatives reflect losses. Bigger positive returns are more favourable.
    • Keep in mind, this chart focuses on gains and losses, excluding risk and timing considerations.
    • There are 2 sub categories of cumulative returns chart depending on the scale we are using. One is normal scaled and other is log scaled
    "},{"location":"analytics/pyalgotrading_analytics/#end-of-year-returns-eoy","title":"End of Year Returns (EoY)","text":"
    • The End of Year Returns chart showcases our strategy's annual performance as a percentage.
    • It quantifies its overall performance, considering gains or losses throughout each year.
    "},{"location":"analytics/pyalgotrading_analytics/#distributions-of-monthly-returns-histogram","title":"Distributions of Monthly Returns (Histogram)","text":"
    • In the Monthly Returns Distribution Histogram, we see the frequency distribution of different levels of returns over consecutive months.
    • This histogram helps us understand the range and patterns in monthly returns, shedding light on our strategy's volatility and performance trends.
    "},{"location":"analytics/pyalgotrading_analytics/#daily-returns","title":"Daily Returns","text":"
    • The Daily Returns Chart portrays the percentage change in our strategy's returns between trading days.
    • It provides insights into short-term volatility, trend analysis, and risk assessment.
    "},{"location":"analytics/pyalgotrading_analytics/#rolling-volatility-6-months","title":"Rolling Volatility (6 months)","text":"
    • A Rolling Volatility (6 months) Plot showcases the changing volatility of an investment over time using a rolling window of six months.
    • This plot reveals how the investment's price fluctuations vary as the window moves across the dataset.
    • It provides insights into short-term volatility patterns, helping investors understand how the investment's risk level evolves in response to different market conditions.
    "},{"location":"analytics/pyalgotrading_analytics/#rolling-sharpe-6-months","title":"Rolling Sharpe (6 months)","text":"
    • A Rolling Sharpe (6 months) Plot illustrates the dynamic changes in the Sharpe ratio over time using a rolling window of six months.
    • The plot shows how the risk-adjusted performance of an investment fluctuates as the window moves through the dataset.
    • This visualization helps investors understand how the Sharpe ratio varies with changing market conditions and provides insights into the investment's consistency and risk-return trade-offs over short-term periods.
    "},{"location":"analytics/pyalgotrading_analytics/#rolling-sortino-6-months","title":"Rolling Sortino (6 months)","text":"
    • A Rolling Sortino (6 months) Plot visualizes the variation in the Sortino ratio over time using a rolling window of six months.
    • This plot demonstrates how the investment's risk-adjusted performance, considering only downside volatility, changes as the window progresses through the data.
    • It offers insights into how the Sortino ratio evolves with market conditions, helping investors assess the investment's ability to generate favorable risk-adjusted returns over short-term intervals.
    "},{"location":"analytics/pyalgotrading_analytics/#worst-5-drawdown-periods","title":"Worst 5 Drawdown Periods","text":"
    • A Worst 5 Drawdown Periods plot displays the top five periods during which the strategy experienced the largest declines from peak to trough.
    • This visualization helps strategists understand the most significant loss-making episodes in the strategy's run.
    • It shows the magnitude and duration of these drawdowns, providing insights into the strategy's risk and potential vulnerabilities.
    "},{"location":"analytics/pyalgotrading_analytics/#underwater-plot","title":"Underwater Plot","text":"
    • The Underwater Plot visually narrates our strategy's performance concerning its past peaks.
    • It showcases how much our returns value has dropped from its highest point over time.
    • This aids in visualising periods of drawdown and recovery, offering insights into historical risk and resilience.
    "},{"location":"analytics/pyalgotrading_analytics/#monthly-returns-heatmap","title":"Monthly Returns (Heatmap)","text":"
    • The Monthly Returns Heatmap offers a colour-coded view of our strategy's performance across months.
    • Shades of green indicate positive returns, while shades of red signify losses.
    • This visual tool helps spot trends and patterns, aiding in identifying strong and weak performance periods.
    "},{"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":"
    • You can run your strategies on American exchanges like NASDAQ or NYSE.
    • It helps you access the historical data as well as live data of all the stocks from Alpaca.
    • It will also help you backtest, paper trade and live trade on AlgoBulls.
    "},{"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.

    • OAuth Method: Follow the simple steps mentioned here to connect using OAuth.
    • Non-OAuth Method: For the Non-OAuth method, you can follow the steps mentioned here.

    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":"
    • Navigate to the Broking Detailspage on the AlgoBulls platform.
    • Here you will see all the brokers you have connected and their current statuses.
    "},{"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":"
    • Click on Add Broker.
    "},{"location":"brokers/connecting_alpaca/#search-for-alpaca","title":"Search for Alpaca","text":"
    • On the pop-up window that appears, you have a search bar for finding your desired broker.

    • Type Alpaca in the search dialog box

    • Click on Alpaca Paper (OAuth) for choosing your Alpaca Paper Account.
    • Click on Alpaca Live (OAuth) for choosing your Alpaca Live Account.

    "},{"location":"brokers/connecting_alpaca/#provide-permission","title":"Provide Permission","text":"
    • After clicking on Alpaca Paper (OAuth) or Alpaca Live (OAuth), you will be redirected to the Alpaca website for permission.
    • You will be asked to login if you are not already logged in.
    • On the dialog box that appears, click Allow. This will bind your Alpaca account with the AlgoBulls account.
    • On successful authorisation, you will be redirected to the AlgoBulls platform and you will be able to see your broker on the Broking Detailspage.

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

    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":"
    • Go the the official Alpaca website
    • Click on sign up for free.
    • Follow the steps there and add your details to create the account.
    "},{"location":"brokers/non_auth_alpaca/#api-keys","title":"API keys","text":"
    • After creating your account, login to access the homepage.
    • Click on View API Keys on the right side under the Quick Trade block.
    • Click on regenerate to create API and Secret Key.
    • On regenerating, you will get fresh API keys under the Key section and a secret key under the Secret section.
    "},{"location":"brokers/non_auth_alpaca/#add-broker","title":"Add Broker","text":"
    • Click on Add Broker.
    "},{"location":"brokers/non_auth_alpaca/#search-for-alpaca-non-oauth","title":"Search for Alpaca Non-OAuth","text":"
    • On the pop-up window that appears, you have a search bar for finding your desired broker..
    • Type Alpacain the search box and choose Alpaca Non-OAuth from the search results.
    "},{"location":"brokers/non_auth_alpaca/#provide-api-and-secret-key","title":"Provide API And Secret key","text":"
    • After clicking Alpaca Non-OAuth, you will see a dialog box requesting your API and Secret key.
    • Enter your keys there and click Confirm to bind Alpaca with your AlgoBulls account.
    • On successful authorisation, you will be redirected to the AlgoBulls platform and you will be able to see your broker on the Broking Details page.
    "},{"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":"
    • Parameter Name: broker_commission_percentage
    • Type: float
    • Default Value: None
    • Definition: Brokerage is the fee charged by your broker for executing a trade. It's usually a percentage of the trade value. The broker_commission_percentage parameter lets you specify the brokerage fee as a percentage.
    • Explanation: Brokers charge a fee for executing your trades, and this fee is often a percentage of your trade amount. You can adjust this parameter to match the fees your broker charges.

    • Parameter Name: broker_commission_price

    • Type: float
    • Default Value: None
    • Definition: The broker_commission_price parameter allows you to specify a fixed broker fee per trade. This fee is added on top of the percentage-based brokerage. It accounts for any flat fees associated with your trades.
    • Explanation: In addition to the percentage-based fees, some brokers charge a fixed fee for every trade. Use this parameter to include those fixed fees in your backtesting calculations.
    "},{"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.

    • Note: When both broker_commission_percentage and broker_commission_price are provided, the function will automatically calculate the brokerage cost using both parameters and select the option that results in the lower brokerage cost. This ensures that you pay the minimum brokerage fees for your trades.
    "},{"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":"
    • Powered by the AlgoBulls Platform
    • Everything related to Algorithmic Trading Strategies!
      • Free pool of Strategies are available at pyalgostrategypool!
      • Create & upload strategies easily on the cloud
      • Support for all 150+ Technical Indicators provided by TA-Lib
      • Support for multiple candlesticks patterns - Japanese OHLC, Renko, Heikin-Ashi, Linebreak
      • Support for multiple candle intervals - 1 minute, 3 minutes, 5 minutes, 10 minutes, 15 minutes, 30 minutes, 1 hour, 1 day.
      • Support for Regular Orders, Bracket Orders and Cover Orders
      • Support for MARKET, LIMIT, STOPLOSS-LIMIT, STOPLOSS-MARKET orders
      • Support for INTRADAY and DELIVERY orders
    • Support for Backtesting
    • Support for Paper Trading
    • Support for Live Trading / Real Trading
    • Support for multiple brokers for Live Trading. Check list of supported brokers here.
    • Real-time Logs for Backtesting, Paper Trading, Live Trading
    • Multiple real-time Reports available for Backtesting, Paper Trading and Live Trading:
      • Profit-&-Loss report (P&L report)
      • Statistics Report
      • Order History Log for each order with state transitions & timestamps
      • Detailed analytics with charts
    • Support for calculating Slippage
    • Support for calculating Brokerage
    • Support for importing external P&L table and generating analytics on the same
    • Plot Candlestick charts using plotly.py

    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":"
    • Bug Reporting / New Feature Request: Create a new issue on GitHub.
    • Engage in Discussion: Join fellow developers on the discussion forum.
    • Discussion Community: Join fellow algotrading ninjas on the discussion Slack
    • Additional Support: For further help, contact support@algobulls.com.
    "},{"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:

    • Step 1: Activate the Advanced Python Build Plan from the Pricing menu.
    • Step 2: Get the Developer Key from the Settings section.

    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

    • It is a good idea to set up a virtual environment first while installing Python 3.10.
    • Once Python is installed, most packages are easily installed in your venv using pip install command
    "},{"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:

    • PyCharm
    • VS Code
    "},{"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

    • SELL Entry positions are allowed only if the strategy is running for INTRADAY. DELIVERY strategies do not allow SELL as entry positions. This is taken care of in the elif part.
    • The strategy_select_instruments_for_entry method is called once for every candle time. For Instance, if you submit a job with the candle time as 15 minutes, then this method will be called once for every 15 minute candle.
    • The actual Entry position (BUY/SELL) is not entered here. Here, only the instrument is selected based on the crossover value with the proper action mentioned in the meta. The Entry position will be taken in the next method below.
    • The meta contains a very versatile dictionary object. You may use it to pass any other additional information that you wish.
    "},{"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:

    • price - If you want to BUY at the market price (Last Traded Price) or LTP, then just fetch the LTP using get_ltp as shown in the code above. Store the value in ltp and pass it to price.
    • stoploss_trigger, target_trigger and trailing_stoploss_trigger - You can calculate these using the ltp and the values you will pass through the job that you will submit. The parameters will be caught as self.stoploss, self.target and self.trailing_stoploss.

    Note

    • If you plan to use Bracket Order instead of Regular Orders, then create a separate Python file for it, say strategy_sma_bracket_order.py. You can also change the class name as StrategySMABracketOrder. There will be changes in the entry and exit methods also.
    • The strategy_enter_position method is called once for every instrument. For instance, you want to run this strategy for 5 instruments. Say that the strategy_select_instruments_for_entry method selects 3 instruments for ENTRY positions (BUY/SELL). Then, the strategy_enter_position method will be called thrice, once for each instrument respectively within the candle time frame (say, 15 minutes).
    "},{"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

    • The actual Exit position (BUY/SELL) is not entered here. Here, only the instrument is selected based on the crossover value with the proper action mentioned in the meta. The Exit position will be taken in the next method below.
    • The meta contains a very versatile dictionary object. You may use it to pass any other additional information that you wish.
    • Whenever a new trading day starts, the strategy_select_instruments_for_exit is called first. This is very important for DELIVERY strategies. Many instruments might be holding in an Entry Position at the end of the previous trading day, and they might be eligible for exit at the start of the new trading day.
    "},{"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

    • The order of values passed to the crossover method of the utils package is very important.
    • Example: you have 2 SMA values, 5 and 12. The strategy describes that there should be an BUY Entry Position when SMA(5) cuts SMA(12) upwards (crossover value should be 1).
    • In this case, if you mistakenly pass SMA(12) value first and SMA(5) value next to the crossover function, the answer you will get is -1 (Cut downwards).
    • Though, the crossover value is correct, the strategy is expecting to BUY at crossover 1 as per the code, which will not work now.
    • Therefore, the strategy will work correctly only if you pass SMA(5) first and then SMA(12) to the crossover function, thus making the order of parameters passed an important point to be aware of, while coding the strategy.
    "},{"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":"
    • The Cumulative Returns chart illustrates how our strategy's returns value has evolved over time in percentage.
    • Positive values indicate gains, while negatives reflect losses. Bigger positive returns are more favourable.
    • Keep in mind, this chart focuses on gains and losses, excluding risk and timing considerations.
    • There are 2 sub categories of cumulative returns chart depending on the scale we are using. One is normal scaled and other is log scaled
    "},{"location":"pyalgotrad/pyalgotrading_analytics/#end-of-year-returns-eoy","title":"End of Year Returns (EoY)","text":"
    • The End of Year Returns chart showcases our strategy's annual performance as a percentage.
    • It quantifies its overall performance, considering gains or losses throughout each year.
    "},{"location":"pyalgotrad/pyalgotrading_analytics/#distributions-of-monthly-returns-histogram","title":"Distributions of Monthly Returns (Histogram)","text":"
    • In the Monthly Returns Distribution Histogram, we see the frequency distribution of different levels of returns over consecutive months.
    • This histogram helps us understand the range and patterns in monthly returns, shedding light on our strategy's volatility and performance trends.
    "},{"location":"pyalgotrad/pyalgotrading_analytics/#daily-returns","title":"Daily Returns","text":"
    • The Daily Returns Chart portrays the percentage change in our strategy's returns between trading days.
    • It provides insights into short-term volatility, trend analysis, and risk assessment.
    "},{"location":"pyalgotrad/pyalgotrading_analytics/#rolling-volatility-6-months","title":"Rolling Volatility (6 months)","text":"
    • A Rolling Volatility (6 months) Plot showcases the changing volatility of an investment over time using a rolling window of six months.
    • This plot reveals how the investment's price fluctuations vary as the window moves across the dataset.
    • It provides insights into short-term volatility patterns, helping investors understand how the investment's risk level evolves in response to different market conditions.
    "},{"location":"pyalgotrad/pyalgotrading_analytics/#rolling-sharpe-6-months","title":"Rolling Sharpe (6 months)","text":"
    • A Rolling Sharpe (6 months) Plot illustrates the dynamic changes in the Sharpe ratio over time using a rolling window of six months.
    • The plot shows how the risk-adjusted performance of an investment fluctuates as the window moves through the dataset.
    • This visualization helps investors understand how the Sharpe ratio varies with changing market conditions and provides insights into the investment's consistency and risk-return trade-offs over short-term periods.
    "},{"location":"pyalgotrad/pyalgotrading_analytics/#rolling-sortino-6-months","title":"Rolling Sortino (6 months)","text":"
    • A Rolling Sortino (6 months) Plot visualizes the variation in the Sortino ratio over time using a rolling window of six months.
    • This plot demonstrates how the investment's risk-adjusted performance, considering only downside volatility, changes as the window progresses through the data.
    • It offers insights into how the Sortino ratio evolves with market conditions, helping investors assess the investment's ability to generate favorable risk-adjusted returns over short-term intervals.
    "},{"location":"pyalgotrad/pyalgotrading_analytics/#worst-5-drawdown-periods","title":"Worst 5 Drawdown Periods","text":"
    • A Worst 5 Drawdown Periods plot displays the top five periods during which the strategy experienced the largest declines from peak to trough.
    • This visualization helps strategists understand the most significant loss-making episodes in the strategy's run.
    • It shows the magnitude and duration of these drawdowns, providing insights into the strategy's risk and potential vulnerabilities.
    "},{"location":"pyalgotrad/pyalgotrading_analytics/#underwater-plot","title":"Underwater Plot","text":"
    • The Underwater Plot visually narrates our strategy's performance concerning its past peaks.
    • It showcases how much our returns value has dropped from its highest point over time.
    • This aids in visualising periods of drawdown and recovery, offering insights into historical risk and resilience.
    "},{"location":"pyalgotrad/pyalgotrading_analytics/#monthly-returns-heatmap","title":"Monthly Returns (Heatmap)","text":"
    • The Monthly Returns Heatmap offers a colour-coded view of our strategy's performance across months.
    • Shades of green indicate positive returns, while shades of red signify losses.
    • This visual tool helps spot trends and patterns, aiding in identifying strong and weak performance periods.
    "},{"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:

    • Your strategy is already uploaded on the AlgoBulls account and you want to search or select it

    OR

    • You have saved the strategy from the AlgoBulls Website
    "},{"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":"
    • Make sure you have an active working AlgoBulls account ready to go!
    • Open a Jupyter Notebook.
    • If you have coded the strategy yourself and not used a ready strategy from the pyalgostrategypool package, then make sure your strategy file (.py) and the Jupyter Notebook are in the same folder.
    "},{"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.

    • Import a ready strategy

      from pyalgostrategypool.strategy_ema_regular_order import StrategyEMARegularOrder\n

    • Import your own strategy

      from strategy_sma_regular_order import StrategySMARegularOrder\n

    "},{"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":"
    • Search your strategy using strategy name. Make sure you have the strategy with given name in your AlgoBulls Account.
          strategy_name = 'Exponential Moving Averages Crossover'\n    strategy_code, strategy_name = all_strategies_df.loc[all_strategies_df['strategyName'] == strategy_name].iloc[0]        \n
    • Search your strategy using strategy code. Make sure you have the strategy with given code in your AlgoBulls Account.
      strategy_code = 'afd6214c5db94dbeae7502e861fa4ffc'\nstrategycode, strategyname = all_strategies_df.loc[all_strategies_df['strategyCode'] == strategy_code].iloc[0]\n
    "},{"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":"
    • Parameter Name: slippage_percent
    • Type: float
    • Default Value: None
    • Definition: Slippage is the difference between the expected execution price of a trade and the actual execution price. It often occurs due to market volatility and the time it takes to execute an order. Slippage can have a significant impact on trading results, and this parameter allows you to simulate it.
    • Explanation: Imagine you're trading and placing an order at a specific price, but the market moves quickly. Slippage accounts for the price difference between what you expected and what you actually get. Use this parameter to make your backtesting experience more realistic.
    "},{"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:

    • Backtesting
    • Paper Trading
    • Real Trading
    "},{"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

    • Keep a unique file name
    • Make sure that the file name is in lowercase and that each word is separated with an underscore '_' as shown above.

    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

    • There are 2 variations when fetching logs:
      • Progressive Logs (print_live_logs = True): will show progress bar and update the latest logs as the strategy is executed
      • Complete Logs (print_live_logs = False): will fetch logs after strategy is executed.(It wont update the latest logs, unless called manually again)

    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

    • Order History for Real Trading is not supported by brokers.
    • Order History for Backtesting, Paper Trading and Real Trading is supported by the AlgoBulls Virtual Brokers.
    "},{"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:

    • Coding the complete strategy from the Create page.

    OR

    • Picking up a ready strategy from the pyalgostrategypool package.
    "},{"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":"
    • Make sure you have an active working AlgoBulls account ready to go!
    • Open a Jupyter Notebook.
    • If you have coded the strategy yourself and not used a ready strategy from the pyalgostrategypool package, then make sure your strategy file (.py) and the Jupyter Notebook are in the same folder.
    "},{"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
    • Import a ready strategy

      from pyalgostrategypool.strategy_ema_regular_order import StrategyEMARegularOrder\n

    • Import your own strategy

      from strategy_sma_regular_order import StrategySMARegularOrder\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

    • Code Structure of Strategy (workflow of a strategy)
    "},{"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

    • The parameter names and the number of parameters may change for different strategies.
    "},{"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":"
    • Stores the order object for the given tags. eg:
    self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
    • Here the _order is the order object stored inside the OrderTagManager for the tags base_inst_str and entry_key.
    "},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#get_orders","title":"get_orders","text":"
    • Retrieve the order(s) for the given tags.

    eg:

    self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
    • Here the order object retrieved from the OrderTagManager for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER and entry_key
    "},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#remove_tags","title":"remove_tags","text":"
    • Removes the tags stored in the OrderTagManager along with the orders related stored in that tag

    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":"
    • Remove the order(s) from the OrderTagManager for the given tag(s).

    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":"
    • In this method we process each instrument in the instruments bucket, if there is some entry condition to be checked then we create a get_entry_decision method that calculates the entry condition like a crossover or compares the latest value of the OHLC data or indicator data.

    • When the order has to be placed we add the instrument to selectd_instruments_bucket and additional data related to the instrument that will be required while placing to the sideband_info. This information is passed to the strategy_enter_position method

    "},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#strategy_enter_position","title":"strategy_enter_position","text":"
    • Here is where we actually place the entry order for which we calculate the quantity for the order to be placed. If the order is placed successfully we save the order in a class variable such that we can access the order object via the variable in the exit methods.
    "},{"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":"
    • This method is called before the entry methods because in the case of delivery strategy we want to resume and exit previous day orders before we can place new entry orders.
    • Here we place stoploss exit orders, target exit orders, and check for exit conditions for the open entry orders.
    "},{"location":"pyalgotrad/strategy_guides/common_options_strategy/#strategy_exit_position","title":"strategy_exit_position","text":"
    • Here is where we actually place the exit order for where we exit the order which was placed during entry. If the order is placed successfully we clear the order in a class variable such that we can add new orders to the vacant place in variable in the entry methods.
    "},{"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":"
    • Options Bear Call Ladder
    • Options Bear Put Ladder
    • Options Bull Call Ladder
    • Options Bull Put Ladder
    • Options Long Iron Butterfly
    • Options Straddle
    • Options Strangle

    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

    • Code Structure of Strategy (workflow of a strategy)
    "},{"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

    • The parameter names and the number of parameters may be different for different strategies.
    "},{"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":"
    • Stores the order object for the given tags. eg:
      self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
    • Here the _order is the order object stored inside the OrderTagManager for the tags base_inst_str and entry_key.
    "},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#get_orders","title":"get_orders","text":"
    • Retrieve the order(s) for the given tags. eg:
      self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
    • Here the order object retrieved from the OrderTagManager for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER and entry_key
    "},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#remove_tags","title":"remove_tags","text":"
    • Removes the tags stored in the OrderTagManager along with the orders related stored in that tag 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 the order tags.

    "},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#remove_order","title":"remove_order","text":"
    • Remove the order(s) from the OrderTagManager for the given tag(s). 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_regular_strategy/#get_internals","title":"get_internals","text":"
    • Returns the values i.e. both the entry and exit orders stored inside the tags list.
    "},{"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":"
    • In this method we process each instrument in the instruments bucket, if there is some entry condition to be checked then we create an get_entry_decision method that calculates the entry condition like a crossover or compares the latest value of the OHLC data or indicator data.

    • When the order has to be placed we add the instrument to selected_instruments_bucket and additional data related to the instrument that will be required while placing to the sideband_info. This information is passed to the strategy_enter_position method

    "},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#strategy_enter_position","title":"strategy_enter_position","text":"
    • Here is where we actually place the entry order for which we calculate the quantity for the order to be placed. If the order is placed successfully we save the order in a class variable such that we can access the order object via the variable in the exit methods.
    "},{"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":"
    • This method is called before the entry methods because in the case of delivery strategy we want to resume and exit previous day orders before we can place new entry orders.
    • Here we place stoploss exit orders, target exit orders, and check for exit conditions for the open entry orders.
    "},{"location":"pyalgotrad/strategy_guides/common_regular_strategy/#strategy_exit_position","title":"strategy_exit_position","text":"
    • Here is where we actually place the exit order for where we exit the order which was placed during entry. If the order is placed successfully we clear the order in a class variable such that we can add new orders to the vacant place in variable in the entry methods.
    "},{"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":"
    • Aroon Crossover
    • Bollinger Bands
    • EMA Crossover
    • Inverse EMA Scalping
    • Reverse RSI
    • Stochastic Crossover
    • VWAP Crossover

    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

    • For pyalgotrading check here.
    • For Python Build Web check here.
    "},{"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

    • Strategy Structure (regular)
    • Strategy Structure (options)
    "},{"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":"
    • The Cumulative Returns chart illustrates how our strategy's returns value has evolved over time in percentage.
    • Positive values indicate gains, while negatives reflect losses. Bigger positive returns are more favourable.
    • Keep in mind, this chart focuses on gains and losses, excluding risk and timing considerations.
    • There are 2 sub categories of cumulative returns chart depending on the scale we are using. One is normal scaled and other is log scaled
    "},{"location":"python_build/pyalgotrading_analytics/#end-of-year-returns-eoy","title":"End of Year Returns (EoY)","text":"
    • The End of Year Returns chart showcases our strategy's annual performance as a percentage.
    • It quantifies its overall performance, considering gains or losses throughout each year.
    "},{"location":"python_build/pyalgotrading_analytics/#distributions-of-monthly-returns-histogram","title":"Distributions of Monthly Returns (Histogram)","text":"
    • In the Monthly Returns Distribution Histogram, we see the frequency distribution of different levels of returns over consecutive months.
    • This histogram helps us understand the range and patterns in monthly returns, shedding light on our strategy's volatility and performance trends.
    "},{"location":"python_build/pyalgotrading_analytics/#daily-returns","title":"Daily Returns","text":"
    • The Daily Returns Chart portrays the percentage change in our strategy's returns between trading days.
    • It provides insights into short-term volatility, trend analysis, and risk assessment.
    "},{"location":"python_build/pyalgotrading_analytics/#rolling-volatility-6-months","title":"Rolling Volatility (6 months)","text":"
    • A Rolling Volatility (6 months) Plot showcases the changing volatility of an investment over time using a rolling window of six months.
    • This plot reveals how the investment's price fluctuations vary as the window moves across the dataset.
    • It provides insights into short-term volatility patterns, helping investors understand how the investment's risk level evolves in response to different market conditions.
    "},{"location":"python_build/pyalgotrading_analytics/#rolling-sharpe-6-months","title":"Rolling Sharpe (6 months)","text":"
    • A Rolling Sharpe (6 months) Plot illustrates the dynamic changes in the Sharpe ratio over time using a rolling window of six months.
    • The plot shows how the risk-adjusted performance of an investment fluctuates as the window moves through the dataset.
    • This visualization helps investors understand how the Sharpe ratio varies with changing market conditions and provides insights into the investment's consistency and risk-return trade-offs over short-term periods.
    "},{"location":"python_build/pyalgotrading_analytics/#rolling-sortino-6-months","title":"Rolling Sortino (6 months)","text":"
    • A Rolling Sortino (6 months) Plot visualizes the variation in the Sortino ratio over time using a rolling window of six months.
    • This plot demonstrates how the investment's risk-adjusted performance, considering only downside volatility, changes as the window progresses through the data.
    • It offers insights into how the Sortino ratio evolves with market conditions, helping investors assess the investment's ability to generate favorable risk-adjusted returns over short-term intervals.
    "},{"location":"python_build/pyalgotrading_analytics/#worst-5-drawdown-periods","title":"Worst 5 Drawdown Periods","text":"
    • A Worst 5 Drawdown Periods plot displays the top five periods during which the strategy experienced the largest declines from peak to trough.
    • This visualization helps strategists understand the most significant loss-making episodes in the strategy's run.
    • It shows the magnitude and duration of these drawdowns, providing insights into the strategy's risk and potential vulnerabilities.
    "},{"location":"python_build/pyalgotrading_analytics/#underwater-plot","title":"Underwater Plot","text":"
    • The Underwater Plot visually narrates our strategy's performance concerning its past peaks.
    • It showcases how much our returns value has dropped from its highest point over time.
    • This aids in visualising periods of drawdown and recovery, offering insights into historical risk and resilience.
    "},{"location":"python_build/pyalgotrading_analytics/#monthly-returns-heatmap","title":"Monthly Returns (Heatmap)","text":"
    • The Monthly Returns Heatmap offers a colour-coded view of our strategy's performance across months.
    • Shades of green indicate positive returns, while shades of red signify losses.
    • This visual tool helps spot trends and patterns, aiding in identifying strong and weak performance periods.
    "},{"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":"
    • Here you can select the allowed exchanges from the drop box given on the left (eg: NASDAQ, NYSE, NSE etc.)
    • Once you have selected the exchange you can search the instrument in the search-box right beside it
    "},{"location":"python_build/python-build-config-parameters/#strategy-settings","title":"Strategy Settings","text":"
    • Here you can select the candle size, it is the size of candle on which you are running your strategy is going to be executed
    • You can even select the mode i.e. INTRADAY or DELIVERY
    "},{"location":"python_build/python-build-config-parameters/#order-settings","title":"Order Settings","text":"
    • You can adjust your orders, on how they will act when the strategy is 'Resumed' or strategy is 'Exited'
    • Resume Positions from Start: If you have previous trades in your strategy, you can resume your strategy without deleting or overwriting them. Only applicable for DELIVERY mode.
    • Exit Intraday Orders on Stop: If checked, strategy will square-off positions automatically at the end of each trading day.
    • Max Order Count: Maximum number of orders your strategy will execute per day. Once this limit is completed for the day, all BUY/SELL signals for new orders would be automatically ignored.
    • Crossover Accuracy Decimal: When running a crossover strategy, the number of decimals of the underlying indicators to be taken do decide an upward cut, downward cut or no cut.
    • Credit Exposure Factor: Applicable only for Live Trading. Use this to set the exposure limit given by your broker. System will take available funds as 'current fund balance X credit exposure factor' for executing the strategy
    "},{"location":"python_build/python-build-config-parameters/#user-parameters","title":"User Parameters","text":"
    • Use this option to pass various values of the strategy parameters from outside, without changing the code base for every execution. They are accessible as a dictionary called strategy_parameters inside your strategy class' constructor method.
    • You can customize/create your own parameters for the strategy. Click on +Add New Parameter to begin adding them. They should match with the parameters you have defined in your Python class.

    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.

    • Advanced Python Build Plan: Develop your own Algorithmic Trading Strategy for Free along with Analytics support, concurrent Strategy Executions, Professional Support, and more.

    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

    • Code Structure of Strategy (workflow of a strategy)
    "},{"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

    • The parameter names and the number of parameters may change for different strategies.
    "},{"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":"
    • Stores the order object for the given tags. eg:
    self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
    • Here the _order is the order object stored inside the OrderTagManager for the tags base_inst_str and entry_key.
    "},{"location":"python_build/strategy_guides/common_options_strategy/#get_orders","title":"get_orders","text":"
    • Retrieve the order(s) for the given tags.

    eg:

    self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
    • Here the order object retrieved from the OrderTagManager for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER and entry_key
    "},{"location":"python_build/strategy_guides/common_options_strategy/#remove_tags","title":"remove_tags","text":"
    • Removes the tags stored in the OrderTagManager along with the orders related stored in that tag

    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":"
    • Remove the order(s) from the OrderTagManager for the given tag(s).

    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":"
    • In this method we process each instrument in the instruments bucket, if there is some entry condition to be checked then we create a get_entry_decision method that calculates the entry condition like a crossover or compares the latest value of the OHLC data or indicator data.

    • When the order has to be placed we add the instrument to selectd_instruments_bucket and additional data related to the instrument that will be required while placing to the sideband_info. This information is passed to the strategy_enter_position method

    "},{"location":"python_build/strategy_guides/common_options_strategy/#strategy_enter_position","title":"strategy_enter_position","text":"
    • Here is where we actually place the entry order for which we calculate the quantity for the order to be placed. If the order is placed successfully we save the order in a class variable such that we can access the order object via the variable in the exit methods.
    "},{"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":"
    • This method is called before the entry methods because in the case of delivery strategy we want to resume and exit previous day orders before we can place new entry orders.
    • Here we place stoploss exit orders, target exit orders, and check for exit conditions for the open entry orders.
    "},{"location":"python_build/strategy_guides/common_options_strategy/#strategy_exit_position","title":"strategy_exit_position","text":"
    • Here is where we actually place the exit order for where we exit the order which was placed during entry. If the order is placed successfully we clear the order in a class variable such that we can add new orders to the vacant place in variable in the entry methods.
    "},{"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":"
    • Options Bear Call Ladder
    • Options Bear Put Ladder
    • Options Bull Call Ladder
    • Options Bull Put Ladder
    • Options Long Iron Butterfly
    • Options Straddle
    • Options Strangle

    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

    • Code Structure of Strategy (workflow of a strategy)
    "},{"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

    • The parameter names and the number of parameters may be different for different strategies.
    "},{"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":"
    • Stores the order object for the given tags. eg:
      self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
    • Here the _order is the order object stored inside the OrderTagManager for the tags base_inst_str and entry_key.
    "},{"location":"python_build/strategy_guides/common_regular_strategy/#get_orders","title":"get_orders","text":"
    • Retrieve the order(s) for the given tags. eg:
      self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
    • Here the order object retrieved from the OrderTagManager for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER and entry_key
    "},{"location":"python_build/strategy_guides/common_regular_strategy/#remove_tags","title":"remove_tags","text":"
    • Removes the tags stored in the OrderTagManager along with the orders related stored in that tag 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 the order tags.

    "},{"location":"python_build/strategy_guides/common_regular_strategy/#remove_order","title":"remove_order","text":"
    • Remove the order(s) from the OrderTagManager for the given tag(s). 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_regular_strategy/#get_internals","title":"get_internals","text":"
    • Returns the values i.e. both the entry and exit orders stored inside the tags list.
    "},{"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":"
    • In this method we process each instrument in the instruments bucket, if there is some entry condition to be checked then we create an get_entry_decision method that calculates the entry condition like a crossover or compares the latest value of the OHLC data or indicator data.

    • When the order has to be placed we add the instrument to selected_instruments_bucket and additional data related to the instrument that will be required while placing to the sideband_info. This information is passed to the strategy_enter_position method

    "},{"location":"python_build/strategy_guides/common_regular_strategy/#strategy_enter_position","title":"strategy_enter_position","text":"
    • Here is where we actually place the entry order for which we calculate the quantity for the order to be placed. If the order is placed successfully we save the order in a class variable such that we can access the order object via the variable in the exit methods.
    "},{"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":"
    • This method is called before the entry methods because in the case of delivery strategy we want to resume and exit previous day orders before we can place new entry orders.
    • Here we place stoploss exit orders, target exit orders, and check for exit conditions for the open entry orders.
    "},{"location":"python_build/strategy_guides/common_regular_strategy/#strategy_exit_position","title":"strategy_exit_position","text":"
    • Here is where we actually place the exit order for where we exit the order which was placed during entry. If the order is placed successfully we clear the order in a class variable such that we can add new orders to the vacant place in variable in the entry methods.
    "},{"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":"
    • Aroon Crossover
    • Bollinger Bands
    • EMA Crossover
    • Inverse EMA Scalping
    • Reverse RSI
    • Stochastic Crossover
    • VWAP Crossover

    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

    • For pyalgotrading check here.
    • For Python Build Web check here.
    "},{"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

    • Strategy Structure (regular)
    • Strategy Structure (options)
    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebooks for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.

    Jupyter Notebook for US Exchange (NASDAQ)

    • Click here to view a working notebook for NASDAQ exchange in cloud. No installation required.
    • Click here to execute a working notebook for NASDAQ exchange in cloud. No installation required.
    "},{"location":"strategies/aroon_crossover/#aroon-indicator","title":"Aroon Indicator","text":"
    • In the stock market, Aroon refers to the Aroon indicator, which is a technical analysis tool used to measure the strength and direction of a trend. It consists of two lines, the Aroon-Up line and the Aroon-Down line.

    • The Aroon-Up line measures the number of periods since the highest price within a given period, while the Aroon-Down line measures the number of periods since the lowest price within a given period. The Aroon indicator ranges from 0 to 100, with values closer to 100 indicating a strong trend and values closer to 0 indicating a weak or non-existent trend.

    • Traders and investors use the Aroon indicator to identify potential trend reversals, assess the strength of a trend, and generate buy or sell signals. For example, when the Aroon-Up line crosses above the Aroon-Down line, it may suggest a bullish trend, while a cross below may indicate a bearish trend.

    • It is important to note that the Aroon indicator is just one of many tools used in technical analysis, and its effectiveness can vary depending on market conditions and other factors. It is often used in conjunction with other indicators and analysis techniques to make informed trading decisions.

    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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebooks for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.

    Jupyter Notebook for US Exchange (NASDAQ)

    • Click here to view a working notebook for NASDAQ exchange in cloud. No installation required.
    • Click here to execute a working notebook for NASDAQ exchange in cloud. No installation required.
    "},{"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:

    • The middle band is a moving average, while the upper and lower bands are calculated by adding/subtracting standard deviations from the middle band.
    • Bollinger Bands help assess price volatility and identify potential overbought or oversold market conditions.
    • A narrowing of the bands (Bollinger Squeeze) suggests low volatility, often followed by increased volatility and potential price breakout.
    • Touching or exceeding the upper band may indicate an overbought market, while touching or falling below the lower band may suggest an oversold market.
    • Price reversals can be observed when the price moves from one band to the other.
    • The upper and lower bands can act as dynamic support and resistance levels.
    • Bollinger Bands are used in combination with other indicators and analysis techniques to make trading decisions. They are not a standalone strategy but provide valuable insights when combined with other tools like the RSI.
    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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebooks for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.

    Jupyter Notebook for US Exchange (NASDAQ)

    • Click here to view a working notebook for NASDAQ exchange in cloud. No installation required.
    • Click here to execute a working notebook for NASDAQ exchange in cloud. No installation required.
    "},{"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:

    • An Exponential Moving Average is a type of moving average that assigns more weight to recent prices, making it more responsive to current market conditions.
    • Unlike the SMA, which gives equal weight to all data points, the EMA assigns exponentially decreasing weights to older data points.
    • The formula for calculating an EMA involves using a smoothing factor or multiplier that determines the weight given to the previous EMA value and the current price.
    • The most common period used for EMAs is 12 and 26 days, representing short-term and long-term trends, respectively.
    • EMAs are commonly used to identify trend direction, support and resistance levels, and potential entry or exit points.
    • When the price crosses above the EMA, it may signal a bullish trend, while a cross below the EMA may suggest a bearish trend.
    • The EMA is more responsive to price changes compared to the SMA, making it useful for short-term trading strategies.
    • EMAs are often used in conjunction with other technical indicators, such as the Moving Average Convergence Divergence (MACD), to generate trading signals.
    • Traders and investors use Exponential Moving Averages to smooth out price fluctuations, identify trend reversals, and determine potential support and resistance levels. They provide a visual representation of the average price over a specific period, with greater weight given to recent prices.
    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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebooks for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.

    Jupyter Notebooks for US Exchange (NASDAQ)

    • Click here to view a working notebook for NASDAQ exchange in cloud. No installation required.
    • Click here to execute a working notebook for NASDAQ exchange in cloud. No installation required.
    "},{"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:

    • Inverse EMA is calculated by applying the EMA formula in reverse, giving greater weight to older data points and less weight to recent prices.
    • Instead of smoothing out price fluctuations like the EMA, the Inverse EMA amplifies them, making it more responsive to historical data.
    • The formula for calculating Inverse EMA is similar to the EMA, but it uses a different smoothing factor or multiplier that assigns higher weight to older data points.
    • The Inverse EMA is primarily used to identify historical patterns and potential turning points in the market.
    • When the price crosses above the Inverse EMA, it may suggest a potential reversal from a downtrend to an uptrend, and vice versa when the price crosses below the Inverse EMA.
    • Inverse EMA is not as widely used as the EMA or other moving averages, and its applications may vary among traders and analysts.
    • Inverse EMA is a less commonly used variation of the Exponential Moving Average. While the EMA is designed to provide a smoothed average of recent prices, the Inverse EMA emphasizes historical data, potentially highlighting significant turning points in the market. Traders and analysts who utilize the Inverse EMA may incorporate it into their technical analysis toolkit to complement other indicators and gain insights into price reversals and historical patterns.
    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.
    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.
    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Options from Indian Exchange (NSE)

    • Click here to view a working notebook for options from NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for options from NSE exchange in cloud. No installation required.
    "},{"location":"strategies/options_bear_call_ladder/#bear-call-ladder","title":"Bear Call Ladder","text":"
    • In the stock market, an options bear call ladder is a strategy that involves buying and selling call options with different strike prices to profit from a moderate bearish outlook on the underlying asset. It is a complex strategy that combines both long and short call positions.

    • To create a bear call ladder, an investor typically does the following:

      1. Sells a lower strike call option.
      2. Buys two higher strike call options.
      3. Sells a final even higher strike call option.
    • The bear call ladder aims to generate a limited profit if the price of the underlying asset remains below the middle strike price at expiration. The strategy benefits from time decay and a moderate decrease in the price of the underlying asset.

    • The maximum profit potential of the bear call ladder is achieved when the price of the underlying asset is below the middle strike price at expiration. If the price declines further, the profit potential remains limited. However, if the price rises above the higher strike price, the strategy can result in losses.

    • The key feature of the bear call ladder is the combination of short call options, which generate premium income, and long call options, which provide protection against unlimited losses in case the price of the underlying asset rises sharply.

    • Traders implementing the bear call ladder strategy should carefully consider factors such as the strike prices, premium costs, and expiration date to assess their risk-reward profile. It's important to note that options trading involves risks, and traders should have a thorough understanding of the strategy and associated risks before employing it in the stock market.

    • Please be aware that options trading can be complex and involves significant risks. It is always recommended to consult with a qualified financial advisor or broker before engaging in options trading activities.

    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Options from Indian Exchange (NSE)

    • Click here to view a working notebook for options from NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for options from NSE exchange in cloud. No installation required.
    "},{"location":"strategies/options_bear_put_ladder/#bear-put-ladder","title":"Bear Put Ladder","text":"
    • In the stock market, an options bear put ladder is a strategy that combines buying and selling put options with different strike prices to profit from a moderate bearish view on the underlying asset. It involves a mix of long and short put positions.

    • To implement a bear put ladder strategy, an investor generally follows these steps:

      1. Buys a put option with a lower strike price.
      2. Sells two put options with higher strike prices.
      3. Buys a final put option with an even higher strike price.
    • The goal of the bear put ladder is to generate a limited profit if the price of the underlying asset remains below the middle strike price at expiration. The strategy benefits from time decay and a moderate decline in the price of the underlying asset.

    • The maximum profit potential is reached when the price of the underlying asset is below the middle strike price at expiration. If the price continues to decrease, the profit potential remains limited. However, if the price rises above the higher strike price, the strategy can result in losses.

    • The bear put ladder strategy combines short put options to generate premium income and long put options to provide protection against significant losses in case the price of the underlying asset declines substantially.

    • Traders implementing the bear put ladder strategy should consider factors such as the strike prices, premium costs, and expiration date to assess the risk-reward profile. It's crucial to have a comprehensive understanding of options trading and associated risks before employing this strategy in the stock market.

    • Keep in mind that options trading can be complex and involves substantial risks. It is advisable to consult with a qualified financial advisor or broker before engaging in options trading activities.

    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Options from Indian Exchange (NSE)

    • Click here to view a working notebook for options from NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for options from NSE exchange in cloud. No installation required.
    "},{"location":"strategies/options_bull_call_ladder/#bull-call-ladder","title":"Bull Call Ladder","text":"
    • In the stock market, an options bull call ladder is a strategy that involves buying and selling call options with different strike prices to profit from a moderate bullish outlook on the underlying asset. It is a complex strategy that combines both long and short call positions.

    • To create a bull call ladder, an investor typically does the following:

      1. Buys a lower strike call option.
      2. Sells two higher strike call options.
      3. Buys a final even higher strike call option.
    • The key feature of the bull call ladder is that it provides limited risk and potential for limited profit. The strategy is constructed in such a way that it can benefit from both a moderate rise in the price of the underlying asset and from time decay.

    • The profit potential of the bull call ladder is highest if the price of the underlying asset rises to the level of the middle strike price at expiration. In this case, the investor can achieve the maximum profit. If the price of the underlying asset rises above the middle strike price, the profit potential is limited.

    • On the other hand, if the price of the underlying asset remains below the lower strike price or declines, the strategy can result in losses. The maximum loss occurs if the price falls below the lower strike price.

    • The bull call ladder is a moderately bullish strategy that aims to benefit from both time decay and the potential for a moderate increase in the price of the underlying asset. Traders implementing this strategy should carefully consider factors such as the strike prices, premium costs, and expiration date to assess their risk-reward profile.

    • It is important to note that options trading involves risks, and traders should have a thorough understanding of the strategy and associated risks before employing it in the stock market.

    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Options from Indian Exchange (NSE)

    • Click here to view a working notebook for options from NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for options from NSE exchange in cloud. No installation required.
    "},{"location":"strategies/options_bull_put_ladder/#bull-put-ladder","title":"Bull Put ladder","text":"
    • In the stock market, an options bull put ladder is a strategy that involves buying and selling put options with different strike prices to profit from a moderate bullish outlook on the underlying asset. It is a complex strategy that combines both long and short put positions.

    • To create a bull put ladder, an investor typically does the following:

      1. Sells a higher strike put option.
      2. Buys two lower strike put options.
      3. Sells a final even lower strike put option.
    • The key feature of the bull put ladder is that it provides limited risk and potential for limited profit. The strategy is constructed in such a way that it can benefit from both a moderate rise in the price of the underlying asset and from time decay.

    • The profit potential of the bull put ladder is highest if the price of the underlying asset rises to the level of the middle strike price at expiration. In this case, the investor can achieve the maximum profit. If the price of the underlying asset rises above the middle strike price, the profit potential is limited.

    • On the other hand, if the price of the underlying asset remains above the higher strike price or increases, the strategy can result in losses. The maximum loss occurs if the price rises above the higher strike price.

    • The bull put ladder is a moderately bullish strategy that aims to benefit from both time decay and the potential for a moderate increase in the price of the underlying asset. Traders implementing this strategy should carefully consider factors such as the strike prices, premium costs, and expiration date to assess their risk-reward profile.

    • It is important to note that options trading involves risks, and traders should have a thorough understanding of the strategy and associated risks before employing it in the stock market.

    "},{"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":"
    • The transaction_type_map, tradingsymbol_suffix_map, and strike_direction_map dictionaries are used for mapping transaction types, trading symbol suffixes, and strike directions, respectively.

    • The strategy supports a single allowed expiry date, which can be modified for multiple expiry dates.

    • The strategy uses the get_options_instrument_with_strike_direction method from the base class to fetch child instruments.

    • The initialize method sets up the list of instruments processed for the day.

    • The options_instruments_set_up_local method sets up the Call and Put Options instruments for a given base instrument.

    • The strategy_select_instruments_for_entry method selects instruments for entry by setting up child instruments and appending them to the selected instruments list.

    • The strategy_enter_position method

    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)
    "},{"location":"strategies/options_long_iron_butterfly/#long-iron-butterfly","title":"Long Iron Butterfly","text":"
    • In the stock market, an options long iron butterfly is a complex strategy that involves buying two options with the same expiration date but different strike prices. It combines elements of both a bullish and bearish strategy and is designed to profit from low volatility in the underlying asset.

    • To create a long iron butterfly, an investor typically does the following:

      1. Buys an at-the-money (ATM) put option.
      2. Buys an ATM call option.
      3. Sells an out-of-the-money (OTM) put option with a lower strike price.
      4. Sells an OTM call option with a higher strike price.
    • The key feature of the long iron butterfly is that the sold options (OTM put and OTM call) help offset the cost of the purchased options (ATM put and ATM call). This results in a limited-risk, limited-reward strategy.

    • The strategy profits when the price of the underlying asset remains within a specific range, known as the \"profit zone.\" The profit zone is determined by the strike prices of the options involved in the strategy. If the price of the underlying asset is within this range at expiration, the investor can achieve the maximum profit.

    • However, if the price of the underlying asset moves significantly beyond the profit zone, the strategy can result in losses. The maximum loss occurs if the price falls below the lower strike price or rises above the higher strike price.

    • The long iron butterfly is commonly used when traders anticipate low volatility in the underlying asset. It is a neutral strategy that seeks to benefit from the passage of time and a decrease in implied volatility. Traders implementing this strategy should carefully analyze factors such as the strike prices, premium costs, and expiration date to determine their risk-reward profile.

    • It is important to note that options trading involves risks, and traders should have a thorough understanding of the strategy and associated risks before employing it in the stock market.

    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Options from Indian Exchange (NSE)

    • Click here to view a working notebook for options from NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.
    "},{"location":"strategies/options_straddle/#straddle-options","title":"Straddle Options","text":"
    • In the stock market, an options straddle is a strategy where an investor simultaneously purchases a call option and a put option with the same strike price and expiration date on a particular underlying asset, such as a stock. The purpose of this strategy is to profit from significant price movements in the underlying asset, regardless of whether the price goes up or down.

    • By using an options straddle, the investor is essentially betting on volatility rather than the direction of the price movement. If the price of the underlying asset experiences a substantial increase or decrease, either the call or put option will generate profits, offsetting any losses from the other option. The potential for profit is highest when there is a significant price swing, while the risk is limited to the cost of purchasing the options.

    • This strategy is often employed when traders anticipate an upcoming event or announcement that could cause significant market volatility, such as earnings reports or regulatory decisions. The goal is to take advantage of the resulting price movement, regardless of whether it is upward or downward.

    • It is important to note that options straddles can be risky as they require significant price movements to be profitable. If the price remains relatively stable, the trader may experience losses due to the cost of purchasing the options. Therefore, careful consideration of market conditions and risk management is crucial when implementing an options straddle strategy.

    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Options from Indian Exchange (NSE)

    • Click here to view a working notebook for options from NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for options from NSE exchange in cloud. No installation required.
    "},{"location":"strategies/options_strangle/#strangle-options","title":"Strangle Options","text":"
    • In the stock market, an options strangle is a strategy where an investor simultaneously buys or sells a call option and a put option on the same underlying asset but with different strike prices and the same expiration date. The purpose of this strategy is to profit from significant price volatility in the underlying asset.

    • Unlike an options straddle, which involves purchasing options at the same strike price, an options strangle involves selecting different strike prices. Typically, the investor buys an out-of-the-money call option (with a strike price above the current market price) and an out-of-the-money put option (with a strike price below the current market price).

    • The strategy aims to benefit from a significant price movement in either direction. If the price of the underlying asset moves significantly upwards, the call option can generate profits. Conversely, if the price moves significantly downwards, the put option can generate profits. The investor is essentially betting on increased price volatility rather than predicting the direction of the price movement.

    • Options strangles are commonly used when traders anticipate a substantial price movement but are unsure about the direction. This strategy allows for potential profits in either an upward or downward market scenario. However, it is important to note that options strangles can involve higher risks, as the underlying asset's price must move significantly to offset the cost of purchasing both options.

    • Traders employing options strangles should carefully consider factors such as the expected price volatility, the expiration date, and the costs associated with purchasing the options. Implementing risk management techniques and monitoring market conditions are essential when utilizing an options strangle strategy.

    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.

    Jupyter Notebook for US Exchange (NASDAQ)

    • Click here to view a working notebook for NASDAQ exchange in cloud. No installation required.
    • Click here to execute a working notebook for NASDAQ exchange in cloud. No installation required.
    "},{"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:

    • The Relative Strength Index (RSI) is a momentum oscillator that measures the speed and change of price movements.
    • It compares the magnitude of recent gains to recent losses over a specified period, typically 14 days, and generates a value between 0 and 100.
    • The RSI is calculated using a formula that involves averaging the upward price movements (gains) and the downward price movements (losses) over the chosen period.
    • A high RSI value (typically above 70) indicates that a stock is overbought, meaning it may have experienced a significant price increase and could be due for a correction or pullback.
    • Conversely, a low RSI value (typically below 30) suggests that a stock is oversold, indicating it may have experienced a significant price decline and could be poised for a potential rebound or upward move.
    • Traders often use RSI as a tool to identify potential trend reversals, as extreme RSI readings (above 70 or below 30) can signal a potential change in the direction of the price trend.
    • Additionally, traders may look for bullish or bearish divergences between the RSI and the price chart, which can provide further indications of a potential trend reversal.
    • The RSI is just one tool among many in technical analysis, and it is often used in conjunction with other indicators and analysis techniques to make more informed trading decisions.

    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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.
    "},{"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.

    • The RSI is an oscillator that measures the speed and change of price movements. RSI values above 70 typically indicate an overbought condition, signaling a potential price reversal to the downside. RSI values below 30 suggest an oversold condition, indicating a potential price reversal to the upside.

    • The essence of this strategy lies in the crossover of the MACD and RSI indicators. When the MACD generates a bullish crossover and the RSI confirms by being below 70 (not in an overbought condition), it could be an opportune time to consider a long (BUY) position.

    • Conversely, when the MACD produces a bearish crossover and the RSI is above 30 (not in an oversold condition), it may be a suitable moment to contemplate a short (SELL) position.

    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.

    Jupyter Notebook for US Exchange (NASDAQ)

    • Click here to view a working notebook for NASDAQ exchange in cloud. No installation required.
    • Click here to execute a working notebook for NASDAQ exchange in cloud. No installation required.
    "},{"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:

    • The Stochastic Oscillator measures the relationship between a security's closing price and its price range over a chosen period.
    • The indicator consists of two lines: %K and %D. %K represents the current closing price relative to the price range, while %D is a smoothed average of %K.
    • The Stochastic Oscillator is bound between 0 and 100. Readings above 80 are typically considered overbought, suggesting a potential price decline or correction. Readings below 20 are often considered oversold, indicating a potential price increase or rebound.
    • Traders use the Stochastic Oscillator to identify potential trend reversals, as overbought or oversold conditions can indicate a possible change in the direction of the price trend.
    • The indicator also generates bullish or bearish divergences, where the price trend and the Stochastic lines move in opposite directions, which can signal a potential trend reversal.
    • The Stochastic Oscillator has various trading strategies associated with it, such as crossovers, overbought/oversold levels, and divergences, which traders use to make buy or sell decisions.
    • It is important to note that the Stochastic Oscillator is a lagging indicator, meaning it may not provide precise timing for trade entries or exits. Therefore, it is often used in conjunction with other indicators and analysis techniques to confirm signals and improve the accuracy of trading decisions.
    • Overall, the Stochastic Oscillator is a widely used technical indicator in the stock market that helps traders assess price momentum, identify overbought and oversold conditions, and spot potential trend reversals. By analyzing the relationship between the closing price and price range, traders can gain insights into potential buying or selling opportunities.
    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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.
    "},{"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.

    • ATR serves as a reliable volatility indicator. It quantifies the market's propensity for price movement. Elevated ATR values indicate significant price fluctuations, while lower values suggest relative price stability.

    • ATR is adaptable to individual trading preferences. Traders can tailor the ATR period to match their specific trading style. For daily charts, a typical choice is the 14-day period, but adjustments can be made for shorter or longer timeframes, allowing for versatile application.

    • ATR provides a numerical value, and its magnitude corresponds to the extent of market volatility. Larger ATR values signal more significant trading opportunities, much like a roller coaster promising an exhilarating ride.

    • However, ATR isn't solely focused on turbulence. It effectively identifies periods of low volatility or consolidation in the market, signaling a need for caution or a potential shift in trading strategies.

    "},{"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

    • Strategy Code (.py)
    • Strategy Structure (common methods used in a regular and options strategy)

    Jupyter Notebook for Indian Exchange (NSE)

    • Click here to view a working notebook for NSE exchange in cloud. No installation required.
    • Click here to execute a working notebook for NSE exchange in cloud. No installation required.

    Jupyter Notebook for US Exchange (NASDAQ)

    • Click here to view a working notebook for NASDAQ exchange in cloud. No installation required.
    • Click here to execute a working notebook for NASDAQ exchange in cloud. No installation required.
    "},{"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:

    • VWAP is calculated by multiplying the price of each trade by the corresponding volume and then summing up these values over a specific time period. The total value is divided by the cumulative volume to obtain the average price.
    • The volume-weighted aspect of VWAP gives more weight to trades with higher volume, reflecting the significance of larger trades in the overall average price calculation.
    • VWAP is typically calculated on an intraday basis, such as the trading day or a specific session, and resets at the start of each new period.
    • Traders and investors use VWAP as a benchmark to assess whether their own trades are executed at a better or worse price compared to the average market price. It helps evaluate the quality of their execution and determine if they are buying or selling at a favorable price.
    • VWAP is commonly used by institutional traders who execute large orders as it helps them minimize market impact and avoid unfavorable executions. By comparing their execution price to VWAP, they can assess their performance and adjust their trading strategies accordingly.
    • In addition to being used as a benchmark, VWAP is also employed as a trading strategy. Some traders use VWAP as a reference point for making buy or sell decisions. For example, if the current price is above VWAP, it may be considered bullish, while a price below VWAP could be seen as bearish.
    • VWAP is often displayed as a line on intraday price charts, allowing traders to visually compare the current price to the average price. It can provide insights into the market's overall sentiment and potential support or resistance levels.
    • It is important to note that VWAP is a lagging indicator since it is based on historical data. Therefore, it is often used in combination with other indicators and analysis techniques to validate trade signals and make informed trading decisions.
    • Overall, VWAP is a widely used indicator in the stock market that provides a volume-weighted average price, serving as a benchmark for evaluating trade execution quality and as a reference point for trading decisions. By considering both price and volume, VWAP offers insights into market dynamics and helps traders assess their performance relative to the average market price.
    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

    • Code Structure of Strategy (workflow of a strategy)
    "},{"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

    • The parameter names and the number of parameters may change for different strategies.
    "},{"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":"
    • Stores the order object for the given tags. eg:
    self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
    • Here the _order is the order object stored inside the OrderTagManager for the tags base_inst_str and entry_key.
    "},{"location":"strategies/strategy_guides/common_options_strategy/#get_orders","title":"get_orders","text":"
    • Retrieve the order(s) for the given tags.

    eg:

    self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
    • Here the order object retrieved from the OrderTagManager for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER and entry_key
    "},{"location":"strategies/strategy_guides/common_options_strategy/#remove_tags","title":"remove_tags","text":"
    • Removes the tags stored in the OrderTagManager along with the orders related stored in that tag

    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":"
    • Remove the order(s) from the OrderTagManager for the given tag(s).

    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":"
    • In this method we process each instrument in the instruments bucket, if there is some entry condition to be checked then we create a get_entry_decision method that calculates the entry condition like a crossover or compares the latest value of the OHLC data or indicator data.

    • When the order has to be placed we add the instrument to selectd_instruments_bucket and additional data related to the instrument that will be required while placing to the sideband_info. This information is passed to the strategy_enter_position method

    "},{"location":"strategies/strategy_guides/common_options_strategy/#strategy_enter_position","title":"strategy_enter_position","text":"
    • Here is where we actually place the entry order for which we calculate the quantity for the order to be placed. If the order is placed successfully we save the order in a class variable such that we can access the order object via the variable in the exit methods.
    "},{"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":"
    • This method is called before the entry methods because in the case of delivery strategy we want to resume and exit previous day orders before we can place new entry orders.
    • Here we place stoploss exit orders, target exit orders, and check for exit conditions for the open entry orders.
    "},{"location":"strategies/strategy_guides/common_options_strategy/#strategy_exit_position","title":"strategy_exit_position","text":"
    • Here is where we actually place the exit order for where we exit the order which was placed during entry. If the order is placed successfully we clear the order in a class variable such that we can add new orders to the vacant place in variable in the entry methods.
    "},{"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":"
    • Options Bear Call Ladder
    • Options Bear Put Ladder
    • Options Bull Call Ladder
    • Options Bull Put Ladder
    • Options Long Iron Butterfly
    • Options Straddle
    • Options Strangle

    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

    • Code Structure of Strategy (workflow of a strategy)
    "},{"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

    • The parameter names and the number of parameters may be different for different strategies.
    "},{"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":"
    • Stores the order object for the given tags. eg:
      self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
    • Here the _order is the order object stored inside the OrderTagManager for the tags base_inst_str and entry_key.
    "},{"location":"strategies/strategy_guides/common_regular_strategy/#get_orders","title":"get_orders","text":"
    • Retrieve the order(s) for the given tags. eg:
      self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
    • Here the order object retrieved from the OrderTagManager for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER and entry_key
    "},{"location":"strategies/strategy_guides/common_regular_strategy/#remove_tags","title":"remove_tags","text":"
    • Removes the tags stored in the OrderTagManager along with the orders related stored in that tag 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 the order tags.

    "},{"location":"strategies/strategy_guides/common_regular_strategy/#remove_order","title":"remove_order","text":"
    • Remove the order(s) from the OrderTagManager for the given tag(s). 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_regular_strategy/#get_internals","title":"get_internals","text":"
    • Returns the values i.e. both the entry and exit orders stored inside the tags list.
    "},{"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":"
    • In this method we process each instrument in the instruments bucket, if there is some entry condition to be checked then we create an get_entry_decision method that calculates the entry condition like a crossover or compares the latest value of the OHLC data or indicator data.

    • When the order has to be placed we add the instrument to selected_instruments_bucket and additional data related to the instrument that will be required while placing to the sideband_info. This information is passed to the strategy_enter_position method

    "},{"location":"strategies/strategy_guides/common_regular_strategy/#strategy_enter_position","title":"strategy_enter_position","text":"
    • Here is where we actually place the entry order for which we calculate the quantity for the order to be placed. If the order is placed successfully we save the order in a class variable such that we can access the order object via the variable in the exit methods.
    "},{"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":"
    • This method is called before the entry methods because in the case of delivery strategy we want to resume and exit previous day orders before we can place new entry orders.
    • Here we place stoploss exit orders, target exit orders, and check for exit conditions for the open entry orders.
    "},{"location":"strategies/strategy_guides/common_regular_strategy/#strategy_exit_position","title":"strategy_exit_position","text":"
    • Here is where we actually place the exit order for where we exit the order which was placed during entry. If the order is placed successfully we clear the order in a class variable such that we can add new orders to the vacant place in variable in the entry methods.
    "},{"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":"
    • Aroon Crossover
    • Bollinger Bands
    • EMA Crossover
    • Inverse EMA Scalping
    • Reverse RSI
    • Stochastic Crossover
    • VWAP Crossover

    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:

    • Historical data is a time series data of open, high, low and close values of an instrument. These values are fetched at an interval same as that of the candle interval. The method given below fetches multiple historical data values till the current candle on which the strategy is executing. Historical data of the instrument up to a certain point in your strategy is collected using:
      hist_data = self.get_historical_data(instrument)\n
      Here the variable hist_data is a pandas.Dataframe object. A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional array, or a table with rows and columns. The hist_data Dataframe will have 4 columns named as : \u201copen\u201d, \u201chigh\u201d, \u201cclose\u201c and \u201clow\u201d. For every row there will be a unique timestamp and the difference between each timestamp is of candle interval.
    • To access all the values of one particular column from the hist_data, you can use the following syntax code. Remember the data type of the column fetched here is pandas.Series
      hist_data[\u2018<column_name>\u2019]\n
      Example:
      close = hist_data[\u2018close\u2019]\n
    • To access the O-H-L-C values of the current latest candle you can use the following code. This also tells us that the index -1 is for latest, -2 will be for second latest and so on. This also implies that index 0 will get the oldest data, index 1 will give second oldest data and so on.
      latest_ohlc = hist_data.iloc[-1]\n
    • Next, you analyse this historical data to determine trading signals and calculate indicator values. You can rely on functions from \"talib\" for this, as shown below:

      ema_x = talib.EMA(hist_data['close'], timeperiod=self.timeperiod1)\nema_y = talib.EMA(hist_data['close'], timeperiod=self.timeperiod2)\n
      As you can see, we have passed the \u201cclose\u201d column and a strategy parameter value called \u201cself.timeperiod1\u201d and \u201cself.timeperiod2\u201d to the talib function. Each of the talib functions require unique input values, some require pandas.Series, some require constants like integers and floats and some require both. To understand the working of each talib function, refer here.

    • In many strategies, the condition to buy or sell can be triggered based on the crossover direction of 2 signals/indicators. A crossover refers to an instance where an indicator and a price, or multiple indicators, overlap and cross one another. Crossovers are used in technical analysis to confirm patterns and trends such as reversals and breakouts, generating buy or sell signals accordingly. Below we have given an example of how to calculate the crossover of the 2 indicator values we had calculated above.

      crossover_value = self.utils.crossover(ema_x, ema_y)\n
      Here if crossover_value is 0 then the indicators ema_x and ema_y have not crossed. If it is 1 then indicator ema_x has crossed ema_y in upward direction. Similarly if it is -1 then indicator ema_x has crossed ema_y in downward direction

    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:

    • base_instrument: The foundation of your options strategy, often represented by an index.
    • tradingsymbol_suffix: Specifies whether the option should be a call option (CE) or a put option (PE), determining the trading symbol's suffix.
    • strike_direction: Defines the direction relative to the current strike price, with options like \"In The Money\" (ITM), \"Out of The Money\" (OTM), and \"At the Money\" (ATM).
    • no_of_strikes: Specifies how many strikes away from the current strike price the function should consider, setting the distance in strike prices within the chosen strike direction.

    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.

    • If number_of_allowed_expiry_dates is set to 1, the function returns the monthly expiry date.
    • If number_of_allowed_expiry_dates is set to 0, the function returns a weekly expiry date.

    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:

    • base_instrument: The foundation of your options strategy.
    • expiry_date: The expiry date of the child instrument, calculated using the \"get_allowed_expiry_dates\" function.
    • tradingsymbol_suffix: Specifies whether the option should be a call option (CE) or a put option (PE), helping identify the appropriate options.
    • strike_direction: Determines the direction in relation to the current strike price, offering options like \"In The Money\" (ITM), \"Out of The Money\" (OTM), and \"At the Money\" (ATM).
    • no_of_strikes: Specifies how many strikes away from the current strike price the function should consider, defining the distance in strike prices within the chosen strike direction.
    "},{"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:

    • base_instrument: The foundation of your options strategy, typically an index.
    • tradingsymbol_suffix: Specifies whether the child instrument should be a call option (CE) or a put option (PE), aiding in the identification of the appropriate options.
    • current_close (strike_price): The current price of the base instrument, also known as the strike price.
    • direction: Determines the direction in relation to the current strike price, helping select the child instrument (i.e., ATM, ITM, or OTM).

    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:

    • base_instrument: The foundation of your options strategy.
    • direction: Determines the direction in relation to the current strike price, helping select the child instrument (i.e., ATM, ITM, or OTM).
    • expiry_date: The expiry date of the child instrument, calculated using the \"get_allowed_expiry_dates\" function.
    • tradingsymbol_suffix: Specifies whether the child instrument should be a call option (CE) or a put option (PE), aiding in the identification of the appropriate options.
    • current_close: The current price of the base instrument, also known as the strike price.

    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:

    • candle: The current candle where the strategy is executing its algorithm.
    • instrument_bucket: A list of all the instruments provided by the user when starting the strategy. Here, you iterate through the instruments, calling \"self.get_decision()\" to determine actions for each. For options strategies, you can also use \"self.options_instruments_set_up_local()\" to set up child instruments for each base instrument. The selected instruments and their meta-information are returned by the function.

    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:

    • candle: The current candle where the strategy is executing its algorithm.
    • instrument: One of the instruments from the selected instruments list returned by \"strategy_select_instruments_for_entry.\"
    • meta: Meta-information of that particular instrument, aligning with the instrument from the meta list.

    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/#orderregular","title":"OrderRegular","text":"

    The self.broker.OrderRegular is used to place the entry/exit orders.

    "},{"location":"strategies/strategy_guides/common_strategy_guide/#parameters","title":"Parameters:","text":"
    • instrument: Instrument object on which to place the order.
    • action: Action to be taken, either 'BUY' or 'SELL'.
    • quantity: The quantity of the order, generally calculated as self.number_of_lots * instrument.lot_size.
    • order_variety: (Optional) Type of order. Default is MARKET order (BrokerOrderVarietyConstants.MARKET).
    • price: (Optional) The price at which the limit order will be placed.
    • trigger_price: (Optional) The trigger price for stop-loss orders.

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

    Market OrderLimit OrderStoploss Market OrderStoploss Limit Order
    self.broker.OrderRegular(\n    instrument,\n    action, \n    quantity \n    )\n
    self.broker.OrderRegular(\n    instrument, \n    action, \n    quantity, \n    order_variety=BrokerOrderVarietyConstants.LIMIT, \n    price=price \n    )\n
    self.broker.OrderRegular(\n    instrument, \n    action, \n    quantity, \n    order=order_variety=BrokerOrderVarietyConstants.STOPLOSS_MARKET, \n    trigger_price=trigger_price\n    )\n
    self.broker.OrderRegular(\n    instrument,  \n    action, \n    quantity,  \n    order_variety=BrokerOrderVarietyConstants.STOPLOSS_LIMIT, \n    price=price, \n    trigger_price=trigger_price\n)\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:

    • candle: The current candle where the strategy is executing its algorithm.
    • instrument_bucket: A list of all instruments provided by the user when starting the strategy.

    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:

    • candle: The current candle where the strategy is executing its algorithm.
    • instrument: One of the instruments from the selected instruments list returned by \"strategy_select_instruments_for_exit.\"
    • meta: Meta-information of that particular instrument, aligning with the instrument from the meta list.

    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 the \"EMA Crossover Strategy\". Here, we are telling the core to exit all positions:

    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
    If you want the strategy to place the exit order instead of letting the core handle it, then this is what the function should look like:
    def strategy_exit_position(self, candle, instrument, meta):\n    if meta['action'] == 'EXIT':\n        self.broker.OrderRegular(\n            instrument,\n            action,\n            quantity,\n            related_order=entry_order,\n            position=BrokerExistingOrderPositionConstants.EXIT\n            )\n        return True\n    return False\n

    Note

    • meta['action'] has to be opposite of the entry order's transaction type. For example: if the entry order is 'BUY', then meta['action'] should be 'SELL', and vice versa.
    • Pass the entry order object as the related_order parameter.
    • You can specify a lesser quantity if you want to partially exit your entry order. In case of partial exits, ensure that you return 'True' only if the quantity becomes zero after placing this order, else return 'False' for your intermediate/partial exits.
    "},{"location":"strategies/strategy_guides/fee/","title":"Frequently Encountered Errors","text":""},{"location":"strategies/strategy_guides/fee/#execution-time-exceeded-timeout_duration-duration-of-60-sec","title":"Execution time exceeded timeout_duration duration of 60 sec.","text":""},{"location":"strategies/strategy_guides/fee/#possible-causes","title":"Possible Causes","text":"
    • Historical Data Fetching Duration:

      Fetching historical data may take longer, especially if the duration is set to a large number of days.

    • Suboptimal Decision-Making Logic:

      The decision-making logic might be suboptimal, leading to increased processing time.

    • Sequential Execution Approach:

      A sequential approach of fetching historical data and then making the decisions in case of multiple instruments can contribute to delays.

    • Real-Time Calculations:

      If there are calculations that could be pre-conditioned or pre-calculated before the market opens, optimizing real-time calculations might help.

    "},{"location":"strategies/strategy_guides/fee/#solutions","title":"Solutions","text":"
    • Optimize Historical Data Fetching:

      Consider reducing the number of days for which historical data is fetched. A shorter duration, like 5 days, can be a reasonable compromise.

      @staticmethod\ndef get_historical_data_duration():\n    return 5\n
    • Optimize the Decision-Making logic:

      Revisit your strategy logic and check if any code block can be optimized.

    • Batch Processing for Decision-Making:

      In case of multiple instruments, lets say you are fetching the historical data for the instrument, and have implemented the decision-making logic for whether this instrument should get selected for order placement or not. Once this is done, you repeat the same process for the next instrument. Instead of a sequential approach, try fetching historical data for all instruments in one loop and then making decisions for all instruments in another loop.

    • Pre-Calculate Conditions:

      Identify conditions that can be pre-calculated before the market opens. Adjust the strategy start time to accommodate these pre-calculations. If certain conditions can be chcked before the market starts, set the trading start time of the strategy to a value before the market start time. Add specific checks inside the strategy to ensure that the actual order placement, etc. are executed after the market starts.

    "},{"location":"strategies/strategy_guides/fee/#no-data-in-charts","title":"No Data in Charts","text":""},{"location":"strategies/strategy_guides/fee/#description","title":"Description","text":"

    Encountering the \"NO data in charts\" error while running a strategy is a common issue. This problem arises when using a small quantity with very large funds. Limited visibility on charts due to large funds with a small quantity setting.

    "},{"location":"strategies/strategy_guides/fee/#possible-causes_1","title":"Possible Causes","text":"
    • Scale Discrepancy:

      The large fund amount may lead to extremely small values on the y-axis, which are not visible, causing charts to appear empty.

    • Default Quantity and Funds:

      Default quantity and funds settings, if not adjusted, may lead to similar issues with empty charts.

    "},{"location":"strategies/strategy_guides/fee/#solutions_1","title":"Solutions","text":"
    • Normalize Values:

      Normalize values by using larger quantities or scaling to ensure meaningful data display across various scenarios.

    • Adjust Default Settings:

      Consider adjusting default values to something more suitable for common scenarios. Charts displaying proper data with suitable funds and quantity settings

    "},{"location":"strategies/strategy_guides/fee/#openai-api-quota-depletion","title":"OpenAI API Quota Depletion","text":""},{"location":"strategies/strategy_guides/fee/#description_1","title":"Description","text":"

    The \"OpenAI API current quota exceeded\" error indicates that the current quota or available credits for the OpenAI API has been exhausted. This typically occurs when the allotted usage limit for the API key has been reached.

    "},{"location":"strategies/strategy_guides/fee/#possible-causes_2","title":"Possible Causes","text":"
    • Credit Depletion:

      The API key has utilized its entire quota or available credits.

    "},{"location":"strategies/strategy_guides/fee/#solutions_2","title":"Solutions","text":"
    • Purchase More Credits:

      To continue using the OpenAI API, consider purchasing additional credits or upgrading your plan to increase the quota. Click here to add more credits.

    • Alternative Key:

      If available, switch to a different API key that still has unused credits.

    "},{"location":"strategies/strategy_guides/how_to/","title":"How to","text":""},{"location":"strategies/strategy_guides/how_to/#fetch-last-traded-price-ltp-of-an-instrument","title":"Fetch Last Traded Price (LTP) of an Instrument","text":"

    To fetch the Last Traded Price (LTP) of any instrument, use the following method:

    self.broker.get_ltp(instrument)\n

    This method retrieves the last traded price of the specified instrument.

    "},{"location":"strategies/strategy_guides/how_to/#access-attributes-of-an-instrument-object","title":"Access Attributes of an Instrument Object","text":"

    An instrument object typically contains various attributes providing information about the instrument:

    • exchange: Exchange on which the instrument is listed.
    • expiry: Expiration date of the instrument (applicable for derivatives).
    • lot_size: Number of units in a single lot of the instrument.
    • strike_price: Strike price of the instrument (applicable for options).
    • segment: Trading segment of the instrument.
    • tradingsymbol: Unique trading symbol of the instrument.
    • tick_size: Minimum price movement (tick) of the instrument.

    To access these attributes, use the following notation:

    instrument.exchange\ninstrument.expiry\ninstrument.lot_size\ninstrument.strike_price\ninstrument.segment\ninstrument.tradingsymbol\ninstrument.tick_size\n
    "},{"location":"strategies/strategy_guides/how_to/#fetch-different-types-of-instruments","title":"Fetch Different Types of Instruments","text":"

    To fetch different types of instruments, use the get_instruments_filtered method:

    Method Signature:

    self.broker.get_instruments_filtered(segment, tradingsymbol_exact=None, tradingsymbol_prefix=None, tradingsymbol_suffix=None, expiry=None)\n
    Example:
    from datetime import date\ninstruments = self.broker.get_instruments_filtered(segment='NSE_FO', tradingsymbol_prefix='NIFTY', expiry=date(2024,01,04))\n

    This example fetches equity instruments with a trading symbol prefix of 'NIFTY' and an expiry date of 4th January, 2024.

    "},{"location":"strategies/strategy_guides/how_to/#access-attributes-of-an-order-object","title":"Access Attributes of an Order Object","text":"

    An order object typically contains various attributes providing information about the order:

    • entry_price: Entry price of the order.
    • id: AlgoBulls specific alphanumeric order ID.
    • instrument: Instrument for which the order is placed.
    • order_code: Code for the order type (INTRADAY/DELIVERY).
    • order_time: Time at which the order is placed.
    • order_transaction_type: Type of transaction (BUY/SELL).
    • order_type: Type of order (REGULAR/BRACKET/COVER).
    • order_variety: Variety of the order (MARKET, LIMIT, STOPLOSS_MARKET, STOPLOSS_LIMIT).
    • position: Position (ENTER/EXIT).
    • price: Price of the order.
    • quantity: Order quantity.
    • quantity_pending: Quantity that is currently pending.
    • trigger_price: Trigger price of the order.

    To access these attributes, use the following notation:

    order.entry_price\norder.id\norder.instrument\norder.order_code\norder.order_time\norder.order_transaction_type\norder.order_type\norder.order_variety\norder.position\norder.price\norder.quantity\norder.quantity_pending\norder.trigger_price\n

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

    Coding Prerequisites

    • For pyalgotrading check here.
    • For Python Build Web check here.
    "},{"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

    • Strategy Structure (regular)
    • Strategy Structure (options)
    "},{"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":"Support pyalgo","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":"Python Build Support","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":"
    • Log in to your AlgoBulls account and choose Python Build from the left-side menu.
    • From the Python Build Splash Screen, choose the My Coded Strategies section display card. This is the section that holds all your saved strategies, whether you have coded them from scratch or modified them from ready templates.
    • Click and open the strategy that you think requires our assistance.

    "},{"location":"support/support_pybuild/#need-support","title":"Need Support","text":"
    • In the chosen strategy, click on the Need Support button on the top right corner of the page.

    • From the pop-up window that appears, click on the Select Strategy dropdown and choose the name of your strategy.

    • Write your query in the Explain your query briefly dialog box. This will help our team to get the best solution for you.

    • Click the Submit button. Our team will reach out to you with the solution within 1-2 business days.

    "}]} \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index 95380062..5430baff 100644 Binary files a/sitemap.xml.gz and b/sitemap.xml.gz differ