Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Python Algorithmic Trading Cookbook
Python Algorithmic Trading Cookbook

Python Algorithmic Trading Cookbook: All the recipes you need to implement your own algorithmic trading strategies in Python

eBook
Can$34.98 Can$49.99
Paperback
Can$61.99
Subscription
Free Trial

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Python Algorithmic Trading Cookbook

Stock Markets - Primer on Trading

When building algorithmic trading systems, it is essential to have an account open with a modern broker that provides APIs for placing and querying trades programmatically. This allows us to control the broking account, which is conventionally operated manually using the broker's website, using our Python script, which would be part of our larger algorithmic trading system. This chapter demonstrates various essential recipes that introduce the essential broker API calls needed for developing a complete algorithmic trading system.

This chapter covers the following recipes:

  • Setting up Python connectivity with the broker
  • Querying a list of instruments
  • Fetching an instrument
  • Querying a list of exchanges
  • Querying a list of segments
  • Knowing other attributes supported by the broker
  • Placing a simple REGULAR order
  • Placing a simple BRACKET order
  • Placing a simple DELIVERY order
  • Placing a simple INTRADAY order
  • Querying margins and funds
  • Calculating the brokerage charged
  • Calculating the government taxes charged

Let's get started!

Technical requirements

You will need the following to successfully execute the recipes in this chapter:

  • Python 3.7+
  • The Python pyalgotrading package ($ pip install pyalgotrading)

The latest Jupyter Notebook for this chapter can be found on GitHub at https://github.com/PacktPublishing/Python-Algorithmic-Trading-Cookbook/tree/master/Chapter02.

This chapter demonstrates the APIs of a modern broker, ZERODHA, which is supported by pyalgotrading. You may wish to choose other brokers supported by pyalgotrading as well. The recipes in this chapter should be more or less the same for any other broker. The pyalgotrading package abstracts broker APIs behind a unified interface, so you don't need to worry about the underlying broker API calls.

To set up a broking account with ZERODHA, please refer to the detailed steps provided in Appendix I.

Setting up Python connectivity with the broker

The first thing you need to set up connectivity with the broker is API keys. The broker provides unique keys to each customer, typically as an api-key and api-secret key pair. These API keys are chargeable, usually on a monthly subscription basis. You need to get your copies of api-key and api-secret from the broker's website before you start this recipe. Please refer to Appendix I for more details.

How to do it…

We execute the following steps to complete this recipe:

  1. Import the necessary modules:
>>> from pyalgotrading.broker.broker_connection_zerodha import BrokerConnectionZerodha
  1. Get the api_key and api_secret keys from the broker. These are unique to you and will be used by the broker to identify your Demat account:
>>> api_key = "<your-api-key>"
>>> api_secret = "<your-api-secret>"
>>> broker_connection = BrokerConnectionZerodha(api_key, api_secret)

You will get the following result:

Installing package kiteconnect via pip...
Please login to this link to generate your request token: https://kite.trade/connect/login?api_key=<your-api-key>&v=3
  1. Get the request token from the preceding URL:
>>> request_token = "<your-request-token>"
>>> broker_connection.set_access_token(request_token)

How it works...

In step 1, you import the BrokerConnectionZerodha class from pyalgotrading. The BrokerConnectionZerodha class provides an abstraction around the broker-specific APIs. For step 2, you need your API key and API secret from the broker. If you do not have them, please refer to Appendix I for detailed instructions with screenshots on getting this keys. In step 2, you assign your API key and API secret to the new api_key and api_secret variables and use them to create broker_connection, an instance of the BrokerConnectionZerodha class. If you are running this for the first time and kiteconnect is not installed, pyalgotrading will automatically install it for you. (kiteconnect is the official Python package that talks to the Zerodha backend; BrokerConnectionZerodha is a wrapper on top of kiteconnect.) Step 2 generates a login URL. Here, you need to click on the link and log in with your Zerodha credentials. If the authentication process is successful, you will see a link in your browser's address bar that looks similar to the following:

https://127.0.0.1/?request_token=&action=login&status=success

For example, the full link would be as follows:

https://127.0.0.1/?request_token=H06I6Ydv95y23D2Dp7NbigFjKweGwRP7&action=login&status=success

Copy the alphanumeric-token, H06I6Ydv95y23D2Dp7NbigFjKweGwRP7, and paste it into request_token as part of step 3. The broker_connection instance is now ready to perform API calls.

Querying a list of instruments

Once the broker_connection handle is ready, it can be used to query the list containing all the financial instruments provided by the broker.

Getting ready

Make sure the broker_connection object is available in your Python namespace. Refer to the previous recipe in this chapter to set up this object.

How to do it…

We execute the following steps to complete this recipe:

  1. Display all the instruments:
>>> instruments = broker_connection.get_all_instruments()
>>> instruments

