From 1bb8af0baaab64e9aad28799b1ba8fec4de03912 Mon Sep 17 00:00:00 2001
From: prithviraj-gotepatil-algobulls 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. 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. 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. 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".
+Support / Seeking AssistanceOverview¶
Contribution Guidelines
Last update:
- 2023-08-31
+ 2023-10-22
diff --git a/pyalgotrad/testing/index.html b/pyalgotrad/testing/index.html
index 5b61ac47..d5924710 100644
--- a/pyalgotrad/testing/index.html
+++ b/pyalgotrad/testing/index.html
@@ -830,6 +830,13 @@
Fetch Report Statistics
+
Fetch logs
logs = algobulls_connection.get_backtesting_logs(
strategy_code, # strategy code
- auto_update=True, # (default=True)update the logs and show your strategy progress. If False, will only fetch logs from start to the current stage of execution
- display_logs_in_auto_update_mode=True # only if auto_update is also True, will print logs as the progress is tracked
+ display_progress_bar=True, # (default=True) to track the execution on progress bar as your strategy is executed
+ print_live_logs: True # (default=False) to print the live logs as your strategy is executed
)
print(logs)
Fetch logs
logs = algobulls_connection.get_papertrading_logs(
strategy_code, # strategy code
- auto_update=True, # (default=True)update the logs and show your strategy progress. If False, will only fetch logs from start to the current stage of execution
- display_logs_in_auto_update_mode=True # only if auto_update is also True, will print logs as the progress is tracked
+ display_progress_bar=True, # (default=True) to track the execution on progress bar as your strategy is executed
+ print_live_logs: True # (default=True) to print the live logs as your strategy is executed
)
print(logs)
Fetch logs
logs = algobulls_connection.get_realtrading_logs(
strategy_code, # strategy code
- auto_update=True, # (default=True)update the logs and show your strategy progress. If False, will only fetch logs from start to the current stage of execution
- display_logs_in_auto_update_mode=True # only if auto_update is also True, will print logs as the progress is tracked
+ display_progress_bar=True, # (default=True) to track the execution on progress bar as your strategy is executed
+ print_live_logs: True # (default=True) to print the live logs as your strategy is executed
)
print(logs)
Fetch PnL Reports
algobulls_connection.get_backtesting_report_pnl_table(
- strategy_code, # strategy code
- show_all_rows=True, # default=True
- force_fetch=True, # pnl data is saved locally once fetched, to update the locally fetched data, make this parameter True
- country='USA', # country of the exchange that was used while starting the job ('India' or 'USA')
-)
+ strategy_code, # strategy code
+ show_all_rows=True, # default=True
+ force_fetch=True, # pnl data is saved locally once fetched, to update the locally fetched data, make this parameter True
+ country='USA', # country of the exchange that was used while starting the job ('India' or 'USA')
+ broker_commission_percentage: 1 # Percentage of broker commission per trade
+ broker_commission_price: 0.2 # Broker fee per trade
+ slippage_percent: 3 # Slippage percentage value
+)
algobulls_connection.get_papertrading_report_pnl_table(
- strategy_code, # strategy code
- show_all_rows=True, # default=True
- force_fetch=True, # pnl data is saved locally once fetched, to update the locally fetched data, make this parameter True
- country='USA', # country of the exchange that was used while starting the job ('India' or 'USA')
-)
+ strategy_code, # strategy code
+ show_all_rows=True, # default=True
+ force_fetch=True, # pnl data is saved locally once fetched, to update the locally fetched data, make this parameter True
+ country='USA', # country of the exchange that was used while starting the job ('India' or 'USA')
+ broker_commission_percentage: 1 # Percentage of broker commission per trade
+ broker_commission_price: 0.2 # Broker fee per trade
+ slippage_percent: 3 # Slippage percentage value
+)
Fetch Report Statistics
algobulls_connection.get_backtesting_report_statistics(
strategy_code, # strategy code
- mode='quantstats', # package used to generate statistics
- report='full', # format of the report
- html_dump=True # save report as html file
-)
+ report='full', # format of the report
+ html_dump=True # save report as html file
+)
algobulls_connection.get_papertrading_report_statistics(
strategy_code, # strategy code
- mode='quantstats', # package used to generate statistics
- report='full', # format of the report
- html_dump=True # save report as html file
-)
+ report='full', # format of the report
+ html_dump=True # save report as html file
+)
algobulls_connection.get_realtrading_report_statistics(
strategy_code, # strategy code
- mode='quantstats', # package used to generate statistics
- report='full', # format of the report
- html_dump=True # save report as html file
-)
+ report='full', # format of the report
+ html_dump=True # save report as html file
+)
+Generate Statistics from External CSV¶
+
Click on each of the tabs to see the relevant code snippet.
order_history = algobulls_connection.get_backtesting_report_order_history(strategy_code)
-print(order_history)
+
order_history = algobulls_connection.get_papertrading_report_order_history(strategy_code)
-print(order_history)
+
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:
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.
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.
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:
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:
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.
Algorithmic Trading: Alpaca's platform is tailored for algorithmic trading strategies, where traders can automate trading decisions based on predefined conditions and rules.
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.
Market Data: The platform offers access to real-time and historical market data, which is crucial for building and testing trading strategies.
Order Execution: Traders can use Alpaca's API to execute trades on supported exchanges. This includes submitting market, limit, and stop orders.
Customizable Dashboards: Alpaca provides customizable dashboards and interfaces to monitor trading activity and portfolio performance.
Brokerage Services: Alpaca acts as a brokerage, providing services that allow traders to execute their strategies on supported exchanges.
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/#how-to-get-api-keys-for-trading-in-alpaca","title":"How to get API-keys for trading in Alpaca ?","text":""},{"location":"brokers/broker_alpaca_guide/#create-or-login-to-alpaca-account","title":"Create or Login to Alpaca Account","text":""},{"location":"brokers/broker_alpaca_guide/#go-to-home-page-of-your-account","title":"Go to Home Page of your Account","text":""},{"location":"brokers/broker_alpaca_guide/#view-api-keys-or-generate-api-keys","title":"View API keys or Generate API keys","text":""},{"location":"brokers/broker_alpaca_guide/#get-the-secret-key-and-api-key","title":"Get theSecret-Key
and API key
","text":""},{"location":"brokers/broker_alpaca_guide/#why-do-we-need-alpaca-account","title":"Why do we need Alpaca Account ?","text":"If you want to run your strategy on American exchanges like NASDAQ or NYSE, you need access to the historical data as well as live data of all the stocks and that is provided by Alpaca. Besides this it will also be helpful to do live trading on AlgoBulls using these credentials.
"},{"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/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":"Execute Backtesting, Paper Trading, and Real Trading using 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":"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.
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.
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.
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.
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.
Reach out to AlgoBulls Support for any queries: If you encounter issues during the tutorial, contact the AlgoBulls Support team for assistance.
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":"master
branch.You will need the following to start with Pyalgotrading:
"},{"location":"pyalgotrad/prerequisites/#algobulls-account","title":"AlgoBulls Account","text":"To upload and test your strategies, you will need this account. You can create your account for FREE on the Algobulls website.
"},{"location":"pyalgotrad/prerequisites/#developer-key","title":"Developer Key","text":"To access the features, you will need a developer key. The key can be obtained as follows:
Please Note
For security reasons, the developer key will get reset every time you log out from your AlgoBulls account.
Once you have the developer key, you can access the AlgoBulls platform using pyalgotrading
functions.
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
pip install
commandTo 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:
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):\nname = 'SMA Regular Order Strategy'\nsuper().__init__(*args, **kwargs)\nself.timeperiod_x = self.strategy_parameters['timeperiod1']\nself.timeperiod_y = self.strategy_parameters['timeperiod2']\nself.main_order = None\n
The init
method does the following:
name
- variable which should store the name of your strategysuper()
- Calls the constructor of the superclass.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
.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.
def initialize()
","text":"def initialize(self):\nself.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
.
def name()
(optional)","text":"If the name
variable is defined in __init__()
, this function is not needed.
@staticmethod\ndef name():\nreturn '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():\nreturn AlgoBullsEngineVersion.VERSION_3_2_0\n
Mark both the above methods as @staticmethod
. The versions_supported
method does the following:
def strategy_select_instruments_for_entry()
","text":"def strategy_select_instruments_for_entry(self, candle, instruments_bucket):\ninstruments = []\nmeta = []\nfor instrument in instruments_bucket:\ncrossover_value = self.get_crossover_value(instrument)\nif crossover_value == 1:\ninstruments.append(instrument)\nmeta.append({'action': 'BUY'})\nelif crossover_value == -1:\nif self.strategy_mode is StrategyMode.INTRADAY:\ninstruments.append(instrument)\nmeta.append({'action': 'SELL'})\nreturn instruments, meta\n
The strategy_select_instruments_for_entry
method does the following:
instruments
and meta
- Creates 2 empty lists that will be used to pass the selected instruments and additional information about them respectively.crossover_value
- The crossover value is calculated and stored here. Crossover values are interpreted as:instruments
, and the associated action (BUY/SELL) is appended to the meta
.instruments
and meta
- Both the lists (whether populated or empty) are returned to the platform for further actions.Note
elif
part.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.meta
. The Entry position will be taken in the next method below.meta
contains a very versatile dictionary object. You may use it to pass any other additional information that you wish. def strategy_enter_position()
","text":"def strategy_enter_position(self, candle, instrument, sideband_info):\nif sideband_info['action'] == 'BUY':\nqty = self.number_of_lots * instrument.lot_size\nself.main_order[instrument] = \\\n self.broker.BuyOrderRegular(instrument=instrument,\norder_code=BrokerOrderCodeConstants.INTRADAY,\norder_variety=BrokerOrderVarietyConstants.MARKET,\nquantity=qty)\nelif sideband_info['action'] == 'SELL':\nqty = self.number_of_lots * instrument.lot_size\nself.main_order[instrument] = \\\n self.broker.SellOrderRegular(instrument=instrument,\norder_code=BrokerOrderCodeConstants.INTRADAY,\norder_variety=BrokerOrderVarietyConstants.MARKET,\nquantity=qty)\nelse:\nraise SystemExit(f'Got invalid sideband_info value: {sideband_info}')\nreturn self.main_order[instrument]\n
"},{"location":"pyalgotrad/programexample/#or","title":"or","text":"def strategy_enter_position(self, candle, instrument, meta):\nself.main_order_map[instrument] = _ = self.broker.OrderRegular(\nintrument=instrument, \norder_transaction_type=meta['action'], # 'BUY' or 'SELL'\nquantity=self.number_of_lots * instrument.lot_size, # number of lots (int)\nprice=None,\ntrigger_price=None\n)\nreturn _\n
The strategy_enter_position
method does the following:
sideband_info
and perform the required action (BUY/SELL).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.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.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,\norder_code=BrokerOrderCodeConstants.INTRADAY,\norder_variety=BrokerOrderVarietyConstants.LIMIT,\nquantity=qty,\nprice=ltp,\nstoploss_trigger=ltp - (ltp * self.stoploss),\ntarget_trigger=ltp + (ltp * self.target),\ntrailing_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
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.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). def strategy_select_instruments_for_exit()
","text":"def strategy_select_instruments_for_exit(self, candle, instruments_bucket):\ninstruments = []\nmeta = []\nfor instrument in instruments_bucket:\nif self.main_order.get(instrument) is not None:\ncrossover_value = self.get_crossover_value(instrument)\nif crossover_value in [1, -1]:\ninstruments.append(instrument)\nmeta.append({'action': 'EXIT'})\nreturn instruments, meta\n
The strategy_select_instruments_for_exit
method does the following:
instruments
and meta
- Creates 2 empty lists that will be used to pass the selected instruments and additional information about them respectively.self.main_order
object is None
or not, and proceed only if it is not None
. crossover_value
- The crossover value is calculated and stored here. Crossover values are interpreted as:instruments
, and the associated action (EXIT) is appended to the meta
.instruments
and meta
- Both the lists (whether populated or empty) are returned to the platform for further actions.Note
meta
. The Exit position will be taken in the next method below.meta
contains a very versatile dictionary object. You may use it to pass any other additional information that you wish.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. def strategy_exit_position()
","text":"def strategy_exit_position(self, candle, instrument, sideband_info):\nif sideband_info['action'] == 'EXIT':\nself.main_order[instrument].exit_position()\nself.main_order[instrument] = None\nreturn True\nreturn False\n
The strategy_exit_position
method does the following:
sideband_info
.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.self.main_order
- set it to None
, as the order has been exited and no longer holds anything.True
to the platform if the exit steps were performed, else return False
.def get_crossover_value()
","text":"def get_crossover_value(self, instrument):\nhist_data = self.get_historical_data(instrument)\nsma_x = talib.SMA(hist_data['close'], timeperiod=self.timeperiod_x)\nsma_y = talib.SMA(hist_data['close'], timeperiod=self.timeperiod_y)\ncrossover_value = self.utils.crossover(sma_x, sma_y)\nreturn crossover_value\n
The get_crossover_value
method does the following:
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 measuredvolume
- the volume of that instrumentopen
, high
, low
and close
- the OHLC values of the instrumentoi
- the Open Interest of that instrumentsma_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']
.crossover_value
- calculates the crossover value using the crossover
method from the utils
package.Note
crossover
method of the utils
package is very important.crossover
function, the answer you will get is -1 (Cut downwards).crossover
function, thus making the order of parameters passed an important point to be aware of, while coding the strategy.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":"Once you start the strategy, it may take a while for it to complete the execution. You can switch to the Analytics tab after you run your strategy. Even if the strategy execution is not complete, you will still see intermediate results.
Analytics: In the analytics section, you can view a strategy\u2019s Stats & various other metrics in the form of graphs like P&L.
"},{"location":"pyalgotrad/python-build-view-results/#stats","title":"Stats","text":"In this section you can see the total returns, sharpe ratio, sortino ratio, volatility, Max Drawdown, Total wins or Loses, Total short or long trades, hit ratio, number of trades, average trades per day, max profit, max loss, average profit per winning trade, average loss per losing trade.
"},{"location":"pyalgotrad/python-build-view-results/#cumulative-returns","title":"Cumulative Returns","text":""},{"location":"pyalgotrad/python-build-view-results/#profit-loss-currency-or","title":"Profit & Loss (Currency or %)","text":"The trade by trade P&L in Currency or Percentage.
"},{"location":"pyalgotrad/python-build-view-results/#end-of-year-returns-plot","title":"End of Year Returns Plot (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#monthly-returns-histogram","title":"Monthly Returns Histogram (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#monthly-returns-heatmap","title":"Monthly Returns Heatmap (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#daily-returns","title":"Daily Returns (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#underwater-drawdown-plot","title":"Underwater Drawdown Plot (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#pl-book","title":"P&L Book","text":"View detailed trade by trade report. Premium users can analyze this data in the form of heatmaps for Gross Profit & Loss, Trading Volume & Total number of Trades.
"},{"location":"pyalgotrad/python-build-view-results/#user-log","title":"User Log","text":"Real-time logs from strategy execution are displayed in this section. Use these logs to debug your strategy\u2019s behavior and performance.
"},{"location":"pyalgotrad/python-build-view-results/#order-history","title":"Order History","text":"View the order state transition for every order placed by your strategy in-depth.
"},{"location":"pyalgotrad/select/","title":"Select your Strategy","text":""},{"location":"pyalgotrad/select/#previously","title":"Previously...","text":"You have uploaded or saved a strategy by:
OR
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":"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
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":"strategy name
. Make sure you have the strategy with given name in your AlgoBulls Account. strategy_name = 'Exponential Moving Averages Crossover'\nstrategy_code, strategy_name = all_strategies_df.loc[all_strategies_df['strategyName'] == strategy_name].iloc[0] \n
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
You are now ready to test your uploaded strategy and perform Backtesting, Paper Trading and/or Real Trading with it.
"},{"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:
Open a Jupyter Notebook.
The steps you will follow are:
Run the following code snippets into the Jupyter Notebook one by one (or all together).
"},{"location":"pyalgotrad/testing/#create-a-new-strategy-file","title":"Create a new strategy file","text":"eg: strategy_<unique_code_if_needed>
_options_ema_crossover.py Make sure this strategy file is in the same folder as the jupyter notebook.
Coding Conventions
How to Code ?
To know more on how to code trading strategies and understand their format, click here. We have in detail explanation for regular strategies as well as options strategies
"},{"location":"pyalgotrad/testing/#import-statements","title":"Import statements","text":"from pyalgotrading.algobulls import AlgoBullsConnection\nfrom datetime import datetime as dt\nfrom pyalgotrading.constants import *\n
"},{"location":"pyalgotrad/testing/#establish-a-connection-to-the-algobulls-platform","title":"Establish a connection to the AlgoBulls Platform","text":"algobulls_connection = AlgoBullsConnection()\nalgobulls_connection.get_authorization_url()\n
The output of the above step is: Please login to this URL with your AlgoBulls credentials and get your developer access token: https://app.algobulls.com/user/login
Get Developer Key
You will need to log in to your AlgoBulls account and fetch the access token from: (See How) Settings -> General -> Developer Options
Once you have the access token, set it in the code as shown here:
algobulls_connection.set_access_token('4365817b795770ea31040a21ad29c8e78b63ad88')\n
Replace the token you have copied with the token in the code above.
"},{"location":"pyalgotrad/testing/#display-all-strategies-in-your-account","title":"Display all strategies in your account","text":"all_strategies = algobulls_connection.get_all_strategies()\nall_strategies\n
An example of the output will be:
"},{"location":"pyalgotrad/testing/#select-the-strategy","title":"Select the strategy","text":"Select the last entry of the strategyCode
column and display it.
strategy_code = all_strategies.iloc[-1]['strategyCode']\nstrategy_code\n
"},{"location":"pyalgotrad/testing/#print-your-strategy-code","title":"Print your Strategy code","text":"You can print your strategy code once to verify if this is the correct code. This step is optional.
strategy_details1 = algobulls_connection.get_strategy_details(strategy_code)\nprint(strategy_details1)\n
"},{"location":"pyalgotrad/testing/#search-for-instruments-based-on-a-search-query","title":"Search for instruments (based on a search query)","text":"Now display a few instruments with some keyword. The example below uses 'SBIN' as the keyword.
instruments = algobulls_connection.search_instrument('SBIN')\ninstruments\n
"},{"location":"pyalgotrad/testing/#select-an-instrument","title":"Select an instrument","text":"From the output, select the instrument on which you wish to test your strategy. For this example, select the first one.
instrument = instruments[0]['value']\ninstrument\n
"},{"location":"pyalgotrad/testing/#submit-a-job","title":"Submit a Job","text":"Delete previous trades
algobulls_connection.delete_previous_trades(strategy=strategy)\n
Set the parameters for the strategy
parameters={\n'timeperiod1': 5,\n'timeperiod2': 12\n}\n
vendor_details = {\n'brokerName': '<VENDOR_NAME>',\n'credentialParameters': {\n'api_key': '<API_KEY>',\n'secret_key': '<SECRET_KEY>'\n}\n}\n
broking_details = {\n'brokerName': '<BROKER_NAME>',\n'credentialParameters': {\n'user_id': '<USER_ID>',\n'api_key': '<API_KEY>',\n'password': '<PASSWORD>'\n}\n}\n
Click on each of the tabs to see the relevant code snippet.
BacktestingPaper TradingReal Tradingalgobulls_connection.backtest(\nstrategy=strategy_code, # strategy code\nstart='2020-7-1 09:15 +0530', # start date-time of strategy ('YYYY-MM-DD HH:MM z')\nend='2020-7-7 15:30 +0530', # end date-time of strategy ('YYYY-MM-DD HH:MM z')\ninstruments='NSE:SBIN', # name of the instrument\nlots=1, # number of lots per trade\nparameters=parameters, # parameters required for the strategy\ncandle='15 minutes', # candle size eg : '1 Day', '1 hour', '3 minutes'\ndelete_previous_trades=True, # delete the previous trades for papertrading (default is true),\ninitial_funds_virtual=10000, # virtual funds allotted before the paper trading starts (default is 1e9)\nvendor_details=vendor_details # vendor's details for authentication and verification \n)\n
algobulls_connection.papertrade(\nstrategy=strategy_code, # strategy code\nstart='09:15 +0530', # start time of strategy (HH:MM z) \nend='15:30 +0530', # end time of strategy (HH:MM z)\ninstruments='NSE:SBIN', # name of the instrument\nlots=1, # number of lots per trade\nparameters=parameters, # parameters required for the strategy\ncandle='15 minutes', # candle size eg : '1 Day', '1 hour', '3 minutes'\ndelete_previous_trades=True, # delete the previous trades for papertrading (default is true)\ninitial_funds_virtual=10000, # virtual funds allotted before the paper trading starts (default is 1e9)\nvendor_details=vendor_details # vendor's details for authentication and verification \n)\n
algobulls_connection.realtrade(\nstrategy=strategy_code, # strategy code\nstart='09:15 +0530', # start time of strategy (HH:MM z) \nend='15:30 +0530', # end time of strategy (HH:MM z)\ninstruments='NSE:SBIN', # name of the instrument\nlots=1, # number of lots per trade\nparameters=parameters, # parameters required for the strategy\ncandle='15 minutes', # candle size eg : '1 Day', '1 hour', '3 minutes'\nbroking_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 Tradingalgobulls_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 Tradingalgobulls_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
auto_update
= True): will show progress bar and update the latest logs as the strategy is executedauto_update
= False): will fetch logs only till the point where strategy is currently executing.(It wont update the latest logs, unless called manually again)Click on each of the tabs to see the relevant code snippet.
BacktestingPaper TradingReal Tradinglogs = algobulls_connection.get_backtesting_logs(\nstrategy_code, # strategy code \nauto_update=True, # (default=True)update the logs and show your strategy progress. If False, will only fetch logs from start to the current stage of execution\ndisplay_logs_in_auto_update_mode=True # only if auto_update is also True, will print logs as the progress is tracked\n)\nprint(logs)\n
logs = algobulls_connection.get_papertrading_logs(\nstrategy_code, # strategy code \nauto_update=True, # (default=True)update the logs and show your strategy progress. If False, will only fetch logs from start to the current stage of execution\ndisplay_logs_in_auto_update_mode=True # only if auto_update is also True, will print logs as the progress is tracked\n)\nprint(logs)\n
logs = algobulls_connection.get_realtrading_logs(\nstrategy_code, # strategy code \nauto_update=True, # (default=True)update the logs and show your strategy progress. If False, will only fetch logs from start to the current stage of execution\ndisplay_logs_in_auto_update_mode=True # only if auto_update is also True, will print logs as the progress is tracked\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 Tradingalgobulls_connection.get_backtesting_report_pnl_table(\nstrategy_code, # strategy code\nshow_all_rows=True, # default=True \nforce_fetch=True, # pnl data is saved locally once fetched, to update the locally fetched data, make this parameter True\ncountry='USA', # country of the exchange that was used while starting the job ('India' or 'USA')\n)\n
algobulls_connection.get_papertrading_report_pnl_table(\nstrategy_code, # strategy code\nshow_all_rows=True, # default=True \nforce_fetch=True, # pnl data is saved locally once fetched, to update the locally fetched data, make this parameter True\ncountry='USA', # country of the exchange that was used while starting the job ('India' or 'USA')\n)\n
algobulls_connection.get_realtrading_report_pnl_table(\nstrategy_code, # strategy code\nshow_all_rows=True, # default=True \nforce_fetch=True, # pnl data is saved locally once fetched, to update the locally fetched data, make this parameter True\ncountry='USA', # country of the exchange that was used while starting the job ('India' or 'USA')\n)\n
"},{"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 Tradingalgobulls_connection.get_backtesting_report_statistics(\nstrategy_code, # strategy code\nmode='quantstats', # package used to generate statistics\nreport='full', # format of the report\nhtml_dump=True # save report as html file\n)\n
algobulls_connection.get_papertrading_report_statistics(\nstrategy_code, # strategy code\nmode='quantstats', # package used to generate statistics\nreport='full', # format of the report\nhtml_dump=True # save report as html file\n)\n
algobulls_connection.get_realtrading_report_statistics(\nstrategy_code, # strategy code\nmode='quantstats', # package used to generate statistics\nreport='full', # format of the report\nhtml_dump=True # save report as html file\n)\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 Tradingorder_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
You can now explore more by creating and uploading more complex strategies.
You can also check out the Analytics, to understand more about the returns and analyze your strategy based on the analytics report.
"},{"location":"pyalgotrad/upload/","title":"Upload your Strategy","text":""},{"location":"pyalgotrad/upload/#previously","title":"Previously...","text":"You have created a strategy by:
OR
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":"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
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
StrategyOptionsEMACrossover(StrategyOptionsBaseV2)\n
Coding Conventions
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
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:
self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
_order
is the order object stored inside the OrderTagManager
for the tags base_inst_str
and entry_key
.eg:
self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
OrderTagManager
for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER
and entry_key
OrderTagManager
along with the orders related stored in that tageg:
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":"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
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.
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.
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.
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.
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
StrategyFuturesEMACrossover(StrategyBase)\n
Coding Conventions
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
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.
"},{"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:
self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
_order
is the order object stored inside the OrderTagManager
for the tags base_inst_str
and entry_key
.self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
OrderTagManager
for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER
and entry_key
OrderTagManager
along with the orders related stored in that tag eg: self.order_tag_manager.remove_tags(tags=entry_key)\n
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":"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":"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
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.
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.
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
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
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":"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":"Click on the Save button to save your key and model and establish the connection.
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":"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.
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":"strategy_parameters
inside your strategy class' constructor method.Once Strategy and User Parameters are configured, you can follow these steps to execute your strategy.
"},{"location":"python_build/python-build-config-parameters/#follow-these-simple-steps-to-test-the-strategys-performance","title":"Follow these simple steps to test the strategy's performance","text":"Step 1
After clicking Save & Start, a pop-up window will appear.
Step 2
In the customizations section, choose Backtesting to backtest or Paper Trading to Paper Trade a strategy.
Select the duration option in the customizations section. Add the desired date and time, as well as the quantity/lots. In Backtesting, you will need to put the start date and end date along with time.
In Paper Trading, you only need to add the start and end time.
Step 3
In the Strategy Configuration section, you can check the parameters added or modified by you.
Step 4
To begin testing the strategy, click on Execute.
Step 5
Go to the Analytics section to see the returns and performance of the strategy visualized.
Note:
The use of Paper Trading would be available from Monday - Friday (excluding exchange's holidays) from 9 AM to 16:00 PM. You can code your strategy & analyze the strategy results 24x7.
Go to the Logs section to see the step-by-step execution of the strategy in logs.
You can rename a strategy by clicking the edit symbol beside the strategy name.
"},{"location":"python_build/python-build-getstarted/","title":"Setup your Workspace","text":""},{"location":"python_build/python-build-getstarted/#how-to-get-started-with-python-build","title":"How to get started with Python Build?","text":"To start developing your own strategy, you must first activate a plan from the Pricing section. Select the Developers tab in the Pricing section and select a plan of your choice. There is currently one developer plan available:
After selecting your plan, you will be able to begin coding. You can either edit the preloaded Ready templates or use the My Coded Strategies section to create your own strategies.
"},{"location":"python_build/python-build-introduction/","title":"Python Build Web","text":""},{"location":"python_build/python-build-introduction/#introduction","title":"Introduction","text":"Now you can code your own strategy easily using our Python Build service! Begin coding your own strategy from scratch, or modify some of our ready-made templates to suit your needs. Get access to our state-of-the-art AlgoBulls Core Trading Engine, which automatically leverages our infrastructure so that you can access the latest historical data to gauge the performance of your strategies. Tweak the various parameters of your strategy to choose the ideal instrument, indicator values, and profit loss percentages as per your needs! View the performance of your strategy using our visual analytics feature and continue to tweak until you are satisfied with the performance. Get your strategy approved for live trading from our experts and deploy it on 30+ supported brokers without coding any broker integration logic.
Select Python Build from the navigation bar on the left to know more.
"},{"location":"python_build/python-build-introduction/#an-overview","title":"An overview","text":"Running Strategies: This section shows how many strategies are currently active and running in your account.
Strategies Saved: This displays the number of strategies saved in your AlgoBulls account. It also shows the number of maximum strategies that you can save as per your current plan.
Execution Time Consumed: You can view the number of minutes that have been used for Backtesting or Paper Trading your strategies.
Note:
Paper Trading would be available from Monday - Friday (excluding NSE/NASDAQ holidays) within the trading time of that particular exchange. You can code your strategy, execute on Backtesting mode or analyse the strategy results 24x7.
Analytics Support: This shows whether your analytics support is active. Analytics support is not available to free plan users.
Professional Support: This section connects you to other professional support forums for additional support while developing the strategy.
Active Plan: This section displays the current plan active on your AlgoBulls account.
Ready Templates: Ready-to-use templates that you can modify and test.
My Coded Strategies: Strategies that have been coded and saved by you are displayed here. This includes new and modified strategies developed by you.
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:
Click on \"Professional Support\" - Look for the \"Professional Support\" button on the Python Build Web splash and click on it to get started.
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%.\"
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.
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.
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
StrategyOptionsEMACrossover(StrategyOptionsBaseV2)\n
Coding Conventions
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
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:
self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
_order
is the order object stored inside the OrderTagManager
for the tags base_inst_str
and entry_key
.eg:
self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
OrderTagManager
for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER
and entry_key
OrderTagManager
along with the orders related stored in that tageg:
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":"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
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.
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.
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.
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.
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
StrategyFuturesEMACrossover(StrategyBase)\n
Coding Conventions
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
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.
"},{"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:
self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
_order
is the order object stored inside the OrderTagManager
for the tags base_inst_str
and entry_key
.self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
OrderTagManager
for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER
and entry_key
OrderTagManager
along with the orders related stored in that tag eg: self.order_tag_manager.remove_tags(tags=entry_key)\n
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":"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":"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
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.
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.
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
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
Once you create your own strategy or use a ready strategy from the pyalgostrategypool package, this is how it works internally on the AlgoBulls Core Trading Engine.
"},{"location":"strategies/aroon_crossover/","title":"Aroon Crossover","text":"This is a trading strategy called \"Aroon Crossover\" implemented in Python using the PyAlgoTrading library. The strategy is based on the Aroon indicator crossover.
Links
Jupyter Notebooks for Indian Exchange (NSE)
Jupyter Notebook for US Exchange (NASDAQ)
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.
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.
This is a trading strategy called \"Bollinger Bands\" implemented in Python using the PyAlgoTrading library. The strategy is based on the bollinger bands indicator values.
Links
Jupyter Notebooks for Indian Exchange (NSE)
Jupyter Notebook for US Exchange (NASDAQ)
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:
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.
This is a trading strategy called \"EMA Regular Order Strategy\" implemented in Python using the PyAlgoTrading library. The strategy is based on the exponential moving average crossover.
Links
Jupyter Notebooks for Indian Exchange (NSE)
Jupyter Notebook for US Exchange (NASDAQ)
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:
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).
This is a trading strategy called \"Inverse EMA Scalping Regular Order Strategy\" implemented in Python using the PyAlgoTrading library. The strategy is based on the exponential moving average crossover.
Links
Jupyter Notebooks for Indian Exchange (NSE)
Jupyter Notebooks for US Exchange (NASDAQ)
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:
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).
This class implements the Options Bear Call Ladder strategy.
Links
Jupyter Notebook for Options from Indian Exchange (NSE)
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:
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.
This is a template for the Options Bear Put Ladder strategy. The strategy involves the combination of buying and selling put options to profit from a downward price movement in the underlying asset. It utilizes multiple legs with different strike prices and transaction types to create a ladder-like structure.
Links
Jupyter Notebook for Options from Indian Exchange (NSE)
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:
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.
Links
Jupyter Notebook for Options from Indian Exchange (NSE)
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:
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.
Links
Jupyter Notebook for Options from Indian Exchange (NSE)
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:
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.
The __init__
method initializes the strategy and accepts parameters for configuring the strategy. The parameters are:
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
This is a template for implementing the Options Long Iron Butterfly strategy in Python.
Links
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:
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.
The strategy accepts the following parameters:
Name Default Value Expected Value Description LEG_ONE_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_ONE_TRADING_SYMBOL_SUFFIX 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_ONE_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_ONE_NUMBER_OF_STRIKES 0 greater than 0 Number of strikes for leg one. LEG_TWO_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_TWO_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_TWO_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_TWO_NUMBER_OF_STRIKES 0 greater than 0 Number of strikes for leg one. LEG_THREE_TRANSACTION_TYPE 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_THREE_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_THREE_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_THREE_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one. LEG_FOUR_TRANSACTION_TYPE 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_FOUR_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_FOUR_STRIKE_DIRECTION 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_FOUR_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one."},{"location":"strategies/options_straddle/","title":"Options Straddle","text":""},{"location":"strategies/options_straddle/#options-straddle","title":"Options Straddle","text":"This class represents the implementation of an options straddle trading strategy.
Links
Jupyter Notebook for Options from Indian Exchange (NSE)
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.
The StrategyOptionsStrangle
class is a strategy template for trading options strangles. It is derived from the StrategyOptionsBaseV2
class.
Links
Jupyter Notebook for Options from Indian Exchange (NSE)
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.
The following parameters can be set in the Parameters Configuration Pane:
Name Default Value Expected Value Description _leg_one_transaction_type 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] _leg_one_tradingsymbol_suffix 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] _leg_one_strike_direction 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] _leg_one_number_of_strikes 2 greater than 0 Number of strikes for leg one. _leg_two_transaction_type 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] _leg_two_tradingsymbol_suffix 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] _leg_two_strike_direction 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] _leg_two_number_of_strikes 2 greater than 0 Number of strikes for leg one."},{"location":"strategies/reverse_rsi/","title":"Reverse RSI","text":"This is a trading strategy called \"Reverse RSI\" implemented in Python using the PyAlgoTrading library. The strategy is based on the relative strength index indicator.
Links
Jupyter Notebook for Indian Exchange (NSE)
Jupyter Notebook for US Exchange (NASDAQ)
RSI stands for Relative Strength Index, and it is a popular technical indicator used in the stock market to analyze the strength and momentum of a price trend. The RSI provides insights into whether a stock is overbought or oversold and can help identify potential trend reversals.
Here is a summary of RSI in the stock market:
Overall, the Relative Strength Index (RSI) is a widely used indicator in the stock market to assess the strength and momentum of price movements. It helps traders identify overbought and oversold conditions, as well as potential trend reversals, which can assist in making trading decisions.
Fig.1 - MCD candle chart (top) and RSI plot (bottom)"},{"location":"strategies/reverse_rsi/#strategy-overview","title":"Strategy Overview","text":"The Reverse RSI strategy is a trading strategy based on the Relative Strength Index (RSI) indicator. It generates entry and exit signals based on the reverse crossover of the RSI values from specified overbought and oversold levels.
"},{"location":"strategies/reverse_rsi/#strategy-parameters","title":"Strategy Parameters","text":"The following parameters can be configured for the strategy:
Name Default Value Expected Value Description TIME_PERIOD None greater than 0 Period (number of candles) by which RSI is calculated OVERBOUGHT_VALUE None greater than 0 RSI value above which stocks are considered over-bought OVERSOLD_VALUE None greater than 0 RSI value below which stocks are considered over-sold"},{"location":"strategies/reverse_rsi/#crossover-calculation","title":"Crossover Calculation","text":"The get_crossover_value
method calculates the crossover values for the RSI indicator using historical data of the instrument. It compares the RSI values with the overbought and oversold levels to determine the entry and exit actions. The method returns the crossover values for oversold and overbought levels.
This is a trading strategy called \"Stochastic Crossover\" implemented in Python using the PyAlgoTrading library. The strategy is based on the Stochastic indicator crossover.
Links
Jupyter Notebook for Indian Exchange (NSE)
Jupyter Notebook for US Exchange (NASDAQ)
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 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.
This is a trading strategy called \"VWAP Crossover\" implemented in Python using the PyAlgoTrading library. The strategy is based on the crossover of the VWAP (Volume Weighted Average Price) indicator.
Links
Jupyter Notebook for Indian Exchange (NSE)
Jupyter Notebook for US Exchange (NASDAQ)
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:
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.
Links
StrategyOptionsEMACrossover(StrategyOptionsBaseV2)\n
Coding Conventions
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
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:
self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
_order
is the order object stored inside the OrderTagManager
for the tags base_inst_str
and entry_key
.eg:
self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
OrderTagManager
for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER
and entry_key
OrderTagManager
along with the orders related stored in that tageg:
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":"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
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.
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.
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.
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.
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
StrategyFuturesEMACrossover(StrategyBase)\n
Coding Conventions
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
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.
"},{"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:
self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
_order
is the order object stored inside the OrderTagManager
for the tags base_inst_str
and entry_key
.self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
OrderTagManager
for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER
and entry_key
OrderTagManager
along with the orders related stored in that tag eg: self.order_tag_manager.remove_tags(tags=entry_key)\n
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":"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":"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
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.
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.
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). Inside the strategy class there are many methods that could be divided into 4 different sections: Initialization Methods, Algorithmic Calculation Methods, 4-Core Loop Methods, Miscellaneous Methods. These 4 sections are explained briefly below.
"},{"location":"strategies/strategy_guides/common_strategy_guide/#initialization-methods","title":"Initialization Methods","text":"In this section, you will have the Strategy Class\u2019s \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/#algorithmic-calculations-methods","title":"Algorithmic Calculations Methods","text":"This section will majorly contain the methods that are defined by the user. Their main purpose will be to perform operations on historical 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/#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/#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":""},{"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:
RegularOptionsclass MovingAverageCrossoverV2(StrategyBase):\nname = 'Moving Average Crossover V2'\n
class StrategyOptionsBearCallLadder(StrategyOptionsBaseV2):\nname = '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.
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):\nsuper().__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.
RegularOptionsclass StrategyEMARegularOrder(StrategyBase):\nname = 'EMA Regular Order Strategy'\ndef __init__(self, *args, **kwargs):\nsuper().__init__(*args, **kwargs)\nself.timeperiod1 = self.strategy_parameters['TIMEPERIOD1']\nself.timeperiod2 = self.strategy_parameters['TIMEPERIOD2']\nself.main_order_map = None\n
class StrategyOptionsBearCallLadder(StrategyOptionsBaseV2):\nname = 'Options Bear Call Ladder Template'\ndef __init__(self, *args, **kwargs):\nsuper().__init__(*args, **kwargs)\n# Parameters (currently set with default values, can be overridden from the Parameters Configuration Pane)\nself._leg_one_transaction_type = self.strategy_parameters.get('LEG_ONE_TRANSACTION_TYPE', 1) # BUY: 1 | SELL: 2\nself._leg_one_tradingsymbol_suffix = self.strategy_parameters.get('LEG_ONE_TRADING_SYMBOL_SUFFIX', 1) # CE: 1 | PE: 2\nself._leg_one_strike_direction = self.strategy_parameters.get('LEG_ONE_STRIKE_DIRECTION', 1) # ITM: 0| ATM: 1| OTM: 2\nself._leg_one_number_of_strikes = self.strategy_parameters.get('LEG_ONE_NUMBER_OF_STRIKES', 0)\nself._leg_two_transaction_type = self.strategy_parameters.get('LEG_TWO_TRANSACTION_TYPE', 1) # BUY: 1 | SELL: 2\nself._leg_two_tradingsymbol_suffix = self.strategy_parameters.get('LEG_TWO_TRADING_SYMBOL_SUFFIX', 1) # CE: 1 | PE: 2\nself._leg_two_strike_direction = self.strategy_parameters.get('LEG_TWO_STRIKE_DIRECTION', 2) # ITM: 0| ATM: 1| OTM: 2\nself._leg_two_number_of_strikes = self.strategy_parameters.get('LEG_TWO_NUMBER_OF_STRIKES', 2)\nself._leg_three_transaction_type = self.strategy_parameters.get('LEG_THREE_TRANSACTION_TYPE', 2) # BUY: 1 | SELL: 2\nself._leg_three_tradingsymbol_suffix = self.strategy_parameters.get('LEG_THREE_TRADING_SYMBOL_SUFFIX', 1) # CE: 1 | PE: 2\nself._leg_three_strike_direction = self.strategy_parameters.get('LEG_THREE_STRIKE_DIRECTION', 0) # ITM: 0| ATM: 1| OTM: 2\nself._leg_three_number_of_strikes = self.strategy_parameters.get('LEG_THREE_NUMBER_OF_STRIKES', 2)\n# Maps\nself.transaction_type_map = {1: \"BUY\", 2: \"SELL\"}\nself.tradingsymbol_suffix_map = {1: \"CE\", 2: \"PE\"}\nself.strike_direction_map = {0: OptionsStrikeDirection.ITM, 1: OptionsStrikeDirection.ATM, 2: OptionsStrikeDirection.OTM}\n# Variables\nself.number_of_allowed_expiry_dates = 1\nself.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:
RegularOptionsdef initialize(self):\nself.main_order_map = {}\n
def initialize(self):\nsuper().initialize()\nself.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:
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.hist_data[\u2018<column_name>\u2019]\n
Example: close = hist_data[\u2018close\u2019]\n
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. Next, you analyze this 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. 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 directionBy 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):\nhist_data = self.get_historical_data(instrument)\nrsi_value = talib.RSI(hist_data['close'], timeperiod=self.time_period)\noversold_list = [self.oversold_value] * rsi_value.size\noverbought_list = [self.overbought_value] * rsi_value.size\noversold_crossover_value = self.utils.crossover(rsi_value, oversold_list)\noverbought_crossover_value = self.utils.crossover(rsi_value, overbought_list)\nreturn oversold_crossover_value, overbought_crossover_value\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#miscellaneous-functions","title":"Miscellaneous Functions","text":""},{"location":"strategies/strategy_guides/common_strategy_guide/#get_child_instrument_details","title":"get_child_instrument_details()","text":"The get_child_instrument_details function is at your disposal. It takes several parameters:
This function calls two other functions: self.get_allowed_expiry_dates()
and get_options_instrument_with_strike_direction()
.
Example: This is how the function looks ideally. This example was taken from \u201cOptions Bear Call Strategy\u201d from ready templates.
def get_child_instrument_details(self, base_instrument, tradingsymbol_suffix, strike_direction, no_of_strikes):\nexpiry_date = self.get_allowed_expiry_dates()[0]\nchild_instrument = self.get_options_instrument_with_strike_direction(base_instrument, expiry_date, tradingsymbol_suffix, strike_direction, no_of_strikes)\nreturn child_instrument\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#get_allowed_expiry_dates","title":"get_allowed_expiry_dates()","text":"In options strategies, the get_allowed_expiry_dates function plays a vital role. It doesn't require parameters; instead, it relies on the number_of_allowed_expiry_dates variable defined in the constructor method.
In essence, this function helps you select the appropriate expiry date based on the value you assign to number_of_allowed_expiry_dates
variable.
This function is a key player in options strategies, taking parameters such as:
Now, let's talk about a crucial piece of the options strategy puzzle \u2013 options_instruments_set_up_local
. This function creates local instances of all available child instruments based on specified parameters:
Once executed, this function sets up and stores local instances of child instruments matching your criteria. These instances become valuable assets for further analysis or operations, including utilising the \"get_child_instrument_details\" function.
Example: This is how this function looks ideally. This example was taken from \u201cOptions Bear Call Ladder\u201d from ready templates.
def options_instruments_set_up_local(self, base_instrument, tradingsymbol_suffix, current_close, direction=OptionsInstrumentDirection.EXACT):\nexpiry_dates = self.get_allowed_expiry_dates()\nfor expiry_date in expiry_dates:\nself.options_instruments_set_up(base_instrument, direction, expiry_date, tradingsymbol_suffix, current_close)\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#options_instruments_set_up","title":"options_instruments_set_up()","text":"The final piece of the puzzle is \"options_instruments_set_up.\" This function takes parameters like:
Now, let's talk about the engine that drives your strategy \u2013 the core loop functions.
These include \"strategy_select_instruments_for_entry\", \"strategy_enter_position\", \"strategy_select_instruments_for_exit\" and \"strategy_exit_position\" These functions are called within a loop from the AlgoBulls core until an Exit Event for the strategy occurs.
"},{"location":"strategies/strategy_guides/common_strategy_guide/#the-4-core-loop-functions","title":"The 4 Core Loop Functions","text":""},{"location":"strategies/strategy_guides/common_strategy_guide/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry()","text":"This function takes parameters:
Example: This function would ideally look like this. This example was taken from \u201cOptions Straddle\u201d from Ready Templates.
Examples:
RegularOptionsdef strategy_select_instruments_for_entry(self, candle, instruments_bucket):\nselected_instruments, meta = [], []\nfor instrument in instruments_bucket:\ncrossover = self.get_decision(instrument)\naction_constants = {1: 'BUY', -1: 'SELL'}\nif crossover in [-1, 1]:\nselected_instruments.append(instrument)\nmeta.append({'action': action_constants[crossover]})\nreturn selected_instruments, meta\n
def strategy_select_instruments_for_entry(self, candle, instruments_bucket):\nselected_instruments, meta = [], []\nfor instrument in instruments_bucket:\nif instrument not in self.instruments_done_for_the_day:\nself.instruments_done_for_the_day.append(instrument)\nltp = self.broker.get_ltp(instrument)\nself.options_instruments_set_up_local(instrument, \"CE\", ltp)\nself.options_instruments_set_up_local(instrument, \"PE\", ltp)\nleg_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)]\nfor leg_number, tradingingsymbol_suffix, strike_direction, number_of_strikes, transaction_type in leg_wise_list:\nself.logger.info(f'Processing {leg_number}...')\nchild_instrument = self.get_child_instrument_details(instrument, self.tradingsymbol_suffix_map[tradingingsymbol_suffix], self.strike_direction_map[strike_direction], number_of_strikes)\nselected_instruments.append(child_instrument)\nmeta.append({'base_instrument': instrument, 'action': self.transaction_type_map[transaction_type]})\nreturn selected_instruments, meta\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#strategy_enter_position","title":"strategy_enter_position()","text":"This function takes parameters:
Here, you place orders for the selected instruments, updating them in \"self.main_order\" for easy access in exit functions.
Example: This function would ideally look like this. This example was taken from \u201cOptions Straddle\u201d from Ready Templates.
Examples:
RegularOptionsdef strategy_enter_position(self, candle, instrument, meta):\nself.main_order_map[instrument] = _ = self.broker.OrderRegular(instrument, meta['action'], quantity=self.number_of_lots * instrument.lot_size)\nreturn _\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)\nreturn _\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit()","text":"Similar to entry, this function takes parameters:
The function iterates through the instrument bucket, checking if the instrument is present in \"self.main_order\" and whether its exit condition is satisfied. Instruments meeting exit conditions are added to the selected instruments list, along with their respective actions and meta-information.
Example: This function should ideally look like this. This example was taken from \u201cEMA Crossover Strategy\u201d.
def strategy_select_instruments_for_exit(self, candle, instruments_bucket):\nselected_instruments, meta = [], []\nfor instrument in instruments_bucket:\nif self.main_order_map.get(instrument) is not None:\ncrossover = self.get_decision(instrument)\nif crossover in [1, -1]:\nselected_instruments.append(instrument)\nmeta.append({'action': 'EXIT'})\nreturn selected_instruments, meta\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#strategy_exit_position","title":"strategy_exit_position()","text":"Finally, this function takes parameters:
Here, you place orders for the selected instruments, removing them from \"self.main_order\" to prepare for the next iteration of the AlgoBulls core loop.
Example: This function should ideally look like this. This example was taken from \u201cEMA Crossover Strategy\u201d.
def strategy_exit_position(self, candle, instrument, meta):\nif meta['action'] == 'EXIT':\nself.main_order_map[instrument].exit_position()\nself.main_order_map[instrument] = None\nreturn True\nreturn False\n
"},{"location":"strategies/strategy_guides/structure/","title":"Code Structure of Strategy","text":"Coding Prerequisites
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
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.
"}]} \ 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:
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.
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.
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:
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:
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.
Algorithmic Trading: Alpaca's platform is tailored for algorithmic trading strategies, where traders can automate trading decisions based on predefined conditions and rules.
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.
Market Data: The platform offers access to real-time and historical market data, which is crucial for building and testing trading strategies.
Order Execution: Traders can use Alpaca's API to execute trades on supported exchanges. This includes submitting market, limit, and stop orders.
Customizable Dashboards: Alpaca provides customizable dashboards and interfaces to monitor trading activity and portfolio performance.
Brokerage Services: Alpaca acts as a brokerage, providing services that allow traders to execute their strategies on supported exchanges.
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/#how-to-get-api-keys-for-trading-in-alpaca","title":"How to get API-keys for trading in Alpaca ?","text":""},{"location":"brokers/broker_alpaca_guide/#create-or-login-to-alpaca-account","title":"Create or Login to Alpaca Account","text":""},{"location":"brokers/broker_alpaca_guide/#go-to-home-page-of-your-account","title":"Go to Home Page of your Account","text":""},{"location":"brokers/broker_alpaca_guide/#view-api-keys-or-generate-api-keys","title":"View API keys or Generate API keys","text":""},{"location":"brokers/broker_alpaca_guide/#get-the-secret-key-and-api-key","title":"Get theSecret-Key
and API key
","text":""},{"location":"brokers/broker_alpaca_guide/#why-do-we-need-alpaca-account","title":"Why do we need Alpaca Account ?","text":"If you want to run your strategy on American exchanges like NASDAQ or NYSE, you need access to the historical data as well as live data of all the stocks and that is provided by Alpaca. Besides this it will also be helpful to do live trading on AlgoBulls using these credentials.
"},{"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/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":"Execute Backtesting, Paper Trading, and Real Trading using 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":"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.
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.
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.
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.
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.
Reach out to AlgoBulls Support for any queries: If you encounter issues during the tutorial, contact the AlgoBulls Support team for assistance.
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":"master
branch.You will need the following to start with Pyalgotrading:
"},{"location":"pyalgotrad/prerequisites/#algobulls-account","title":"AlgoBulls Account","text":"To upload and test your strategies, you will need this account. You can create your account for FREE on the Algobulls website.
"},{"location":"pyalgotrad/prerequisites/#developer-key","title":"Developer Key","text":"To access the features, you will need a developer key. The key can be obtained as follows:
Please Note
For security reasons, the developer key will get reset every time you log out from your AlgoBulls account.
Once you have the developer key, you can access the AlgoBulls platform using pyalgotrading
functions.
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
pip install
commandTo 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:
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):\nname = 'SMA Regular Order Strategy'\nsuper().__init__(*args, **kwargs)\nself.timeperiod_x = self.strategy_parameters['timeperiod1']\nself.timeperiod_y = self.strategy_parameters['timeperiod2']\nself.main_order = None\n
The init
method does the following:
name
- variable which should store the name of your strategysuper()
- Calls the constructor of the superclass.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
.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.
def initialize()
","text":"def initialize(self):\nself.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
.
def name()
(optional)","text":"If the name
variable is defined in __init__()
, this function is not needed.
@staticmethod\ndef name():\nreturn '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():\nreturn AlgoBullsEngineVersion.VERSION_3_2_0\n
Mark both the above methods as @staticmethod
. The versions_supported
method does the following:
def strategy_select_instruments_for_entry()
","text":"def strategy_select_instruments_for_entry(self, candle, instruments_bucket):\ninstruments = []\nmeta = []\nfor instrument in instruments_bucket:\ncrossover_value = self.get_crossover_value(instrument)\nif crossover_value == 1:\ninstruments.append(instrument)\nmeta.append({'action': 'BUY'})\nelif crossover_value == -1:\nif self.strategy_mode is StrategyMode.INTRADAY:\ninstruments.append(instrument)\nmeta.append({'action': 'SELL'})\nreturn instruments, meta\n
The strategy_select_instruments_for_entry
method does the following:
instruments
and meta
- Creates 2 empty lists that will be used to pass the selected instruments and additional information about them respectively.crossover_value
- The crossover value is calculated and stored here. Crossover values are interpreted as:instruments
, and the associated action (BUY/SELL) is appended to the meta
.instruments
and meta
- Both the lists (whether populated or empty) are returned to the platform for further actions.Note
elif
part.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.meta
. The Entry position will be taken in the next method below.meta
contains a very versatile dictionary object. You may use it to pass any other additional information that you wish. def strategy_enter_position()
","text":"def strategy_enter_position(self, candle, instrument, sideband_info):\nif sideband_info['action'] == 'BUY':\nqty = self.number_of_lots * instrument.lot_size\nself.main_order[instrument] = \\\n self.broker.BuyOrderRegular(instrument=instrument,\norder_code=BrokerOrderCodeConstants.INTRADAY,\norder_variety=BrokerOrderVarietyConstants.MARKET,\nquantity=qty)\nelif sideband_info['action'] == 'SELL':\nqty = self.number_of_lots * instrument.lot_size\nself.main_order[instrument] = \\\n self.broker.SellOrderRegular(instrument=instrument,\norder_code=BrokerOrderCodeConstants.INTRADAY,\norder_variety=BrokerOrderVarietyConstants.MARKET,\nquantity=qty)\nelse:\nraise SystemExit(f'Got invalid sideband_info value: {sideband_info}')\nreturn self.main_order[instrument]\n
"},{"location":"pyalgotrad/programexample/#or","title":"or","text":"def strategy_enter_position(self, candle, instrument, meta):\nself.main_order_map[instrument] = _ = self.broker.OrderRegular(\nintrument=instrument, \norder_transaction_type=meta['action'], # 'BUY' or 'SELL'\nquantity=self.number_of_lots * instrument.lot_size, # number of lots (int)\nprice=None,\ntrigger_price=None\n)\nreturn _\n
The strategy_enter_position
method does the following:
sideband_info
and perform the required action (BUY/SELL).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.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.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,\norder_code=BrokerOrderCodeConstants.INTRADAY,\norder_variety=BrokerOrderVarietyConstants.LIMIT,\nquantity=qty,\nprice=ltp,\nstoploss_trigger=ltp - (ltp * self.stoploss),\ntarget_trigger=ltp + (ltp * self.target),\ntrailing_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
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.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). def strategy_select_instruments_for_exit()
","text":"def strategy_select_instruments_for_exit(self, candle, instruments_bucket):\ninstruments = []\nmeta = []\nfor instrument in instruments_bucket:\nif self.main_order.get(instrument) is not None:\ncrossover_value = self.get_crossover_value(instrument)\nif crossover_value in [1, -1]:\ninstruments.append(instrument)\nmeta.append({'action': 'EXIT'})\nreturn instruments, meta\n
The strategy_select_instruments_for_exit
method does the following:
instruments
and meta
- Creates 2 empty lists that will be used to pass the selected instruments and additional information about them respectively.self.main_order
object is None
or not, and proceed only if it is not None
. crossover_value
- The crossover value is calculated and stored here. Crossover values are interpreted as:instruments
, and the associated action (EXIT) is appended to the meta
.instruments
and meta
- Both the lists (whether populated or empty) are returned to the platform for further actions.Note
meta
. The Exit position will be taken in the next method below.meta
contains a very versatile dictionary object. You may use it to pass any other additional information that you wish.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. def strategy_exit_position()
","text":"def strategy_exit_position(self, candle, instrument, sideband_info):\nif sideband_info['action'] == 'EXIT':\nself.main_order[instrument].exit_position()\nself.main_order[instrument] = None\nreturn True\nreturn False\n
The strategy_exit_position
method does the following:
sideband_info
.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.self.main_order
- set it to None
, as the order has been exited and no longer holds anything.True
to the platform if the exit steps were performed, else return False
.def get_crossover_value()
","text":"def get_crossover_value(self, instrument):\nhist_data = self.get_historical_data(instrument)\nsma_x = talib.SMA(hist_data['close'], timeperiod=self.timeperiod_x)\nsma_y = talib.SMA(hist_data['close'], timeperiod=self.timeperiod_y)\ncrossover_value = self.utils.crossover(sma_x, sma_y)\nreturn crossover_value\n
The get_crossover_value
method does the following:
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 measuredvolume
- the volume of that instrumentopen
, high
, low
and close
- the OHLC values of the instrumentoi
- the Open Interest of that instrumentsma_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']
.crossover_value
- calculates the crossover value using the crossover
method from the utils
package.Note
crossover
method of the utils
package is very important.crossover
function, the answer you will get is -1 (Cut downwards).crossover
function, thus making the order of parameters passed an important point to be aware of, while coding the strategy.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":"Once you start the strategy, it may take a while for it to complete the execution. You can switch to the Analytics tab after you run your strategy. Even if the strategy execution is not complete, you will still see intermediate results.
Analytics: In the analytics section, you can view a strategy\u2019s Stats & various other metrics in the form of graphs like P&L.
"},{"location":"pyalgotrad/python-build-view-results/#stats","title":"Stats","text":"In this section you can see the total returns, sharpe ratio, sortino ratio, volatility, Max Drawdown, Total wins or Loses, Total short or long trades, hit ratio, number of trades, average trades per day, max profit, max loss, average profit per winning trade, average loss per losing trade.
"},{"location":"pyalgotrad/python-build-view-results/#cumulative-returns","title":"Cumulative Returns","text":""},{"location":"pyalgotrad/python-build-view-results/#profit-loss-currency-or","title":"Profit & Loss (Currency or %)","text":"The trade by trade P&L in Currency or Percentage.
"},{"location":"pyalgotrad/python-build-view-results/#end-of-year-returns-plot","title":"End of Year Returns Plot (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#monthly-returns-histogram","title":"Monthly Returns Histogram (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#monthly-returns-heatmap","title":"Monthly Returns Heatmap (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#daily-returns","title":"Daily Returns (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#underwater-drawdown-plot","title":"Underwater Drawdown Plot (%)","text":""},{"location":"pyalgotrad/python-build-view-results/#pl-book","title":"P&L Book","text":"View detailed trade by trade report. Premium users can analyze this data in the form of heatmaps for Gross Profit & Loss, Trading Volume & Total number of Trades.
"},{"location":"pyalgotrad/python-build-view-results/#user-log","title":"User Log","text":"Real-time logs from strategy execution are displayed in this section. Use these logs to debug your strategy\u2019s behavior and performance.
"},{"location":"pyalgotrad/python-build-view-results/#order-history","title":"Order History","text":"View the order state transition for every order placed by your strategy in-depth.
"},{"location":"pyalgotrad/select/","title":"Select your Strategy","text":""},{"location":"pyalgotrad/select/#previously","title":"Previously...","text":"You have uploaded or saved a strategy by:
OR
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":"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
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":"strategy name
. Make sure you have the strategy with given name in your AlgoBulls Account. strategy_name = 'Exponential Moving Averages Crossover'\nstrategy_code, strategy_name = all_strategies_df.loc[all_strategies_df['strategyName'] == strategy_name].iloc[0] \n
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
You are now ready to test your uploaded strategy and perform Backtesting, Paper Trading and/or Real Trading with it.
"},{"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:
Open a Jupyter Notebook.
The steps you will follow are:
Run the following code snippets into the Jupyter Notebook one by one (or all together).
"},{"location":"pyalgotrad/testing/#create-a-new-strategy-file","title":"Create a new strategy file","text":"eg: strategy_<unique_code_if_needed>
_options_ema_crossover.py Make sure this strategy file is in the same folder as the jupyter notebook.
Coding Conventions
How to Code ?
To know more on how to code trading strategies and understand their format, click here. We have in detail explanation for regular strategies as well as options strategies
"},{"location":"pyalgotrad/testing/#import-statements","title":"Import statements","text":"from pyalgotrading.algobulls import AlgoBullsConnection\nfrom datetime import datetime as dt\nfrom pyalgotrading.constants import *\n
"},{"location":"pyalgotrad/testing/#establish-a-connection-to-the-algobulls-platform","title":"Establish a connection to the AlgoBulls Platform","text":"algobulls_connection = AlgoBullsConnection()\nalgobulls_connection.get_authorization_url()\n
The output of the above step is: Please login to this URL with your AlgoBulls credentials and get your developer access token: https://app.algobulls.com/user/login
Get Developer Key
You will need to log in to your AlgoBulls account and fetch the access token from: (See How) Settings -> General -> Developer Options
Once you have the access token, set it in the code as shown here:
algobulls_connection.set_access_token('4365817b795770ea31040a21ad29c8e78b63ad88')\n
Replace the token you have copied with the token in the code above.
"},{"location":"pyalgotrad/testing/#display-all-strategies-in-your-account","title":"Display all strategies in your account","text":"all_strategies = algobulls_connection.get_all_strategies()\nall_strategies\n
An example of the output will be:
"},{"location":"pyalgotrad/testing/#select-the-strategy","title":"Select the strategy","text":"Select the last entry of the strategyCode
column and display it.
strategy_code = all_strategies.iloc[-1]['strategyCode']\nstrategy_code\n
"},{"location":"pyalgotrad/testing/#print-your-strategy-code","title":"Print your Strategy code","text":"You can print your strategy code once to verify if this is the correct code. This step is optional.
strategy_details1 = algobulls_connection.get_strategy_details(strategy_code)\nprint(strategy_details1)\n
"},{"location":"pyalgotrad/testing/#search-for-instruments-based-on-a-search-query","title":"Search for instruments (based on a search query)","text":"Now display a few instruments with some keyword. The example below uses 'SBIN' as the keyword.
instruments = algobulls_connection.search_instrument('SBIN')\ninstruments\n
"},{"location":"pyalgotrad/testing/#select-an-instrument","title":"Select an instrument","text":"From the output, select the instrument on which you wish to test your strategy. For this example, select the first one.
instrument = instruments[0]['value']\ninstrument\n
"},{"location":"pyalgotrad/testing/#submit-a-job","title":"Submit a Job","text":"Delete previous trades
algobulls_connection.delete_previous_trades(strategy=strategy)\n
Set the parameters for the strategy
parameters={\n'timeperiod1': 5,\n'timeperiod2': 12\n}\n
vendor_details = {\n'brokerName': '<VENDOR_NAME>',\n'credentialParameters': {\n'api_key': '<API_KEY>',\n'secret_key': '<SECRET_KEY>'\n}\n}\n
broking_details = {\n'brokerName': '<BROKER_NAME>',\n'credentialParameters': {\n'user_id': '<USER_ID>',\n'api_key': '<API_KEY>',\n'password': '<PASSWORD>'\n}\n}\n
Click on each of the tabs to see the relevant code snippet.
BacktestingPaper TradingReal Tradingalgobulls_connection.backtest(\nstrategy=strategy_code, # strategy code\nstart='2020-7-1 09:15 +0530', # start date-time of strategy ('YYYY-MM-DD HH:MM z')\nend='2020-7-7 15:30 +0530', # end date-time of strategy ('YYYY-MM-DD HH:MM z')\ninstruments='NSE:SBIN', # name of the instrument\nlots=1, # number of lots per trade\nparameters=parameters, # parameters required for the strategy\ncandle='15 minutes', # candle size eg : '1 Day', '1 hour', '3 minutes'\ndelete_previous_trades=True, # delete the previous trades for papertrading (default is true),\ninitial_funds_virtual=10000, # virtual funds allotted before the paper trading starts (default is 1e9)\nvendor_details=vendor_details # vendor's details for authentication and verification \n)\n
algobulls_connection.papertrade(\nstrategy=strategy_code, # strategy code\nstart='09:15 +0530', # start time of strategy (HH:MM z) \nend='15:30 +0530', # end time of strategy (HH:MM z)\ninstruments='NSE:SBIN', # name of the instrument\nlots=1, # number of lots per trade\nparameters=parameters, # parameters required for the strategy\ncandle='15 minutes', # candle size eg : '1 Day', '1 hour', '3 minutes'\ndelete_previous_trades=True, # delete the previous trades for papertrading (default is true)\ninitial_funds_virtual=10000, # virtual funds allotted before the paper trading starts (default is 1e9)\nvendor_details=vendor_details # vendor's details for authentication and verification \n)\n
algobulls_connection.realtrade(\nstrategy=strategy_code, # strategy code\nstart='09:15 +0530', # start time of strategy (HH:MM z) \nend='15:30 +0530', # end time of strategy (HH:MM z)\ninstruments='NSE:SBIN', # name of the instrument\nlots=1, # number of lots per trade\nparameters=parameters, # parameters required for the strategy\ncandle='15 minutes', # candle size eg : '1 Day', '1 hour', '3 minutes'\nbroking_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 Tradingalgobulls_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 Tradingalgobulls_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
auto_update
= True): will show progress bar and update the latest logs as the strategy is executedauto_update
= False): will fetch logs only till the point where strategy is currently executing.(It wont update the latest logs, unless called manually again)Click on each of the tabs to see the relevant code snippet.
BacktestingPaper TradingReal Tradinglogs = algobulls_connection.get_backtesting_logs(\nstrategy_code, # strategy code \ndisplay_progress_bar=True, # (default=True) to track the execution on progress bar as your strategy is executed\nprint_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(\nstrategy_code, # strategy code \ndisplay_progress_bar=True, # (default=True) to track the execution on progress bar as your strategy is executed\nprint_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(\nstrategy_code, # strategy code \ndisplay_progress_bar=True, # (default=True) to track the execution on progress bar as your strategy is executed\nprint_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 Tradingalgobulls_connection.get_backtesting_report_pnl_table(\nstrategy_code, # strategy code\nshow_all_rows=True, # default=True \nforce_fetch=True, # pnl data is saved locally once fetched, to update the locally fetched data, make this parameter True\ncountry='USA', # country of the exchange that was used while starting the job ('India' or 'USA')\nbroker_commission_percentage: 1 # Percentage of broker commission per trade\nbroker_commission_price: 0.2 # Broker fee per trade\nslippage_percent: 3 # Slippage percentage value\n)\n
algobulls_connection.get_papertrading_report_pnl_table(\nstrategy_code, # strategy code\nshow_all_rows=True, # default=True \nforce_fetch=True, # pnl data is saved locally once fetched, to update the locally fetched data, make this parameter True\ncountry='USA', # country of the exchange that was used while starting the job ('India' or 'USA')\nbroker_commission_percentage: 1 # Percentage of broker commission per trade\nbroker_commission_price: 0.2 # Broker fee per trade\nslippage_percent: 3 # Slippage percentage value\n)\n
algobulls_connection.get_realtrading_report_pnl_table(\nstrategy_code, # strategy code\nshow_all_rows=True, # default=True \nforce_fetch=True, # pnl data is saved locally once fetched, to update the locally fetched data, make this parameter True\ncountry='USA', # country of the exchange that was used while starting the job ('India' or 'USA')\n)\n
"},{"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 Tradingalgobulls_connection.get_backtesting_report_statistics(\nstrategy_code, # strategy code\nreport='full', # format of the report\nhtml_dump=True # save report as html file\n)\n
algobulls_connection.get_papertrading_report_statistics(\nstrategy_code, # strategy code\nreport='full', # format of the report\nhtml_dump=True # save report as html file\n)\n
algobulls_connection.get_realtrading_report_statistics(\nstrategy_code, # strategy code\nreport='full', # format of the report\nhtml_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 Tradingorder_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
You can now explore more by creating and uploading more complex strategies.
You can also check out the Analytics, to understand more about the returns and analyze your strategy based on the analytics report.
"},{"location":"pyalgotrad/upload/","title":"Upload your Strategy","text":""},{"location":"pyalgotrad/upload/#previously","title":"Previously...","text":"You have created a strategy by:
OR
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":"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
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
StrategyOptionsEMACrossover(StrategyOptionsBaseV2)\n
Coding Conventions
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
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:
self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
_order
is the order object stored inside the OrderTagManager
for the tags base_inst_str
and entry_key
.eg:
self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
OrderTagManager
for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER
and entry_key
OrderTagManager
along with the orders related stored in that tageg:
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":"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
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.
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.
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.
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.
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
StrategyFuturesEMACrossover(StrategyBase)\n
Coding Conventions
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
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.
"},{"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:
self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
_order
is the order object stored inside the OrderTagManager
for the tags base_inst_str
and entry_key
.self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
OrderTagManager
for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER
and entry_key
OrderTagManager
along with the orders related stored in that tag eg: self.order_tag_manager.remove_tags(tags=entry_key)\n
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":"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":"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
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.
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.
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
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
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":"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":"Click on the Save button to save your key and model and establish the connection.
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":"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.
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":"strategy_parameters
inside your strategy class' constructor method.Once Strategy and User Parameters are configured, you can follow these steps to execute your strategy.
"},{"location":"python_build/python-build-config-parameters/#follow-these-simple-steps-to-test-the-strategys-performance","title":"Follow these simple steps to test the strategy's performance","text":"Step 1
After clicking Save & Start, a pop-up window will appear.
Step 2
In the customizations section, choose Backtesting to backtest or Paper Trading to Paper Trade a strategy.
Select the duration option in the customizations section. Add the desired date and time, as well as the quantity/lots. In Backtesting, you will need to put the start date and end date along with time.
In Paper Trading, you only need to add the start and end time.
Step 3
In the Strategy Configuration section, you can check the parameters added or modified by you.
Step 4
To begin testing the strategy, click on Execute.
Step 5
Go to the Analytics section to see the returns and performance of the strategy visualized.
Note:
The use of Paper Trading would be available from Monday - Friday (excluding exchange's holidays) from 9 AM to 16:00 PM. You can code your strategy & analyze the strategy results 24x7.
Go to the Logs section to see the step-by-step execution of the strategy in logs.
You can rename a strategy by clicking the edit symbol beside the strategy name.
"},{"location":"python_build/python-build-getstarted/","title":"Setup your Workspace","text":""},{"location":"python_build/python-build-getstarted/#how-to-get-started-with-python-build","title":"How to get started with Python Build?","text":"To start developing your own strategy, you must first activate a plan from the Pricing section. Select the Developers tab in the Pricing section and select a plan of your choice. There is currently one developer plan available:
After selecting your plan, you will be able to begin coding. You can either edit the preloaded Ready templates or use the My Coded Strategies section to create your own strategies.
"},{"location":"python_build/python-build-introduction/","title":"Python Build Web","text":""},{"location":"python_build/python-build-introduction/#introduction","title":"Introduction","text":"Now you can code your own strategy easily using our Python Build service! Begin coding your own strategy from scratch, or modify some of our ready-made templates to suit your needs. Get access to our state-of-the-art AlgoBulls Core Trading Engine, which automatically leverages our infrastructure so that you can access the latest historical data to gauge the performance of your strategies. Tweak the various parameters of your strategy to choose the ideal instrument, indicator values, and profit loss percentages as per your needs! View the performance of your strategy using our visual analytics feature and continue to tweak until you are satisfied with the performance. Get your strategy approved for live trading from our experts and deploy it on 30+ supported brokers without coding any broker integration logic.
Select Python Build from the navigation bar on the left to know more.
"},{"location":"python_build/python-build-introduction/#an-overview","title":"An overview","text":"Running Strategies: This section shows how many strategies are currently active and running in your account.
Strategies Saved: This displays the number of strategies saved in your AlgoBulls account. It also shows the number of maximum strategies that you can save as per your current plan.
Execution Time Consumed: You can view the number of minutes that have been used for Backtesting or Paper Trading your strategies.
Note:
Paper Trading would be available from Monday - Friday (excluding NSE/NASDAQ holidays) within the trading time of that particular exchange. You can code your strategy, execute on Backtesting mode or analyse the strategy results 24x7.
Analytics Support: This shows whether your analytics support is active. Analytics support is not available to free plan users.
Professional Support: This section connects you to other professional support forums for additional support while developing the strategy.
Active Plan: This section displays the current plan active on your AlgoBulls account.
Ready Templates: Ready-to-use templates that you can modify and test.
My Coded Strategies: Strategies that have been coded and saved by you are displayed here. This includes new and modified strategies developed by you.
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:
Click on \"Professional Support\" - Look for the \"Professional Support\" button on the Python Build Web splash and click on it to get started.
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%.\"
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.
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.
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
StrategyOptionsEMACrossover(StrategyOptionsBaseV2)\n
Coding Conventions
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
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:
self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
_order
is the order object stored inside the OrderTagManager
for the tags base_inst_str
and entry_key
.eg:
self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
OrderTagManager
for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER
and entry_key
OrderTagManager
along with the orders related stored in that tageg:
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":"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
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.
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.
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.
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.
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
StrategyFuturesEMACrossover(StrategyBase)\n
Coding Conventions
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
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.
"},{"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:
self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
_order
is the order object stored inside the OrderTagManager
for the tags base_inst_str
and entry_key
.self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
OrderTagManager
for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER
and entry_key
OrderTagManager
along with the orders related stored in that tag eg: self.order_tag_manager.remove_tags(tags=entry_key)\n
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":"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":"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
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.
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.
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
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
Once you create your own strategy or use a ready strategy from the pyalgostrategypool package, this is how it works internally on the AlgoBulls Core Trading Engine.
"},{"location":"strategies/aroon_crossover/","title":"Aroon Crossover","text":"This is a trading strategy called \"Aroon Crossover\" implemented in Python using the PyAlgoTrading library. The strategy is based on the Aroon indicator crossover.
Links
Jupyter Notebooks for Indian Exchange (NSE)
Jupyter Notebook for US Exchange (NASDAQ)
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.
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.
This is a trading strategy called \"Bollinger Bands\" implemented in Python using the PyAlgoTrading library. The strategy is based on the bollinger bands indicator values.
Links
Jupyter Notebooks for Indian Exchange (NSE)
Jupyter Notebook for US Exchange (NASDAQ)
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:
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.
This is a trading strategy called \"EMA Regular Order Strategy\" implemented in Python using the PyAlgoTrading library. The strategy is based on the exponential moving average crossover.
Links
Jupyter Notebooks for Indian Exchange (NSE)
Jupyter Notebook for US Exchange (NASDAQ)
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:
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).
This is a trading strategy called \"Inverse EMA Scalping Regular Order Strategy\" implemented in Python using the PyAlgoTrading library. The strategy is based on the exponential moving average crossover.
Links
Jupyter Notebooks for Indian Exchange (NSE)
Jupyter Notebooks for US Exchange (NASDAQ)
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:
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).
This class implements the Options Bear Call Ladder strategy.
Links
Jupyter Notebook for Options from Indian Exchange (NSE)
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:
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.
This is a template for the Options Bear Put Ladder strategy. The strategy involves the combination of buying and selling put options to profit from a downward price movement in the underlying asset. It utilizes multiple legs with different strike prices and transaction types to create a ladder-like structure.
Links
Jupyter Notebook for Options from Indian Exchange (NSE)
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:
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.
Links
Jupyter Notebook for Options from Indian Exchange (NSE)
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:
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.
Links
Jupyter Notebook for Options from Indian Exchange (NSE)
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:
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.
The __init__
method initializes the strategy and accepts parameters for configuring the strategy. The parameters are:
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
This is a template for implementing the Options Long Iron Butterfly strategy in Python.
Links
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:
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.
The strategy accepts the following parameters:
Name Default Value Expected Value Description LEG_ONE_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_ONE_TRADING_SYMBOL_SUFFIX 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_ONE_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_ONE_NUMBER_OF_STRIKES 0 greater than 0 Number of strikes for leg one. LEG_TWO_TRANSACTION_TYPE 1 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_TWO_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_TWO_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_TWO_NUMBER_OF_STRIKES 0 greater than 0 Number of strikes for leg one. LEG_THREE_TRANSACTION_TYPE 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_THREE_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_THREE_STRIKE_DIRECTION 1 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_THREE_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one. LEG_FOUR_TRANSACTION_TYPE 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] LEG_FOUR_TRADING_SYMBOL_SUFFIX 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] LEG_FOUR_STRIKE_DIRECTION 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] LEG_FOUR_NUMBER_OF_STRIKES 2 greater than 0 Number of strikes for leg one."},{"location":"strategies/options_straddle/","title":"Options Straddle","text":""},{"location":"strategies/options_straddle/#options-straddle","title":"Options Straddle","text":"This class represents the implementation of an options straddle trading strategy.
Links
Jupyter Notebook for Options from Indian Exchange (NSE)
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.
The StrategyOptionsStrangle
class is a strategy template for trading options strangles. It is derived from the StrategyOptionsBaseV2
class.
Links
Jupyter Notebook for Options from Indian Exchange (NSE)
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.
The following parameters can be set in the Parameters Configuration Pane:
Name Default Value Expected Value Description _leg_one_transaction_type 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] _leg_one_tradingsymbol_suffix 1 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] _leg_one_strike_direction 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] _leg_one_number_of_strikes 2 greater than 0 Number of strikes for leg one. _leg_two_transaction_type 2 1 or 2 Transaction type for leg one. [BUY: 1, SELL: 2] _leg_two_tradingsymbol_suffix 2 1 or 2 Trading symbol suffix for leg one. [CE: 1, PE: 2] _leg_two_strike_direction 2 0, 1 or 2 Strike direction for leg one. [ITM: 0, ATM: 1, OTM: 2] _leg_two_number_of_strikes 2 greater than 0 Number of strikes for leg one."},{"location":"strategies/reverse_rsi/","title":"Reverse RSI","text":"This is a trading strategy called \"Reverse RSI\" implemented in Python using the PyAlgoTrading library. The strategy is based on the relative strength index indicator.
Links
Jupyter Notebook for Indian Exchange (NSE)
Jupyter Notebook for US Exchange (NASDAQ)
RSI stands for Relative Strength Index, and it is a popular technical indicator used in the stock market to analyze the strength and momentum of a price trend. The RSI provides insights into whether a stock is overbought or oversold and can help identify potential trend reversals.
Here is a summary of RSI in the stock market:
Overall, the Relative Strength Index (RSI) is a widely used indicator in the stock market to assess the strength and momentum of price movements. It helps traders identify overbought and oversold conditions, as well as potential trend reversals, which can assist in making trading decisions.
Fig.1 - MCD candle chart (top) and RSI plot (bottom)"},{"location":"strategies/reverse_rsi/#strategy-overview","title":"Strategy Overview","text":"The Reverse RSI strategy is a trading strategy based on the Relative Strength Index (RSI) indicator. It generates entry and exit signals based on the reverse crossover of the RSI values from specified overbought and oversold levels.
"},{"location":"strategies/reverse_rsi/#strategy-parameters","title":"Strategy Parameters","text":"The following parameters can be configured for the strategy:
Name Default Value Expected Value Description TIME_PERIOD None greater than 0 Period (number of candles) by which RSI is calculated OVERBOUGHT_VALUE None greater than 0 RSI value above which stocks are considered over-bought OVERSOLD_VALUE None greater than 0 RSI value below which stocks are considered over-sold"},{"location":"strategies/reverse_rsi/#crossover-calculation","title":"Crossover Calculation","text":"The get_crossover_value
method calculates the crossover values for the RSI indicator using historical data of the instrument. It compares the RSI values with the overbought and oversold levels to determine the entry and exit actions. The method returns the crossover values for oversold and overbought levels.
This is a trading strategy called \"Stochastic Crossover\" implemented in Python using the PyAlgoTrading library. The strategy is based on the Stochastic indicator crossover.
Links
Jupyter Notebook for Indian Exchange (NSE)
Jupyter Notebook for US Exchange (NASDAQ)
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 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.
This is a trading strategy called \"VWAP Crossover\" implemented in Python using the PyAlgoTrading library. The strategy is based on the crossover of the VWAP (Volume Weighted Average Price) indicator.
Links
Jupyter Notebook for Indian Exchange (NSE)
Jupyter Notebook for US Exchange (NASDAQ)
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:
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.
Links
StrategyOptionsEMACrossover(StrategyOptionsBaseV2)\n
Coding Conventions
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
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:
self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
_order
is the order object stored inside the OrderTagManager
for the tags base_inst_str
and entry_key
.eg:
self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
OrderTagManager
for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER
and entry_key
OrderTagManager
along with the orders related stored in that tageg:
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":"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
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.
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.
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.
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.
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
StrategyFuturesEMACrossover(StrategyBase)\n
Coding Conventions
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
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.
"},{"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:
self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])\n
_order
is the order object stored inside the OrderTagManager
for the tags base_inst_str
and entry_key
.self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)\n
OrderTagManager
for the tags base_inst_str, BrokerExistingOrderPositionConstants.ENTER
and entry_key
OrderTagManager
along with the orders related stored in that tag eg: self.order_tag_manager.remove_tags(tags=entry_key)\n
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":"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":"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
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.
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.
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). Inside the strategy class there are many methods that could be divided into 4 different sections: Initialization Methods, Algorithmic Calculation Methods, 4-Core Loop Methods, Miscellaneous Methods. These 4 sections are explained briefly below.
"},{"location":"strategies/strategy_guides/common_strategy_guide/#initialization-methods","title":"Initialization Methods","text":"In this section, you will have the Strategy Class\u2019s \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/#algorithmic-calculations-methods","title":"Algorithmic Calculations Methods","text":"This section will majorly contain the methods that are defined by the user. Their main purpose will be to perform operations on historical 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/#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/#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":""},{"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:
RegularOptionsclass MovingAverageCrossoverV2(StrategyBase):\nname = 'Moving Average Crossover V2'\n
class StrategyOptionsBearCallLadder(StrategyOptionsBaseV2):\nname = '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.
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):\nsuper().__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.
RegularOptionsclass StrategyEMARegularOrder(StrategyBase):\nname = 'EMA Regular Order Strategy'\ndef __init__(self, *args, **kwargs):\nsuper().__init__(*args, **kwargs)\nself.timeperiod1 = self.strategy_parameters['TIMEPERIOD1']\nself.timeperiod2 = self.strategy_parameters['TIMEPERIOD2']\nself.main_order_map = None\n
class StrategyOptionsBearCallLadder(StrategyOptionsBaseV2):\nname = 'Options Bear Call Ladder Template'\ndef __init__(self, *args, **kwargs):\nsuper().__init__(*args, **kwargs)\n# Parameters (currently set with default values, can be overridden from the Parameters Configuration Pane)\nself._leg_one_transaction_type = self.strategy_parameters.get('LEG_ONE_TRANSACTION_TYPE', 1) # BUY: 1 | SELL: 2\nself._leg_one_tradingsymbol_suffix = self.strategy_parameters.get('LEG_ONE_TRADING_SYMBOL_SUFFIX', 1) # CE: 1 | PE: 2\nself._leg_one_strike_direction = self.strategy_parameters.get('LEG_ONE_STRIKE_DIRECTION', 1) # ITM: 0| ATM: 1| OTM: 2\nself._leg_one_number_of_strikes = self.strategy_parameters.get('LEG_ONE_NUMBER_OF_STRIKES', 0)\nself._leg_two_transaction_type = self.strategy_parameters.get('LEG_TWO_TRANSACTION_TYPE', 1) # BUY: 1 | SELL: 2\nself._leg_two_tradingsymbol_suffix = self.strategy_parameters.get('LEG_TWO_TRADING_SYMBOL_SUFFIX', 1) # CE: 1 | PE: 2\nself._leg_two_strike_direction = self.strategy_parameters.get('LEG_TWO_STRIKE_DIRECTION', 2) # ITM: 0| ATM: 1| OTM: 2\nself._leg_two_number_of_strikes = self.strategy_parameters.get('LEG_TWO_NUMBER_OF_STRIKES', 2)\nself._leg_three_transaction_type = self.strategy_parameters.get('LEG_THREE_TRANSACTION_TYPE', 2) # BUY: 1 | SELL: 2\nself._leg_three_tradingsymbol_suffix = self.strategy_parameters.get('LEG_THREE_TRADING_SYMBOL_SUFFIX', 1) # CE: 1 | PE: 2\nself._leg_three_strike_direction = self.strategy_parameters.get('LEG_THREE_STRIKE_DIRECTION', 0) # ITM: 0| ATM: 1| OTM: 2\nself._leg_three_number_of_strikes = self.strategy_parameters.get('LEG_THREE_NUMBER_OF_STRIKES', 2)\n# Maps\nself.transaction_type_map = {1: \"BUY\", 2: \"SELL\"}\nself.tradingsymbol_suffix_map = {1: \"CE\", 2: \"PE\"}\nself.strike_direction_map = {0: OptionsStrikeDirection.ITM, 1: OptionsStrikeDirection.ATM, 2: OptionsStrikeDirection.OTM}\n# Variables\nself.number_of_allowed_expiry_dates = 1\nself.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:
RegularOptionsdef initialize(self):\nself.main_order_map = {}\n
def initialize(self):\nsuper().initialize()\nself.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:
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.hist_data[\u2018<column_name>\u2019]\n
Example: close = hist_data[\u2018close\u2019]\n
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. Next, you analyze this 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. 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 directionBy 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):\nhist_data = self.get_historical_data(instrument)\nrsi_value = talib.RSI(hist_data['close'], timeperiod=self.time_period)\noversold_list = [self.oversold_value] * rsi_value.size\noverbought_list = [self.overbought_value] * rsi_value.size\noversold_crossover_value = self.utils.crossover(rsi_value, oversold_list)\noverbought_crossover_value = self.utils.crossover(rsi_value, overbought_list)\nreturn oversold_crossover_value, overbought_crossover_value\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#miscellaneous-functions","title":"Miscellaneous Functions","text":""},{"location":"strategies/strategy_guides/common_strategy_guide/#get_child_instrument_details","title":"get_child_instrument_details()","text":"The get_child_instrument_details function is at your disposal. It takes several parameters:
This function calls two other functions: self.get_allowed_expiry_dates()
and get_options_instrument_with_strike_direction()
.
Example: This is how the function looks ideally. This example was taken from \u201cOptions Bear Call Strategy\u201d from ready templates.
def get_child_instrument_details(self, base_instrument, tradingsymbol_suffix, strike_direction, no_of_strikes):\nexpiry_date = self.get_allowed_expiry_dates()[0]\nchild_instrument = self.get_options_instrument_with_strike_direction(base_instrument, expiry_date, tradingsymbol_suffix, strike_direction, no_of_strikes)\nreturn child_instrument\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#get_allowed_expiry_dates","title":"get_allowed_expiry_dates()","text":"In options strategies, the get_allowed_expiry_dates function plays a vital role. It doesn't require parameters; instead, it relies on the number_of_allowed_expiry_dates variable defined in the constructor method.
In essence, this function helps you select the appropriate expiry date based on the value you assign to number_of_allowed_expiry_dates
variable.
This function is a key player in options strategies, taking parameters such as:
Now, let's talk about a crucial piece of the options strategy puzzle \u2013 options_instruments_set_up_local
. This function creates local instances of all available child instruments based on specified parameters:
Once executed, this function sets up and stores local instances of child instruments matching your criteria. These instances become valuable assets for further analysis or operations, including utilising the \"get_child_instrument_details\" function.
Example: This is how this function looks ideally. This example was taken from \u201cOptions Bear Call Ladder\u201d from ready templates.
def options_instruments_set_up_local(self, base_instrument, tradingsymbol_suffix, current_close, direction=OptionsInstrumentDirection.EXACT):\nexpiry_dates = self.get_allowed_expiry_dates()\nfor expiry_date in expiry_dates:\nself.options_instruments_set_up(base_instrument, direction, expiry_date, tradingsymbol_suffix, current_close)\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#options_instruments_set_up","title":"options_instruments_set_up()","text":"The final piece of the puzzle is \"options_instruments_set_up.\" This function takes parameters like:
Now, let's talk about the engine that drives your strategy \u2013 the core loop functions.
These include \"strategy_select_instruments_for_entry\", \"strategy_enter_position\", \"strategy_select_instruments_for_exit\" and \"strategy_exit_position\" These functions are called within a loop from the AlgoBulls core until an Exit Event for the strategy occurs.
"},{"location":"strategies/strategy_guides/common_strategy_guide/#the-4-core-loop-functions","title":"The 4 Core Loop Functions","text":""},{"location":"strategies/strategy_guides/common_strategy_guide/#strategy_select_instruments_for_entry","title":"strategy_select_instruments_for_entry()","text":"This function takes parameters:
Example: This function would ideally look like this. This example was taken from \u201cOptions Straddle\u201d from Ready Templates.
Examples:
RegularOptionsdef strategy_select_instruments_for_entry(self, candle, instruments_bucket):\nselected_instruments, meta = [], []\nfor instrument in instruments_bucket:\ncrossover = self.get_decision(instrument)\naction_constants = {1: 'BUY', -1: 'SELL'}\nif crossover in [-1, 1]:\nselected_instruments.append(instrument)\nmeta.append({'action': action_constants[crossover]})\nreturn selected_instruments, meta\n
def strategy_select_instruments_for_entry(self, candle, instruments_bucket):\nselected_instruments, meta = [], []\nfor instrument in instruments_bucket:\nif instrument not in self.instruments_done_for_the_day:\nself.instruments_done_for_the_day.append(instrument)\nltp = self.broker.get_ltp(instrument)\nself.options_instruments_set_up_local(instrument, \"CE\", ltp)\nself.options_instruments_set_up_local(instrument, \"PE\", ltp)\nleg_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)]\nfor leg_number, tradingingsymbol_suffix, strike_direction, number_of_strikes, transaction_type in leg_wise_list:\nself.logger.info(f'Processing {leg_number}...')\nchild_instrument = self.get_child_instrument_details(instrument, self.tradingsymbol_suffix_map[tradingingsymbol_suffix], self.strike_direction_map[strike_direction], number_of_strikes)\nselected_instruments.append(child_instrument)\nmeta.append({'base_instrument': instrument, 'action': self.transaction_type_map[transaction_type]})\nreturn selected_instruments, meta\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#strategy_enter_position","title":"strategy_enter_position()","text":"This function takes parameters:
Here, you place orders for the selected instruments, updating them in \"self.main_order\" for easy access in exit functions.
Example: This function would ideally look like this. This example was taken from \u201cOptions Straddle\u201d from Ready Templates.
Examples:
RegularOptionsdef strategy_enter_position(self, candle, instrument, meta):\nself.main_order_map[instrument] = _ = self.broker.OrderRegular(instrument, meta['action'], quantity=self.number_of_lots * instrument.lot_size)\nreturn _\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)\nreturn _\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#strategy_select_instruments_for_exit","title":"strategy_select_instruments_for_exit()","text":"Similar to entry, this function takes parameters:
The function iterates through the instrument bucket, checking if the instrument is present in \"self.main_order\" and whether its exit condition is satisfied. Instruments meeting exit conditions are added to the selected instruments list, along with their respective actions and meta-information.
Example: This function should ideally look like this. This example was taken from \u201cEMA Crossover Strategy\u201d.
def strategy_select_instruments_for_exit(self, candle, instruments_bucket):\nselected_instruments, meta = [], []\nfor instrument in instruments_bucket:\nif self.main_order_map.get(instrument) is not None:\ncrossover = self.get_decision(instrument)\nif crossover in [1, -1]:\nselected_instruments.append(instrument)\nmeta.append({'action': 'EXIT'})\nreturn selected_instruments, meta\n
"},{"location":"strategies/strategy_guides/common_strategy_guide/#strategy_exit_position","title":"strategy_exit_position()","text":"Finally, this function takes parameters:
Here, you place orders for the selected instruments, removing them from \"self.main_order\" to prepare for the next iteration of the AlgoBulls core loop.
Example: This function should ideally look like this. This example was taken from \u201cEMA Crossover Strategy\u201d.
def strategy_exit_position(self, candle, instrument, meta):\nif meta['action'] == 'EXIT':\nself.main_order_map[instrument].exit_position()\nself.main_order_map[instrument] = None\nreturn True\nreturn False\n
"},{"location":"strategies/strategy_guides/structure/","title":"Code Structure of Strategy","text":"Coding Prerequisites
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
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.
"}]} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index 3fad5771..b5c5cbcb 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -2,237 +2,237 @@