You will get an output similar to the following. The exact output may differ for you:

  instrument_token exchange_token tradingsymbol name last_price expiry strike tick_size lot_size instrument_type segment exchange
0 267556358 1045142 EURINR20AUGFUT EURINR 0.0 2020-08-27 0.0 0.0025 1 FUT BCD-FUT BCD
1 268660998 1049457 EURINR20DECFUT EURINR 0.0 2020-12-29 0.0 0.0025 1 FUT BCD-FUT BCD
2 266440966 1040785 EURINR20JULFUT EURINR 0.0 2020-07-29 0.0 0.0025 1 FUT BCD-FUT BCD
3 266073606 1039350 EURINR20JUNFUT EURINR 0.0 2020-06-26 0.0 0.0025 1 FUT BCD-FUT BCD
4 265780742 1038206 EURINR20MAYFUT EURINR 0.0 2020-05-27 0.0 0.0025 1 FUT BCD-FUT BCD
... ... ... ... ... ... ... ... ... ... ... ... ...
64738 978945 3824 ZODJRDMKJ ZODIAC JRD-MKJ 0.0 0.0 0.0500 1 EQ NSE NSE
64739 2916865 11394 ZOTA ZOTA HEALTH CARE 0.0 0.0 0.0500 1 EQ NSE NSE
64740 7437825 29054 ZUARI-BE ZUARI AGRO CHEMICALS 0.0 0.0 0.0500 1 EQ NSE NSE
64741 979713 3827 ZUARIGLOB ZUARI GLOBAL 0.0 0.0 0.0500 1 EQ NSE NSE
64742 4514561 17635 ZYDUSWELL ZYDUS WELLNESS 0.0 0.0 0.0500 1 EQ NSE NSE

64743 rows × 12 columns
  1. Print the total number of instruments:
>>> print(f'Total instruments: {len(instruments)}')

We get the following output (your output may differ):

Total instruments: 64743

How it works…

The first step fetches all the available financial instruments using the get_all_instruments() method of broker_connection. This method returns a pandas.DataFrame object. This object is assigned to a new variable, instruments, which is shown in the output of step 1. This output may differ for you as new financial instruments are frequently added and existing ones expire regularly. The final step shows the total number of instruments provided by the broker.

An explanation of the data that was returned by the preceding API call will be discussed in depth in Chapter 3, Analyzing Financial Data. For this recipe, it suffices to know the method for fetching the list of instruments.

Fetching an instrument

Instruments, also known as financial instruments or securities, are assets that can be traded in an exchange. In an exchange, there can easily be tens of thousands of instruments. This recipe demonstrates how to fetch an instrument based on its exchange and trading symbol.

Getting ready

Make sure the broker_connection object is available in your Python namespace. Refer to the first recipe in this chapter to set up this object.

How to do it…

Fetch an instrument for a specific trading symbol and exchange:

>>> broker_connection.get_instrument(segment='NSE', tradingsymbol='TATASTEEL')

You'll get the following output:

segment: NSE
exchange: NSE
tradingsymbol: TATASTEEL
broker_token: 895745
tick_size: 0.05
lot_size: 1
expiry:
strike_price: 0.0

How it works…

The broker_connection object provides a handy method, get_instrument, for fetching any financial instrument. It takes segment and tradingsymbol as attributes before returning an instrument. The return object is an instance of the Instrument class.

Querying a list of exchanges

An exchange is a marketplace where instruments are traded. Exchanges ensure that the trading process is fair and happens in an orderly fashion at all times. Usually, a broker supports multiple exchanges. This recipe demonstrates how to find the list of exchanges supported by the broker.

Getting ready

Make sure the instruments object is available in your Python namespace. Refer to the second recipe of this chapter to learn how to set up this object.

How to do it…

Display the exchanges supported by the broker:

>>> exchanges = instruments.exchange.unique()
>>> print(exchanges)

You will get the following output:

['BCD' 'BSE' 'NSE' 'CDS' 'MCX' 'NFO']

How it works…

instruments.exchange returns a pandas.Series object. Its unique() method returns a numpy.ndarray object consisting of unique exchanges supported by the broker.

Querying a list of segments

A segment is essentially a categorization of instruments based on their types. The various types of segments that are commonly found at exchanges include cash/equities, futures, options, commodities, and currency. Each segment may have a different operating time. Usually, a broker supports multiple segments within multiple exchanges. This recipe demonstrates how to find the list of segments supported by the broker.

Getting ready

Make sure the instruments object is available in your Python namespace. Refer to the second recipe of this chapter to learn how to set up this object.

How to do it…

Display the segments supported by the broker:

>>> segments = instruments.segment.unique()
>>> print(segments)

You will get the following output:

['BCD-FUT' 'BCD' 'BCD-OPT' 'BSE' 'INDICES' 'CDS-FUT' 'CDS-OPT' 'MCX-FUT' 'MCX-OPT' 'NFO-OPT' 'NFO-FUT' 'NSE']

How it works…

instruments.segment returns a pandas.Series object. Its unique method returns a numpy.ndarray object consisting of unique segments supported by the broker.

Knowing other attributes supported by the broker

For placing an order, the following attributes are needed: order transaction type, order variety, order type, and order code. Different brokers may support different types of order attributes. For example, some brokers may support just regular orders, while others may support regular and bracket orders. The value for each of the attributes supported by the broker can be queried using the broker specific constants provided by the pyalgotrading package.

How to do it…

We execute the following steps to complete this recipe:

  1. Import the necessary class from the pyalgotrading module:
>>> from pyalgotrading.broker.broker_connection_zerodha import BrokerConnectionZerodha
  1. List the order transaction types:
>>> list(BrokerConnectionZerodha.ORDER_TRANSACTION_TYPE_MAP.keys())

We'll get the following output:

[<BrokerOrderTransactionTypeConstants.BUY: 'BUY'>,
<BrokerOrderTransactionTypeConstants.SELL: 'SELL'>]
  1. List the order varieties:
>>> list(BrokerConnectionZerodha.ORDER_VARIETY_MAP.keys())

We'll get the following output:

[<BrokerOrderVarietyConstants.MARKET: 'ORDER_VARIETY_MARKET'>,
<BrokerOrderVarietyConstants.LIMIT: 'ORDER_VARIETY_LIMIT'>,
<BrokerOrderVarietyConstants.STOPLOSS_LIMIT: 'ORDER_VARIETY_STOPLOSS_LIMIT'>,
<BrokerOrderVarietyConstants.STOPLOSS_MARKET: 'ORDER_VARIETY_STOPLOSS_MARKET'>]
  1. List the order types:
>>> list(BrokerConnectionZerodha.ORDER_TYPE_MAP.keys())

We'll get the following output:

[<BrokerOrderTypeConstants.REGULAR: 'ORDER_TYPE_REGULAR'>,
<BrokerOrderTypeConstants.BRACKET: 'ORDER_TYPE_BRACKET'>,
<BrokerOrderTypeConstants.COVER: 'ORDER_TYPE_COVER'>,
<BrokerOrderTypeConstants.AMO: 'ORDER_TYPE_AFTER_MARKET_ORDER'>]
  1. List the order codes:
>>> list(BrokerConnectionZerodha.ORDER_CODE_MAP.keys())

We'll get the following output:

[<BrokerOrderCodeConstants.INTRADAY: 'ORDER_CODE_INTRADAY'>,
<BrokerOrderCodeConstants.DELIVERY: 'ORDER_CODE_DELIVERY_T0'>]

How it works…

In step 1, we import the BrokerConnectionZerodha class from pyalgotrading. This class holds the order attributes mapping between pyalgotrading and broker specific constants as dictionary objects. The next steps fetch and print these mappings. Step 2 shows that your broker supports both BUY and SELL order transaction types.

Step 3 shows that your broker supports MARKET, LIMIT, STOPLOSS_LIMIT, and STOPLOSS_MARKET order varieties. Step 4 shows that your broker supports REGULAR, BRACKET, COVER, and AFTER_MARKET order types. Step 5 shows that your broker supports INTRADAY and DELIVERY order codes.

The outputs may differ from broker to broker, so consult your broker documentation if you are using a different broker. A detailed explanation of all these types of parameters will be covered in Chapter 6, Placing Trading Orders on the Exchange. This recipe is to just give an overview of the parameters, as they are needed in the subsequent recipes of this chapter.

Placing a simple REGULAR order

This recipe demonstrates how to place a REGULAR order on the exchange via the broker. REGULAR orders are the simplest types of orders. After trying out this recipe, check your broking account by logging into the broker's website; you will find that an order has been placed there. You can match the order ID with the one that's returned in the last code snippet shown in this recipe.

Getting ready

Make sure the broker_connection object is available in your Python namespace. Refer to the first recipe of this chapter to learn how to set up this object.

How to do it…

We execute the following steps to complete this recipe:

  1. Import the necessary constants from pyalgotrading:
>>> from pyalgotrading.constants import *
  1. Fetch an instrument for a specific trading symbol and exchange:
>>> instrument = broker_connection.get_instrument(segment='NSE', 
tradingsymbol='TATASTEEL')
  1. Place a simple regular order – a BUY, REGULAR, INTRADAY, MARKET order:
>>> order_id = broker_connection.place_order(
instrument=instrument,
order_transaction_type= \
BrokerOrderTransactionTypeConstants.BUY,
order_type=BrokerOrderTypeConstants.REGULAR,
order_code=BrokerOrderCodeConstants.INTRADAY,
order_variety= \
BrokerOrderVarietyConstants.MARKET,
quantity=1)
>>> order_id

We'll get the following output:

191209000001676

How it works…

In step 1, you import constants from pyalgotrading. In step 2, you fetch the financial instrument with segment = 'NSE' and tradingsymbol = 'TATASTEEL' using the get_instrument() method of broker_connection. In step 3, you place a REGULAR order using the place_order() method of broker_connection. The descriptions of the parameters accepted by the place_order() method are as follows:

  • instrument: The financial instrument for which the order must be placed. Should an instance of the Instrument class. You pass instrument here.
  • order_transaction_type: The order transaction type. Should be an enum of type BrokerOrderTransactionTypeConstants. You pass BrokerOrderTransactionTypeConstants.BUY here.
  • order_type: The order type. Should be an enum of type BrokerOrderTypeConstants. You pass BrokerOrderTypeConstants.REGULAR here.
  • order_code: The order code. Should be an enum of type BrokerOrderCodeConstants. You pass BrokerOrderCodeConstants.INTRADAY here.
  • order_variety: The order variety. Should be an enum of type BrokerOrderVarietyConstants. You pass BrokerOrderVarietyConstants.MARKET here.
  • quantity: The number of shares to be traded for the given instrument. Should be a positive integer. We pass 1 here.

If the order placement is successful, the method returns an order ID which you can use at any point in time later on for querying the status of the order.

A detailed explanation of the different types of parameters will be covered in Chapter 6, Placing Trading Orders on the Exchange. This recipe is intended to give you an idea of how to place a REGULAR order, one of the various types of possible orders.

Placing a simple BRACKET order

This recipe demonstrates how to place a BRACKET order on the exchange via the broker. BRACKET orders are two-legged orders. Once the first order is executed, the broker automatically places two new orders a STOPLOSS order and a TARGET order. Only one of them is executed at any time; the other is canceled when the first order is completed. After trying out this recipe, check your broking account by logging into the broker's website; you will find that an order has been placed there. You can match the order ID with the one that's returned in the last code snippet shown in this recipe.

Getting ready

Make sure the broker_connection object is available in your Python namespace. Refer to the first recipe of this chapter to learn how to set up this object.

How to do it…

We execute the following steps to complete this recipe:

  1. Import the necessary modules:
>>> from pyalgotrading.constants import *
  1. Fetch an instrument for a specific trading symbol and exchange:
>>> instrument = broker_connection.get_instrument(segment='NSE', 
tradingsymbol='ICICIBANK')
  1. Fetch the last traded price of the instrument:
>>> ltp = broker_connection.get_ltp(instrument)
  1. Place a simple BRACKET order – a BUY, BRACKET, INTRADAY, LIMIT order:
>>> order_id = broker_connection.place_order(
instrument=instrument,
order_transaction_type= \
BrokerOrderTransactionTypeConstants.BUY,
order_type=BrokerOrderTypeConstants.BRACKET,
order_code=BrokerOrderCodeConstants.INTRADAY,
order_variety=BrokerOrderVarietyConstants.LIMIT,
quantity=1, price=ltp-1,
stoploss=2, target=2)
>>> order_id

We'll get the following output:

191212001268839
If you get the following error while executing this code, it would mean that Bracket orders are blocked by the broker due to high volatility in the markets:

InputException: Due to expected higher volatility in the markets, Bracket orders are blocked temporarily.

You should try the recipe later when the broker starts allowing Bracket orders. You can check for updates on the Broker site from time to time to know when Bracket orders would be allowed.

How it works…

In step 1, you import the constants from pyalgotrading. In step 2, you fetch the financial instrument with segment = 'NSE' and tradingsymbol = 'ICICBANK' using the get_instrument() method of broker_connection. In step 3, you fetch the last traded price or LTP of the instrument. (LTP will be explained in more detail in the Last traded price of a financial instrument recipe of Chapter 3, Analyzing Financial Data.) In step 4, you place a BRACKET order using the place_order() method of broker_connection. The descriptions of the parameters accepted by the place_order() method are as follows:

  • instrument: The financial instrument for which the order must be placed. Should be an instance of the Instrument class. You pass instrument here.
  • order_transaction_type: The order transaction type. Should be an enum of type BrokerOrderTransactionTypeConstants. You pass BrokerOrderTransactionTypeConstants.BUY here.
  • order_type: The order type. Should be an enum of type BrokerOrderTypeConstants. You pass BrokerOrderTypeConstants.BRACKET here.
  • order_code: The order code. Should be an enum of type BrokerOrderCodeConstants. You pass BrokerOrderCodeConstants.INTRADAY here.
  • order_variety: The order variety. Should be an enum of type BrokerOrderVarietyConstants. You pass BrokerOrderVarietyConstants.LIMIT here.
  • quantity: The number of shares to be traded for the given instrument. Should be a positive integer. You pass 1 here.
  • price: The limit price at which the order should be placed. You pass ltp-1 here, which means 1 unit price below the ltp value.
  • stoploss: The price difference from the initial order price, at which the stoploss order should be placed. Should be a positive integer or float value. You pass 2 here.
  • target: The price difference from the initial price, at which the target order should be placed. Should be a positive integer or float value. You pass 2 here.

If the order placement is successful, the method returns an order ID which you can use at any point in time later on for querying the status of the order.

A detailed explanation of the different types of parameters will be covered in Chapter 6, Placing Trading Orders on the Exchange. This recipe is intended to give you an idea of how to place a BRACKET order, one of the various types of possible orders.

Placing a simple DELIVERY order

This recipe demonstrates how to place a DELIVERY order on the exchange via the broker. A DELIVERY order is delivered to the user's Demat account and exists until it is explicitly squared-off by the user. Positions created by delivery orders at the end of a trading session are carried forwarded to the next trading session. They are not explicitly squared-off by the broker. After trying out this recipe, check your broking account by logging into the broker's website; you will find that an order has been placed there. You can match the order ID with the one that's returned in the last code snippet shown in this recipe.

Getting ready

Make sure the broker_connection object is available in your Python namespace. Refer to the first recipe of this chapter to learn how to set up this object.

How to do it…

We execute the following steps to complete this recipe:

  1. Import the necessary modules:
>>> from pyalgotrading.constants import *
  1. Fetch an instrument for a specific trading symbol and exchange:
>>> instrument = broker_connection.get_instrument(segment='NSE', 
tradingsymbol='AXISBANK')
  1. Place a simple DELIVERY order – a SELL, REGULAR, DELIVERY, MARKET order:
>>> order_id = broker_connection.place_order(
instrument=instrument,
order_transaction_type= \
BrokerOrderTransactionTypeConstants.SELL,
order_type=BrokerOrderTypeConstants.REGULAR,
order_code=BrokerOrderCodeConstants.DELIVERY,
order_variety= \
BrokerOrderVarietyConstants.MARKET,
quantity=1)
>>> order_id

We'll get the following output:

191212001268956

How it works…

In step 1, you import the constants from pyalgotrading. In step 2, you fetch the financial instrument with segment = 'NSE' and tradingsymbol = 'AXISBANK' using the get_instrument() method of broker_connection. In step 3, you place a DELIVERY order using the place_order() method of broker_connection. This method accepts the following arguments:

  • instrument: The financial instrument for which the order must be placed. Should be an instance of the Instrument class. You pass instrument here.
  • order_transaction_type: The order transaction type. Should be an enum of type BrokerOrderTransactionTypeConstants. You pass BrokerOrderTransactionTypeConstants.SELL here.
  • order_type: The order type. Should be an enum of type BrokerOrderTypeConstants. You pass BrokerOrderTypeConstants.REGULAR here.
  • order_code: The order code. Should be an enum of type BrokerOrderCodeConstants. You pass BrokerOrderCodeConstants.DELIVERY here.
  • order_variety: The order variety. Should be an enum of type BrokerOrderVarietyConstants. You pass BrokerOrderVarietyConstants.MARKET here.
  • quantity: The number of shares to be traded for the given instrument. Should be a positive integer. We pass 1 here.

If the order placement is successful, the method returns an order ID which you can use at any point in time later on for querying the status of the order.

A detailed explanation of the different types of parameters will be covered in Chapter 6, Placing Trading Orders on the Exchange. This recipe is intended to give you an idea of how to place a DELIVERY order, one of the various types of possible orders.

Placing a simple INTRADAY order

This recipe demonstrates how to place an INTRADAY order via the broker API. An INTRADAY order is not delivered to the user's Demat account. Positions created by intraday orders have a lifetime of a single day. The positions are explicitly squared off by the broker at the end of a trading session and are not carried forward to the next trading session. After trying out this recipe, check your broking account by logging into the broker's website; you will find that an order has been placed there. You can match the order ID with the one that's returned in the last code snippet shown in this recipe.

Getting ready

Make sure the broker_connection object is available in your Python namespace. Refer to the first recipe of this chapter to learn how to set up this object.

How to do it…

We execute the following steps to complete this recipe:

  1. Import the necessary modules:
>>> from pyalgotrading.constants import *
  1. Fetch an instrument for a specific trading symbol and exchange:
>>> instrument = broker_connection.get_instrument(segment='NSE', 
tradingsymbol='HDFCBANK')
  1. Fetch the last traded price of the instrument:
>>> ltp = broker_connection.get_ltp(instrument)
  1. Place a simple INTRADAY order – a SELL, BRACKET, INTRADAY, LIMIT order:
>>> order_id = broker_connection.place_order(
instrument=instrument,
order_transaction_type= \
BrokerOrderTransactionTypeConstants.SELL,
order_type=BrokerOrderTypeConstants.BRACKET,
order_code=BrokerOrderCodeConstants.INTRADAY,
order_variety=BrokerOrderVarietyConstants.LIMIT,
quantity=1, price=ltp+1, stoploss=2, target=2)
>>> order_id

We'll get the following output:

191212001269042
If you get the following error while executing this code, it would mean that Bracket orders are blocked by the broker due to high volatility in the markets:

InputException: Due to expected higher volatility in the markets, Bracket orders are blocked temporarily.

You should try the recipe later when the broker starts allowing Bracket orders. You can check for updates on the Broker site from time to time to know when Bracket orders would be allowed.

How it works…

In step 1, you import the constants from pyalgotrading. In step 2, you fetch the financial instrument with segment = 'NSE' and tradingsymbol = 'HDFCBANK' using the get_instrument() method of broker_connection. In step 3, you fetch the LTP of the instrument. (LTP will be explained in detail in the Last traded price of a financial instrument recipe of Chapter 3, Analyzing Financial Data.) In step 4, you place a BRACKET order using the place_order() method of the broker_connection. The descriptions of the parameters accepted by the place_order() method are as follows:

  • instrument: The financial instrument for which the order must be placed. Should be an instance of the Instrument class. You pass instrument here.
  • order_transaction_type: The order transaction type. Should be an enum of type BrokerOrderTransactionTypeConstants. You pass BrokerOrderTransactionTypeConstants.SELL here.
  • order_type: The order type. Should be an enum of type BrokerOrderTypeConstants. You pass BrokerOrderTypeConstants.BRACKET here.
  • order_code: The order code. Should be an enum of type BrokerOrderCodeConstants. You pass BrokerOrderCodeConstants.INTRADAY here.
  • order_variety: The order variety. Should be an enum of type BrokerOrderVarietyConstants. You pass BrokerOrderVarietyConstants.LIMIT here.
  • quantity: The number of shares to be traded for the given instrument. Should be a positive integer. You pass 1 here.
  • price: The limit price at which the order should be placed. You pass ltp+1 here, which means 1 unit price above the ltp value.
  • stoploss: The price difference from the initial order price, at which the stoploss order should be placed. Should be a positive integer or float value. You pass 2 here.
  • target: The price difference from the initial order price, at which the target order should be placed. Should be a positive integer or float value. You pass 2 here.

If the order placement is successful, the method returns an order ID which you can use at any point in time later on for querying the status of the order.

A detailed explanation of the different types of parameters will be covered in Chapter 6, Placing Trading Orders on the Exchange. This recipe is intended to give you an idea of how to place an INTRADAY order, one of the various types of possible orders.

Querying margins and funds

Before placing orders, it is important to ensure that you have enough margins and funds available in your broking account to place the orders successfully. A lack of sufficient funds would result in the rejection of any orders placed by the broker, which means the others would never get placed on the exchange. This recipe shows you how to find the available margins and funds in your broking account at any point in time.

Getting ready

Make sure the broker_connection object is available in your Python namespace. Refer to the first recipe of this chapter to learn how to set it up.

How to do it…

We execute the following steps to complete this recipe:

  1. Display the equity margins:
>>> equity_margins = broker_connection.get_margins('equity')
>>> equity_margins

We'll get the following output (your output may differ):

{'enabled': True,
'net': 1623.67,
'available': {'adhoc_margin': 0,
'cash': 1623.67,
'opening_balance': 1623.67,
'live_balance': 1623.67,
'collateral': 0,
'intraday_payin': 0},
'utilised': {'debits': 0,
'exposure': 0,
'm2m_realised': 0,
'm2m_unrealised': 0,
'option_premium': 0,
'payout': 0,
'span': 0,
'holding_sales': 0,
'turnover': 0,
'liquid_collateral': 0,
'stock_collateral': 0}}
  1. Display the equity funds:
>>> equity_funds = broker_connection.get_funds('equity')
>>> equity_funds

We'll get the following output (your output may differ):

1623.67
  1. Display the commodity margins:
>>> commodity_margins = get_margins(commodity')
>>> commodity_margins

We'll get the following output (your output may differ):

{'enabled': True,
'net': 16215.26,
'available': {'adhoc_margin': 0,
'cash': 16215.26,
'opening_balance': 16215.26,
'live_balance': 16215.26,
'collateral': 0,
'intraday_payin': 0},
'utilised': {'debits': 0,
'exposure': 0,
'm2m_realised': 0,
'm2m_unrealised': 0,
'option_premium': 0,
'payout': 0,
'span': 0,
'holding_sales': 0,
'turnover': 0,
'liquid_collateral': 0,
'stock_collateral': 0}}
  1. Display the commodity funds:
>>> commodity_funds = broker_connection.get_funds('commodity')
>>> commodity_funds

We'll get the following output (your output may differ):

0

How it works…

The broker_connection object provides methods for fetching the available margins and funds for your broking account:

  • get_margins()
  • get_funds()

The broker Zerodha keeps track of margins and funds separately for equity and commodity products. If you are using a different broker supported by pyalgotrading, it may or may not track the funds and margins separately for equity and commodity.

Step 1 shows how margins can be queried for the equity product using the get_margins() method of the broker_connection object, with equity as an argument. Step 2 shows how funds can be queried for the equity product using the get_funds() method of the broker_connection object, with the equity string as an argument.

Steps 3 and 4 show how margins and funds can be queried for the commodity product in a similar way with the commodity string as an argument.

Calculating the brokerage charged

For every order completed successfully, the broker may charge a certain fee, which is usually a small fraction of the price at which the instrument was bought or sold. While the amount may seem small, it is important to keep track of the brokerage as it may end up eating a significant chunk of your profit at the end of the day.

The brokerage that's charged varies from broker to broker and also from segment to segment. For the purpose of this recipe, we will consider a brokerage of 0.01%.

How to do it…

We execute the following steps to complete this recipe:

  1. Calculate the brokerage that's charged per trade:
>>> entry_price = 1245
>>> brokerage = (0.01 * 1245)/100
>>> print(f'Brokerage charged per trade: {brokerage:.4f}')

We'll get the following output:

Brokerage charged per trade: 0.1245
  1. Calculate the total brokerage that's charged for 10 trades:
>>> total_brokerage = 10 * (0.01 * 1245) / 100
>>> print(f'Total Brokerage charged for 10 trades: \
{total_brokerage:.4f}')

We'll get the following output:

Total Brokerage charged for 10 trades: 1.2450

How it works…

In step 1, we start with the price at which a trade was bought or sold, entry_price. For this recipe, we have used 1245. Next, we calculate 0.01% of the price, which comes to 0.1245. Then, we calculate the total brokerage for 10 such trades, which comes out as 10 * 0.1245 = 1.245.

For every order, the brokerage is charged twice. The first time is when the order has entered a position, while the second time is when it has exited the position. To get the exact details of the brokerage that's been charged for your trades, please refer to the list of charges offered by your broker.

Calculating the government taxes charged

For every order that's completed successfully, the government may charge a certain fee, which is a fraction of the price at which the instrument was bought or sold. While the amount may seem small, it is important to keep track of government taxes as they may end up eating a significant chunk of your profit at the end of the day.

The government charge depends on the location of the exchange, and varies from segment to segment. For the purpose of this recipe, we will consider government taxes at a rate of 0.1%.

How to do it…

We execute the following steps to complete this recipe:

  1. Calculate the government taxes that are charged per trade:
>>> entry_price = 1245
>>> brokerage = (0.1 * 1245)/100
>>> print(f'Government taxes charged per trade: {brokerage:.4f}')

We'll get the following output:

Government taxes charged per trade: 1.2450

  1. Calculate the total government taxes that are charged for 10 trades:
>>> total_brokerage = 10 * (0.1 * 1245) / 100
>>> print(f'Total Government taxes charged for 10 trades: \
{total_brokerage:.4f}')

We'll get the following output:

Total Government taxes charged for 10 trades: 12.4500

How it works…

In step 1, we start with the price at which a trade was bought or sold, entry_price. For this recipe, we have used 1245. Next, we calculate 0.1% of the price, which comes to 1.245. Then, we calculate the total brokerage for 10 such trades, which comes out as 10 * 1.245 = 12.245.

For every order, government taxes are charged twice. The first time is when the order has entered a position, while the second time is when it has exited the position. To get the exact details of the government taxes that are charged for your trades, please refer to the list of government taxes provided by your exchange.
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Build a strong foundation in algorithmic trading by becoming well-versed with the basics of financial markets
  • Demystify jargon related to understanding and placing multiple types of trading orders
  • Devise trading strategies and increase your odds of making a profit without human intervention

Description

If you want to find out how you can build a solid foundation in algorithmic trading using Python, this cookbook is here to help. Starting by setting up the Python environment for trading and connectivity with brokers, you’ll then learn the important aspects of financial markets. As you progress, you’ll learn to fetch financial instruments, query and calculate various types of candles and historical data, and finally, compute and plot technical indicators. Next, you’ll learn how to place various types of orders, such as regular, bracket, and cover orders, and understand their state transitions. Later chapters will cover backtesting, paper trading, and finally real trading for the algorithmic strategies that you've created. You’ll even understand how to automate trading and find the right strategy for making effective decisions that would otherwise be impossible for human traders. By the end of this book, you’ll be able to use Python libraries to conduct key tasks in the algorithmic trading ecosystem. Note: For demonstration, we're using Zerodha, an Indian Stock Market broker. If you're not an Indian resident, you won't be able to use Zerodha and therefore will not be able to test the examples directly. However, you can take inspiration from the book and apply the concepts across your preferred stock market broker of choice.

Who is this book for?

If you are a financial analyst, financial trader, data analyst, algorithmic trader, trading enthusiast or anyone who wants to learn algorithmic trading with Python and important techniques to address challenges faced in the finance domain, this book is for you. Basic working knowledge of the Python programming language is expected. Although fundamental knowledge of trade-related terminologies will be helpful, it is not mandatory.

What you will learn

  • Use Python to set up connectivity with brokers
  • Handle and manipulate time series data using Python
  • Fetch a list of exchanges, segments, financial instruments, and historical data to interact with the real market
  • Understand, fetch, and calculate various types of candles and use them to compute and plot diverse types of technical indicators
  • Develop and improve the performance of algorithmic trading strategies
  • Perform backtesting and paper trading on algorithmic trading strategies
  • Implement real trading in the live hours of stock markets
Estimated delivery fee Deliver to Canada

Economy delivery 10 - 13 business days

Can$24.95

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 28, 2020
Length: 542 pages
Edition : 1st
Language : English
ISBN-13 : 9781838989354
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Canada

Economy delivery 10 - 13 business days

Can$24.95

Product Details

Publication date : Aug 28, 2020
Length: 542 pages
Edition : 1st
Language : English
ISBN-13 : 9781838989354
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Can$ 197.97
Learn Algorithmic Trading
Can$61.99
Machine Learning for Algorithmic Trading
Can$73.99
Python Algorithmic Trading Cookbook
Can$61.99
Total Can$ 197.97 Stars icon
Banner background image

Table of Contents

12 Chapters
Handling and Manipulating Date, Time, and Time Series Data Chevron down icon Chevron up icon
Stock Markets - Primer on Trading Chevron down icon Chevron up icon
Fetching Financial Data Chevron down icon Chevron up icon
Computing Candlesticks and Historical Data Chevron down icon Chevron up icon
Computing and Plotting Technical Indicators Chevron down icon Chevron up icon
Placing Regular Orders on the Exchange Chevron down icon Chevron up icon
Placing Bracket and Cover Orders on the Exchange Chevron down icon Chevron up icon
Algorithmic Trading Strategies - Coding Step by Step Chevron down icon Chevron up icon
Algorithmic Trading - Backtesting Chevron down icon Chevron up icon
Algorithmic Trading - Paper Trading Chevron down icon Chevron up icon
Algorithmic Trading - Real Trading Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1
(9 Ratings)
5 star 66.7%
4 star 0%
3 star 22.2%
2 star 0%
1 star 11.1%
Filter icon Filter
Top Reviews

Filter reviews by




Anil Kumar Das Dec 10, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Book delivered on time .Highly recommend this book to anyone start in the python language for trading .
Amazon Verified review Amazon
Ajit Nair Oct 05, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Nothing to dislike !! Highly recommend d for domain specific programming and conceptual exposition to the topic !!!
Amazon Verified review Amazon
jml Sep 09, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Overview:Python Algorithmic Trading Cookbook starts with a gentle introduction to the power of Pandas and moves logically through the process of handling online trades. The book then demonstrates the procedural flow of automated trading, very useful if you’re new to the process. “Recipes” provide deep detail about the steps and terms involved, and subsequent chapters expand on familiarizing the reader with both the Python and investing terms and concepts. A light but readable treatment of the math behind indicators like trend, volatility, and volume analysis is also included with the sections demonstrating each of these tools. Order placement and handling are covered along with recipes for technical trades such as bracketing and stop-loss and lessons on pre-testing and performing actual trades. Appendices describe account setup for the services mentioned in the text as well as some useful strategy hints and reminders.Hits:You don’t need to have a lot of prior knowledge about financial markets to get the concepts and framework presented here. The math’s presented in easily-handled chunks and the author provides references for those who want to dive in deeper. If you’re not familiar with concepts like backtesting and paper trading, they’re made clear using short, comprehensible explanations.Misses:It looks like some chapters rely on specific GUI or at least graphics packages being installed, and it would be nice if more details were available regarding those requirements. I’d also like to see some information regarding trade and account security as those topics are integral to today's trading environments.Conclusion:A solid buy if you want to get into online stock markets and need to understand algorithmic trading. It’s not a trading textbook but if you have even a minimal understanding of how trading works, you’ll get up and running fast by following the recipes and explanations in this book.
Amazon Verified review Amazon
Karl Bateman Nov 24, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book! I'm fairly new to python, and I am able to follow the book with ease.
Amazon Verified review Amazon
Raj Dec 13, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have experience with Python and Data Analysis, but no experience with algorithmic trading. I would say anyone with little programming knowledge of Python can enjoy this book as it provides coding examples for all the concepts it explores.The author has dedicated a section to explain trading strategies which I cant wait to try out in real world with my brokerage account.With over 500 pages of content and detailed codebase on GitHub, this would be a fantastic read if you are an analyst or algorithmic trading enthusiast with an understanding of financial markets and an interest in trading strategies. You should also find value as an investment professional who aims to leverage Python to make better decisions.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela