100% found this document useful (3 votes)
1K views156 pages

Step by Step Automation Using Zerodha Api Python Version

Uploaded by

Rasel more
This chapter discusses variables in Python. It explains how to declare input variables, take user input using the input function, and identify the different types of variables and type casting in Python.

Copyright:

© All Rights Reserved

Available Formats

Download as PDF, TXT or read online on Scribd
Download as pdf or txt
100% found this document useful (3 votes)
1K views156 pages

Step by Step Automation Using Zerodha Api Python Version

Uploaded by

Rasel more
This chapter discusses variables in Python. It explains how to declare input variables, take user input using the input function, and identify the different types of variables and type casting in Python.

Copyright:

© All Rights Reserved

Available Formats

Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 156

ACKNOWLEDGEMENTS

I would like to thank all my mentors, especially Mr. Vihan Singh.


I would like to also sincerely thank interns of Fox Trading Solutions, who have
helped me in writing this book.
The book cover is designed by Snehil Agrawal and the creator should always be
acknowledged.
PREFACE
This book is a concise summary of our years of work in Algorithmic Trading,
creating algorithmic solutions for buying and selling instruments based on your
wonderfully created complex or simple yet extremely elegant strategies. We
have just tried to share a gist of it in this book Titled “Algorithmic Trading using
Zerodha's KiteConnect API in Python”.
Throughout this book, we will take you through a journey from a beginner to an
experienced Algorithmic Trader with basic knowledge in python, Algorithmic
trading, and trading strategies. We will introduce the reader to the basics of
python necessary for Algorithmic Trading. We will introduce the reader with
enough python to have a comfortable understanding of this entire course.
The world of the stock market attracts every person some time or another by its
glitter of easy earning and quick money. Nevertheless, soon they have to
understand the stock markets are not all rosy and there are high risks and losses
also. However, the thing about Algorithmic Trading is that we can assign this
task of buying and selling instruments to an algorithm, which will make the
readers' tasks more manageable and let the reader focus only on building
automated trading strategies instead of execution. Which by the way we are
experienced in doing, and it is time for you to sit back and let algorithms trade
on your behalf.
CONTENTS
1. Introduction
1.1 Introduction
1.2 Installation & Setting of Python
1.3 Install Pip
1.4 Setting of Jupyter Notebook
1.5 Working with Jupyter Notebook
2. Variables
2.1 Input variables
2.2 User Input
2.3 Types of variables
2.4 Printing a variable
2.5 Identify variable type
2.6 Type Casting
3. Strings
3.1 Introduction
3.2 Splitting a string
3.3 Slicing a string
3.4 Concatenate String
3.5 String Formatting
4. Operators
4.1 Arithmetic, Assignment, Comparison operators
4.2 Logical and Identity operator
5. Conditional Statement
5.1 If
5.2 If Else
5.3 Elif
5.4 NestedIf
6. Loop
6.1 For
6.2 While
6.3 Continue & Pass
6.4 Break
7. List
7.1 Introduction to list
7.2 Add & Remove items in list
8. Tuple
8.1 What is Tuple
8.2 Operation in Tuple
9. Introduction to Dictionary
9.1 Loop through Dictionary
9.2 Add/Remove items in Dictionary
10. Functions
10.1 Introduction to Function
10.2 Default parameter & Written Statement
10.3 Lambda Function/ Anonymous Function
11. Classes & Objects
11.1 Object Oriented Programming
11.2 Class
11.3 Implementation of Objects in Python
12. NumPy
12.1 NumPy
13 . Pandas
13.1 Data Frame & Series
13.2 Indexing
14. Data Visualization
14.1 Matplotlib
14.2 Seaborn
14.3 Plotting
15. What is API
15.1 API
15.2 How to interact with API
16. Zerodha API
16.1 Getting Started With KiteConnect
16.2 Create a Trading Application
16.3 Access Token generation
16.4 Installing KiteConnect
16.5 Get Historical data
16.6 Fetching Instrument token
16.7 Streaming Trick Data
16.8 Placing order
16.9 Cancel order
16.10 Order History
17. Technical Indicators & Price Action techniques
17.1 Import Technical Indicator from Library
17.2 Coding technical indicators
17.2.1 MACD
17.2.2 Bollinger Band
17.2.3 Average True Range(ATR)
17.2.4 Relative Strength Index(RSI)
17.2.5 Average Directional Index (ADX)
17.2.6 Supertrend
17.2.7 Chaikin Money Flow(CMF)
17.2.8 Ichimoku Cloud
17.2.9 On-Balance Volume
17.3 Price Action Techniques
17.3.1 Doji
17.3.2 Hammer
17.3.3 Shooting Star
17.3.4 Marubozu
18. Handling Streaming Tick Data
18.1 Starting Streaming Data to CSV
18.2 Converting Ticks to Candles
18.3 Sample strategy
CHAPTER 1

Introduction
1.1 Introduction To Python
Python is a modern day programming language. It is the most simplified version
of human-machine interaction.
Python’s official description:
It has efficient high-level data structures and a simple but effective approach to
object-oriented programming. Python's elegant syntax and dynamic typing,
together with its interpreted nature, make it an ideal language for scripting and
rapid application development in many areas on most platforms.
Features of python
● Simple
● Open Source
● Easy syntax
● Powerful Looping
● High-Level Language
● Object-Oriented

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
1.2 Installing & Setting Up Python
Visit https://www.python.org/downloads/ and download the latest version. The
current version of python is 3.8.2 and it gets updated pretty fast. Double click on
exe to install.
Please make sure you check the option Add Python 3.8.2 to the PATH.If you
forget to add python 3.8.2 to path, go to environment variables in windows and
add python to PATH. This will enable you to access it from the command
prompt.
The default interface which will be installed along with python is called IDLE. It
runs the code line by line and is the least preferred option to work with. There
are various IDEs which support python. The simplest and the most powerful
being Jupyter notebook, which will be discussed further.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
1.3 Installing PIP
PIP is the package installer for python. By using pip you can install any library
you need. The library is a collection of pre-coded files which serves a purpose,
they are built for specific purposes and can be used within our code.
The module PIP comes pre-installed in most of the python installations. If it is
not there, you can install it by following the below mentioned steps.
To install PIP, you need to download the get-pip.py file from
https://bootstrap.pypa.io/get-pip.py .
Open this link in any browser and save it by pressing Ctrl+S . The directory in
which you are saving this file should be the same as the one in which python is
installed.
After saving the file, go to command prompt and write the following code

python get-pip.py

This will install PIP.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
1.4 Installing Jupyter Notebook
It is a web-based interpreter, used to run python code. It holds the title of being
the simplest interpreter.Installing a Jupyter notebook is pretty simple.
Go to command prompt and run the following code:

pip install Jupyter notebook

This will install your Jupyter notebook.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
1.5 Working With Jupyter Notebook
Working with a Jupyter notebook is pretty easy. Just open the command prompt
and type Jupyter notebook. Surprisingly, it will open in a browser window.
To create a new notebook, click New on the top right corner and select python3
from there.This will open up a new file.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 2

Variables
2.1 Input Variables
Variables in Python are used to store data or collections of data. Python uses
dynamic casting to store data which means unlike languages like C, C++, etc.
There is no need to initialize variables with data type in python.
Example:
stoploss = 5
target=50
stock_name = ‘Reliance’
exchange = “NFO”
Rules for variable declarations in python -
● A variable name must start with a letter or the underscore character
● A variable name cannot start with a number
● A variable name can only contain alpha-numeric characters and
underscores
● Variable names are case-sensitive

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
2.2 User Input
Input can be provided to the program in python using the “input” function. We
can ask the user to input values if they aren’t pre-defined
Example:
stoploss = input()
A predefined message can also be outputted while taking the input by putting
that message as a function parameter.
Example:
a = input(“What is your stop loss?”)
Python always takes inputs as a string. Hence to use the input as a number, i.e. to
perform addition, subtraction, multiplication, etc, you need to convert the input
to a number, using an appropriate function like int(), float(), etc. Depending on
the type of variable you want.
Example
a = int(input()) #for integers
b = float(input()) #for numbers with decimal
point

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
2.3 Types Of Variables
There are various types of variables:
1. Integer:

Integers are whole number, without decimal points


Example: 1,2,3,4
2. Float:

Numbers with decimal points


Example: 1.258, 2.587
3. Strings: Strings are a combination of characters. In simple terms, it’s
a word.

Example: ‘Nifty’,’Banknifty’.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
2.4 Printing A Variable
The print function gives a standard output. The output is displayed on the screen
which helps us to verify our input.

Example of a print statement:


stoploss=5
print(“your stoploss is”,stoploss)
Output:
your stoploss is 5

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
2.5 Identify Variable Type
The type of variable you have entered.How it works:
quantity = 1
print(type(quantity))
Output :
<class int>

Example 1:
price=52.35
print(type(price) )
Output:
<class float>

Example 2:
stock_name =’Reliance’ ’
print(type(stock_name))
Output:
<class str>

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
2.6 Type Casting
We can convert one data type into another by using typecasting. Below shown is
how it works
price = 50.50
print(type(price))
Output:
<class float>
We can convert this price which is in float to an integer by using the following
command
print(int(price))
Output:
50
In a similar way, int, float, string can be converted from one to another. The only
exception is strings formed using characters cannot be converted to int or float.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 3

Strings
3.1 Introduction
A string is a sequence of characters. Strings are basically just a bunch of
words.Strings form an integral part of every program. Whenever we define any
variable, we have to use strings. Strings are defined in quotes. There are 3 types
of quotes in python.
Single quotes
Writing your string in single quotes is like ‘What is your stoploss’
Double quotes
Strings in double quotes work exactly the same way as strings in single quotes.
Example: “What is your stoploss”
Triple Quotes
Strings in triple quotes are used as comments. Comments basically mean you
don’t want to include them in the program. They are in simple english and
placed above almost every line of code. They help us understand how the code is
structured and what the code is doing.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Indentation:
Indentation refers to the spaces at the beginning of a code line. Indentation is
very important in python. Python uses indentation to indicate a block of code.
Indentation is used by clicking either one tab or four spaces and using only one
of them at a time for better code management.
Example-
if 10>5:
print (‘Ten is greater than five’)
Python will give you an error if you skip the indentation.

Example-
if 10>5:
print (‘Ten is greater than five’)
In this example, it will show you a Syntax error.

Alias:
In python, Alias is an alternate name for referring to the same thing.
Create an alias with the ‘as’ keyword while importing:
import numpy as np
import pandas as pd
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
3.2 Splitting A String
We can split the string into various parts. The splitting can be done using any
character or special character.
Example:
stock_name=”Reliance-NFO”
print(stock_name.split(“-”))
Output:
['Reliance', 'NFO']

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
3.3 Slicing A String
We can slice the string using the length function. The first step in slicing a string
is finding its length.
How it works:
stock_name=”Reliance-NFO’
print(len(stock_name))
Output:
12
If we want to slice string, we can do it
Example 1:
string=”Price of Reliance is 1400”
print(string[9:17])
Output:
Reliance
Example 2:
print(string[21:])
Output:
1400
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
3.4 Concatenate String
String concatenation means merging 2 strings into one string. How it works:
stock_name = "Reliance"
exchange="NFO"
Combined_name=print(stock_name+exchange)
Output:
RelianceNFO

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
3.5 String Formatting
We use it to format a string in a manner we want.
price = 1400
stock_name = “Reliance”
print('{0} is trading at Rs
{1}'.format(stock_name, price ))
Output:
Reliance is trading at Rs 1400.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 4

Operators
4.1 Arithmetic, Assignment, Comparison Operators
Arithmetic operators in python are used with numeric values to perform
common mathematical operations.

Operator Name Example

+ Addition x + y

- Subtraction x - y

* Multiplication x * y

/ Division x / y

% Modulus x % y

** Exponentiation x ** y

// Floor division x // y

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Assignment operators in python are used to assign values to variables.

Operator Example Same As

= x = 5 x = 5

+= x += 3 x = x + 3

-= x -= 3 x = x - 3
*= x *= 3 x = x * 3

/= x /= 3 x = x / 3

%= x %= 3 x = x % 3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x = x & 3

|= x |= 3 x = x | 3

^= x ^= 3 x = x ^ 3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Comparison operators in python are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x > y

< Less than x < y


>= Greater than or equal to x >= y

<= Less than or equal to x <= y


4.2 Logical And Identity Operator
Logical operators in python are used to combine conditional statements.

Operator Description Example

and Returns True if both statements x < 5 and x < 10


are true

or Returns True if one of the x < 5 or x < 4


statements is true

not Reverse the result, returns False if not(x < 5 and x <
the result is true 10)

Identity operators in python are used to compare the objects, not if they are
equal, but if they are actually the same object, with the same memory location

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Operator Description Example

is Returns True if both variables are the x is y


same object

is not Returns True if both variables are not x is not y


the same object
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 5

Conditional Statements
5.1 If
If statements are conditional statements in python which roughly translates to
english as - if the condition is true then execute this code block. If the condition
of an if returns a boolean True then the code block of that if is executed.
Example-
stock_price = 5
if (stock_price>2):
print(“greater”)
Output-
greater

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
5.2 IF Else
If Else are one of the most common keywords in any language which describe
the conditional changes during the execution of the code. The code block of if is
executed if the condition of if is true but if it is not true then the code block of
else is executed.
Example:
stock_price = 5
if(stock_price=4):
print("stock_price is 4")
else:
print("stock_price is not equal to 4")
Output:
stock_price is not equal to 4

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
5.3 ElIf
Mostly the if statement cannot hold all the possible conditions of an outcome.
Hence the elif or as we speak elseif; condition is checked. The number of elif
can be more than one for an if statement.
Example:
stock_price = 4
if(stock_price>5):
print("Big")
elif(stock_price<5):
print("Small")
else:
print("Match")
Output:
Small

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
5.4 Nested If
If statements are used for conditional executions in python. If-elif-elif- -else is
the basic structure of any Nested If statements. It basically follows a top down
approach, first the if condition is tested, if that is true then the if block statements
are executed but if not then the first elif statement is tested and executions are
performed based on its truth value. After all if and elif are tested and none are
true then at last the else statement is executed.
Example:
x = 4
if(x>4):
print(“greater”)
if(x<4):
print(“less”)
else:
print(“equal”)
Output:
Equal

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

CHAPTER 6

Loops
6.1 For Loop
For loop is used for iterations in python. It is used to iterate over lists, tuples,
generators etc.Unlike other languages like C, C++ etc, python does not support
numeric for loops by default. To iterate over a range of numbers one has to
create a range generator by specifying starting, ending, and jump value to the
range function.
Example :
for x in range(1,5,2):
print(x)
Output :
1
3
For loops can also iterate over predefined arrays and tuples by using the “in”
keyword.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Example:
a = [“a”,”b”,”c”]
for x in a:
print(x)
Output:
a
b
c
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
6.2 While
While loops are similar to for loops in the manner that they repeat the same code
lines over and over again but different in the sense that they are not statically
driven. It means that the looping condition of while loops can change during the
execution of the loop unlike in the case of for loops where the driving condition
remains same during the entire execution.

Example -
x = 4
while x>1:
print(x)
x-=1
Output-
4
3
2

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
6.3 Continue & Pass
Just like any other programming language the “continue” statement is used to
skip the current loop state in a python for or while loop.
Example-
for x in range(8):
if(x%2):
continue
else:
print(x)
Output-
1
3
5
7

Execution blocks in python whether they belong to if, elif, else, try, except,
function, class, etc can never be empty. But due to certain conditions we need to
keep them empty for say, testing, development or code requirement. Hence to
keep an execution statement from performing any execution “pass” keyword is
used to tell the compiler to do nothing if this keyword is encountered.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Example-
A = 10
if(A>10 or A<10):
pass
else:
print(“A is 10”)
Output-
A is 10
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

6.4 Break
Break statement is executed when they meet a condition, which is checked in the
loop during every iteration. Break statement ends the loop and executes the
code, written after the loop.
Simply known as coming out of the loop.
Example of Break-
i=1
while(i<10):
print(i)
If (i==5):
break
i=i+1
Output-
1
2
3
4

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 7

Lists
7.1 Introduction To List
Lists in python contain one or more than types of data at linear indices starting
from 0. In Python lists can be defined by using the keyword “list” or by directly
placing the data of the list into square brackets “[ ]” .
Example-
a = [1,2,3,4]
print(type(a))
Output-
<class 'list'>
The data inside a list can be accessed by providing the index of the data to the
list inside square brackets or by iterating over it inside a for loop.
Example-
a = [1,2,3,4]
print(a[-1])
Output-
4

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Example-
a = [1,2,3]
for x in a:
print(x)

Output-
1
2
3

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
7.2 Add & Remove Items In List
Items can be added to a list using the append function. Append function adds an
item to the list by increasing it length then inserting it at the end.
Example -
a = [1,2,3,4]
print(a)
a.append(0)
print(a)
Output -
[1, 2, 3, 4]
[1, 2, 3, 4, 0]
Data can also be added to the list by assigning data to a pre existing index of a
list.
Example-
a = [1,2,3,4]
print(a)
a[2] = 7
print(a)
Output-
[1, 2, 3, 4]
[1, 2, 7, 4]
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Data can also be removed by list:


Example:
a = [1,2,3,4]
a.pop(3) #it will remove 3rd element from list
print(a)
Output-
[1, 2, 3]

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 8
Tuple
8.1 What Is Tuple
A tuple is an immutable sequence of Python objects. Tuples are sequences, just
like lists. The differences between tuples and lists are, the tuples cannot be
changed unlike lists and tuples use parentheses “( )”, whereas lists use square
brackets “[ ]”.
Tuples are statically created hence they cannot be mutated once they are created
and this makes using them faster than lists. They can be created using
parentheses and commas for separating objects.
Example -
a = ('a',1,"hello")

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
8.2 Operation In Tuple

Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', Repetition


'Hi!')

3 in (1, 2, 3) True Membership

for x in (1, 2, 3): 1 2 3 Iteration


print(x),

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 9
Dictionary
9.1 Loop Through Dictionary
Dictionary is similar to a list in the manner that it stores data at indices too but
different in the sense that in a dictionary we have to define the index at which we
need to place data, there is no function like append, for a dictionary and indices
can be string too.
A dictionary has two variables per entry - a key and a value. They can be
accessed using the items function over a dictionary object. The items function
returns a list of tuples containing key value pairs which can be iterated over
using a for loop.
Example-
a = {'one':1,"apple":"banana",8:9}
for k,v in a.items():
print(f"{k} -> {v}")
Output-
one -> 1
apple -> banana
8 -> 9

_________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
9.2 Add/Remove Items In Dictionary
Adding data to a dictionary is similar to adding data to a list at an index, but
there is a small difference that in a dictionary you can create any index
irrespective of its order or data type.
Example-
a = {'one':1,"apple":"banana",8:9}
a['newData'] = 4
print(a)
Output-
{'one': 1, 'apple': 'banana', 8: 9, 'newData': 4}
Deletion operation in dictionaries is also very simple. It is done using the “del”
keyword.

Example-
a = {'one':1,"apple":"banana",8:9}
del a['one']
print(a)
Output-
{'apple': 'banana', 8: 9}

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 10
Functions
10.1 Introduction To Function
Function is a block of code that performs a specific task. We can do many things
using functions. Some of the advantages of using functions are listed below:
1. Code Reusability: We are writing an application in Python where we need to
perform a specific task in several places of our code, assuming that we need to
write 10 lines of code to do that specific task. It would be better to write those 10
lines of code in a function and just call the function wherever needed.
2. Improves Readability: By using functions for frequent tasks you make your
code structured and readable. It would be easier for anyone to look at the code,
and helps us in making tidier code.
3. Avoid redundancy: When you no longer repeat the same lines of code
throughout the code.

There are two types of functions in Python:


1. Built-in functions: These functions are predefined in Python and we
need not to declare these functions before calling them.
Example:
square = math.pow(a, 2)

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

2. User defined functions: The functions which we create in our code


are user-defined functions. The computation() function that we have
created in the below example is a user-defined function.

User Defined Function Template-


def <functionName> ( [<parameter1>,
[<parameter2>, …]]):
<functionCode>
return [<resultVariable>]
Example-
def computation(a):
square = a*a
return square
Usage-
x = float(input("Var1: "))
y = computation(x)
print(y)
Output
Var1: 2
4
Note:If you don’t include a return statement in your function,the interpreter will
automatically return
None value.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
10.2 Default Parameter & Written Statement
Parameters are the variables we send to a function for its execution. In python
we can sometimes set that data to a default value so as to use that function with
or without passing that variable. Such parameters with default values are called
default parameters.
Example -
def add(a,b,d=0):
c = a+b+d
return c
x = add(3,4)
print(x)
y = add(3,4,5)
print(y)
Output-
7
12

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
10.3 Lambda Functions/ Anonymous Functions
Anonymous functions are functions without names. Lambda keyword is used to
create anonymous functions. Lambda function does not include a “return”
statem-ent, it always contains an expression which is returned.
Example-
g=lambda x: x*x*x # here x is the argument and
x*x*x is the expression
g(2)
Output:
8

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 11
Classes & Objects
11.1 Object Oriented Programming
Python as a language supports Object Oriented Programming (hereafter called as
OOP). OOP is an approach for writing programs in which data and behaviour are
blinded together as classes and the instances of these classes are defined objects.
The OOP is based on certain concepts which are briefly defined as below.
1. Data Abstraction – It is the way of representing the essential features
without including the background details and explanations.
Example:
Your car is a great example of abstraction. You can start a car by turning the key
or pressing the start button. You don't need to know how the engine is getting
started, what all components your car has. The car internal implementation and
complex logic is completely hidden from the user.
2. Data Hiding – Data hiding ensures exclusive data access to class members
and protects object integrity by preventing unintended or intended changes .Data
hiding insulates the data from the straight access by the program.
Example:
You have an account in a XYZ Bank.You can only transfer or check money in
your account.You can’t edit the money in your account. This is called Data
Hiding.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

3. Data Encapsulation – It is the process of wrapping up the data and its


associated functions along with it. It also implements abstraction in a way.
4. Inheritance – It is the capability of one class to inherit properties from
another class. The class which is inherited is called as the base class and the
class which inherits from another class is called as derived class. The derived
class has all the properties of base class by default.
5. Polymorphism – It is the ability of a data to be processed in more than one
form. It is the property by which the same message can be sent to objects of
several classes.
For example: 2+3 results in 5 but ‘A’ + ‘B’ results in ‘AB’. The same operator
symbol ‘+’ is able to distinguish between the two operations depending upon the
data type it is working upon.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
11.2 Class
A Class is a way to bind the data and its associated functions together. For
instance, consider a fruit having characteristics, taste, colour and its size. When
a class is defined, memory is allocated for its member functions and they are
stored in the memory. When an object is created, separate memory space is
allocated for its data members. All objects work with one copy of the member
function shared by all. The declaration of a class involves three things:
1. Data members which are the data type properties to describe the
characteristics of a class.
2. Member functions are the set of operations to be carried out to objects of
that class. They are referred to as class interfaces.
3. Access levels that control access to members from within the program.
These access levels are private, public or protected. Depending upon the access
level of a class member, access to it is allowed or denied.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
11.3 Implementation Of Objects In Python
The objects are implemented through member functions called as methods and it
is given a unique name to make it identifiable in a unique manner. Once a class
has been defined, its objects can be created like any other variable, using the
class name as type specifier.
Example-
class data:
def __init__(self, symbolName, market):
self.symbol = symbolName
self.market = market
self.ltp = []
def newLtp(ltp):
self.ltp.append(ltp)
nifty = data(‘Nifty’,’NSE’)
bankNifty = data(‘Nifty Bank’,
’NSE’)
gold = data(‘GOLD APR FUT’, ’ NFO’)
nifty.newLtp(51341.12)
nifty.newLtp(51341.45)
nifty.newLtp(51341.44)
gold.newLtp(37920.14)
gold.newLtp(37921.55)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Here data is the class and nifty, bankNifty, gold are the objects of that class. The
class stores the symbols’ name, its market and list to store all its ltp values.
_____________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 12

NumPy
12.1 NumPy
NumPy is an inbuilt library, which is used for numerical computations. It is
basically used because of its computational efficiency in terms of speed.
Numerical python (NumPy) supports multidimensional arrays over which you
can easily apply mathematical operations. It is a single (homogeneous) data type.
NumPy’s arrays class is “ndarray,” also referred to as “numpy.array”
Installing NumPy-
!pip install numpy
Once NumPy is installed, import it into your application by adding the “import”
keyword.

Example-
a=[1,2,3,4,5]
b=[2,4,6,6,8]
npa_array=np.array(a)
npb_array=np.array(b)
npa_array+npb_array
Output-
array([3,6,9,10,13])

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Accessing array Elements: Indexing


Example-
a=np.array([[1,3,4,5],[2,3,4,7]])
b=a[0]
b
Output-
array([1,3,4,5])

Where
This function returns elements chosen from x or y depending on condition.
numpy.where(condition[, x, y])
here,
condition : Where True, yield x, otherwise yield y.
x : yielded when condition is True
y : yielded when condition is False
If the yielding elements x and y are not provided the True and False are yielded
as the placeholders.
Example -
a = np.array(range(10))
np.where(a < 5, a, 10*a)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Output -
array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90])

Random
This function returns random integers from low (inclusive) to high (exclusive). It
returns random integers from the “discrete uniform” distribution of the specified
dtype in the “half-open” interval [low, high). If high is None (the default), then
results are from [0, low).
numpy.random.randint(low,high=None, size= None ,
dtype=int)

here,
low : range starting
high : range ending
size : size of output array
dtype : data type of output

Example -
np.random.randint(5,10,(3,4))

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Output -
array([[6, 8, 7, 9],
[5, 5, 5, 9],
[9, 8, 6, 7]])

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 13

Pandas
13.1 Data Frame & Series
Pandas is a fast, powerful, flexible and easy to use open source data analysis and
manipulation tool, built on top of the Python programming language.
A Data frame is a two-dimensional data structure, in which data is aligned in a
tabular fashion in rows and columns.
Pandas Series is a one-dimensional labeled array capable of holding data of any
type. The axis labels are collectively called indexes. Pandas Series is nothing but
a column in an excel sheet.
Installing Pandas-
pip install pandas
Series and DataFrames can be created with different data inputs :-
1.list
2.dictionary
3.scalar
4.ndarrays (Import NumPy while working with ndarray)

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Series Example of ndarray:-


import pandas as pd
import numpy as np
np_name=np.array([‘abc’,’xyz’,’lmn’,’pqr’])
s_name=pd.Series(np_name)
print(s_name)
Output-
1 Abc
2 xyz
3 lmn
4 pqr
DataFrame example of ndarray-
import pandas as pd
import numpy as np
np_name=np.array([‘abc’,’xyz’,’lmn’,’pqr’])
df_name=pd.Dataframe(np_name)
print(df_name)
Output-
0 abc
1 xyz
2 lmn
3 pqr
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Dataframe Example -
import pandas as pd
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
print(df)
Output-
col1 col2
0 1 3
1 2 4
Series Example-
import pandas as pd
data = ['g','e','e','k','s']
ser = pd.Series(data)
print(ser)
Output-
0 g
1 e
2 e
3 k
4 s
dtype: object

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
13.2 Indexing
A pandas series is a simple array and can be indexed similarly. Each row and
column in a pandas dataframe is a seperate pandas series hence they can be
indexed like an array too.
Pandas Series Indexing-
import pandas as pd
a = [4,5,6]
s = pd.Series(a)
print(s[1])
Output-
5

Pandas Dataframe Indexing-


Indexing in python can be done along rows and columns. By default the square
bracket indexing on pandas is reserved for column indexing. To index across
rows “loc” and “iloc” functions are used on the pandas dataframe.
loc gets rows with particular labels from the index.
iloc gets rows at particular positions in the index (so it only takes integers).

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Example-
import pandas as pd
data = {'Name':['Tommy', 'nicky', 'krishna', 'jacky'], 'Age':[23,
21, 18, 28], 'Qualification':['Msc', 'MA', 'MCA', 'Phd']}
df=pd.DataFrame(data, index= ['a', 'b', 'c', 'd'])
print(df['Name'])

Output-
a Tommy
b nicky
c krishna
d jacky
Name: Name, dtype: object

Example-
import pandas as pd
data={'Name':['Tommy','nicky', 'krishna', 'jacky'], 'Age':[23, 21,
18, 28],'Qualification':['Msc', 'MA', 'MCA', 'Phd']}
df=pd.DataFrame(data, index= ['a', 'b', 'c', 'd'])
print(df.iloc[2])
Out put -
Name krishna
Age 18
Qualification MCA
Name: c, dtype: object

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Example-
import pandas as pd
data={'Name':['Tommy','nicky','krishna',
'jacky'],'Age':[23, 21, 18, 28],'Qualification':
['Msc', 'MA', 'MCA', 'Phd']}
df=pd.DataFrame(data,index=['a','b','c','d'])
print(df.loc['d'])
Output-
Name jacky
Age 28
Qualification Phd
Name: d, dtype: object
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 14

Data Visualization

Data visualisation forms an integral part of any strategy as we formulate most of


the strategies seeing charts.
We would be using two inbuilt libraries namely matplotlib and seaborn which
helps us in visualising data.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
14.1 Matplotlib:
Matplotlib library is used for plotting graphs in python.
Installation: pip install matplotlib
Import:
import matplotlib.pyplot as plt
( Matplotlib is a toolkit, Pyplot is an interactive way to use matplotlib)
To save-
plt.savefig(‘filename.png’)
Different type of graphs:
1. Line
2. Bar
3. Histogram
4. Scatter
5. Pie

Line graph
plt.plot()
plt.title() - show the title

Bar graph
plt.bar() - vertical bar graph
plt.barh() - Horizontal bar graph
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Histogram
plt.hist()
Scatter Plot
plt.scatter()
Pie Chart
plt.pie()
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
14.2 Seaborn:
Seaborn library in python is used for data visualization. It is a high level
interface for drawing/plotting graphs.
Installation:
pip install seaborn
Import:
import seaborn as sns

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
14.3 Plotting:
A) Statistical Relationship (Numerical vs Numerical):
Understanding the relationship between the numerical variables and how, in turn,
these relationships depend on other variables is called Statistical Analysis.
Function used - sns.replot()
By default it is scatter plot
Example-
sns.replot(x=’col1’,y=’col2’,data=dataframe,hue=’‘,size=’‘,row=
Hue is for color, size is for number of size.

B) Categorical Relationship (Categorical vs Numerical):


Function used- sns.catplot()
It is figure level function like replot() and has many axes level functions such
as:
Scatter plot (default) - stripplot() and swarmplot()
stripplot() or catplot(x=’col1’, y=’col2’,kind = “strip”)
Data is plotted in the form of strips with jitter.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
swarmplot() or catplot(x=’col1’, y=’col2’, kind=’swarm’)
To prevent the overlapping.
Distribution plot- Distribution plot used with large dataset for better data
visualization.
1.boxplot() or catplot(x=’col1’, y=’col2’,kind = “box”)
2.boxenplot() or catplot(x=’col1’,y=’col2’,kind=’boxen’)
3.violinplot() or catplot(x=’col1’, y=’col2’, kind=’violin’)
Estimate plot- barplot() or catplot(x=’col1’, y=’col2’,kind = “bar”) - Data is
plotted in the form of bars.
C) Distribution of data:

For Univariate analysis- sns.displot()

For Bivariate analysis- sns.jointplot()

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 15

API
15.1 Application Program Interface
An application program interface (API) is a set of routines, protocols, and tools
for building software applications. Basically, an API specifies how we interact
with other computers over the internet. A good API makes it easier to develop a
program by providing all the building blocks. A programmer then puts the
blocks together.
Popular API Examples
1. Google Maps API
2. YouTube APIs
3. Flickr API
4. Twitter APIs
5. Amazon Product Advertising API

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
15.2 How To Interact With API
Most modern API’s are HTTP based and can be accessed using a GET or PUT
request to the base url of the API website. Generally these APIs require a secret
token for user authentication and input data with correct variable name and
value. In python this data can be serialised using python dictionaries.
These requests are sent in python using the requests library.
Installing requests-
!pip install requests
Importing the library-
import requests
Sending request-
response = requests.<GET|POST>
(url_name,data_dictionary)
Extracting Data-
data = response.text
jsonData = response.json()

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 16

Zerodha API
16.1 Getting Started With Kite Connect
Kite Connect is Zerodha’s API for web based trading. It is used to automate
trading strategies based on user’s requirements. Zerodha is one of the pioneers in
API trading in India. Kite connect is a general API which can be manipulated
using various languages like Python, Java, Ruby etc. But in this course we will
be working on python to implement our strategies using Zerodha’s Kite Connect
API.
To start working with Kite Connect we have to first create a developers account
on Zerodha’s platform - https://developers.kite.trade/signup
We also have a list of classes which are present in KiteConnect SDK, they can
be used as a reference while building any trading code. The link for KiteConnect
python SDK is https://kite.trade/docs/pykiteconnect/v3/
Although we don't need to go through the entire documentation right now
because that is what we will be covering in the further chapters but, to have a
full knowledge of what is possible through this API one can always refer to it.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
16.2 Create A Trading Application
Kite connect offers a feature to have multiple sets of strategies being
implemented at the same time through the same account but in isolation from
each other. Hence to start building one of them we need to create a Trading
Application on Kite Connect.
Before you can start building the Trading Application you need to have a
developer account first. If you don't have one then refer the earlier modules as to
how to create one. After creating a developer account you need to log in to it.
Once it is done and you are on the Kite Connect Dashboard, you will see a
“Create New App button on the top right part of your screen (Click it). Then you
will have an option to create a Connect account and a Publisher (Free account).
For trading you have to go with the paid Connect Account. Next fill in your App
Name, Zerodha Client ID, App Icon(optional) and a Description.
Redirect URL is the website where once you authenticate, Zerodha will send
your request token. If you are a developer and know how to configure it then
that's good. But if you don't then you don't need to worry. Just put
https://127.0.0.1 in it.
Postback URL is simply a tracking mechanism to get information about the
requests you make to the Kite Server. So if you don't know how to configure it
then leave it empty for now.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Once the App is created, you can click on it to edit it’s settings and to retrieve
your API key and API secret which is important for the next part. Also you can
enable the Historical API from there if it isn’t already enabled to get Historical
data from Kite Connect API.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
16.3 Installing KiteConnect Library
kiteconnect is the python wrapper of Kite Connect API. You can install by
running this code in you command line -
pip install --upgrade kiteconnect

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
16.4 Access Token Generation
Access token is used to authenticate requests made to the Kite Connect API.
Retrieving an access token is a multi step process. It requires several other inputs
to be retrieved, which include -
1. api_key
2. api_secret
3. user_id
4. password
5. pin
6. request_token

Api Key and Api Secret are retrieved from the edit section of the Zerodha app
after you have signed in, as we did in the previous modules. User Id,password
and PIN are the ones which you use for logging into your developers account.

Request Token is generated using the first five elements and using it along with
the others we will then generate the Access Token. Although you can keep using
the request token for all your request authentications, the problem with it is that
it expires very quickly and then you have to complete the entire tedious
procedure of retrieving the new request token for your requests to
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

the Kite Connect API. Hence to solve this problem, as soon as you get your
request token you must generate your access token using it which doesn't expire
for a long time.
Importing Libraries -
from kiteconnect import KiteConnect
from selenium import webdriver from kiteconnect
import KiteConnect
from selenium import webdriver
import time
import os
Selenium is the library which we will be using to automate our work like
authentication, key retrieval etc. The time library as the name suggests is used
for manipulating time processes using python.
Os library is used to manipulate the operating system using python.
def autologin():
token_path = "api_key.txt"
key_secret = open(token_path,'r').read().split()
kite = KiteConnect(api_key=key_secret[0])
service =
webdriver.chrome.service.Service('./chromedriver')
service.start()
options = webdriver.ChromeOptions()
options.add_argument('--headless')
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

options = options.to_capabilities()
driver = webdriver.Remote(service.service_url,
options)
driver.get(kite.login_url())
driver.implicitly_wait(10)
username=driver.find_element_by_xpath('/html/body/div[1]/d
/div[1]/div/div/div[2]/form/div[1]/input')
password=driver.find_element_by_xpath('/html/body/div[1]/d
/div[1]/div/div/div[2]/form/div[2]/input')
username.send_keys(key_secret[2])
password.send_keys(key_secret[3])
driver.find_element_by_xpath('/html/body/div[1]/div/div[2]
iv/div/div[2]/form/div[4]/button').click()
pin=driver.find_element_by_xpath('/html/body/div[1]/div/di
1]/div/div/div[2]/form/div[2]/div/input')
pin.send_keys(key_secret[4])
driver.find_element_by_xpath('/html/body/div[1]/div/div[2]
iv/div/div[2]/form/div[3]/button').click()
time.sleep(10)
request_token=driver.current_url.split('=')
[1].split('&action')[0]
with open('request_token.txt', 'w') as the_file:
the_file.write(request_token)
driver.quit()
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

This code is used to automate the authentication process and to retrieve the
request token. We start by retrieving the key secret which you have saved inside
api_token.txt file in the same folder as this code. We then create a KiteConnect
object which we will use to interact with the kite connect API. To start the
authentication process we create a selenium webdriver object for chrome, pass
the location of the webdriver file, set it to be headless (which means that the
entire process will take place in the background) and begin it’s service. Once the
service is up and running, we request the login url from the KiteConnect object,
redirect to that url and the username and password field on that page. Once this
is done, selenium passes your username and password to it, finds the submit
button, clicks it and redirects to the page asking for the pin. This process is then
repeated for PIN. Once the authentication is complete, your Request Token
comes as a part of your redirect url which is then retrieved from it and saved to a
file name 'request_token.txt'.
Although this process takes place in the background, knowing these steps is
important so that in case one day Zerodha changes some aspects of the login
procedure then you can adjust your code accordingly. But for now you can use
this code to retrieve your Request Token.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Setting Up Environment Variables


autologin()
request_token =
open("request_token.txt",'r').read()
key_secret=open("api_key.txt",'r')
key_secret=read().split( )
The autologin function which we earlier prepared is of no use unless it is called.
Hence we call that function and create a 'request_token.txt' file containing our
Request Token. We then read the request token and Key Secret from their
corresponding files.
Retrieving Access Token
autologin()
request_token =
open("request_token.txt",'r').read()
key_secret =
open("api_key.txt",'r').read().split()
Everytime we need to communicate with the Kite Connect API we need a
KiteConnect object, but we don't need to create one every time. Although in this
case we created our KiteConnect object inside a function, so we are creating a
new KiteConnect object outside it to be used further. We pass the Key Secret to
create the KiteConnect object and then use this object to generate a session using
Request Token and Key Secret. Once the session is created, we can retrieve our
Access Token from it and save it in a file to be used later to interact with the Kite
Connect API.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
16.5 Getting Historical Data
The term Historical data refers to the data for the time which has gone.
Explaining it with the help of an example, if the market is open the time now
being 11:00 AM. The data which we can fetch from historical API is till 11:00
AM.
It can also be used while we are computing values of certain technical indicators
as it eradicates the need for storing tick data. It helps us with accurate resampled
data even in case our internet gets disconnected as the database is maintained on
Zerodha’s side.The code for fetching historical data is as follows:-
def fetchOHLC(ticker,interval,duration):
"""
extracts historical data and outputs in the form
of dataframe
"""
instrument =
instrumentLookup(instrument_df,ticker)
data = pd.DataFrame( kite.historical_data
(instrument, dt.date.today() - dt.timedelta(duration),
dt.date.today(),interval))
data.set_index("date",inplace=True)
return data
fetchOHLC("BANKNIFTY20SEPFUT","5minute")
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
16.6 Fetching Instrument Token
Instrument token as the name suggests is a token used instead of stock name to
avoid mistakes while typing the stock name. It is provided and maintained by
Zerodha, the instrument tokens are updated on a daily basis for NFO scripts as
they expire every week.
We need to fetch instrument tokens from kite before starting our algorithm. The
command for fetching instrument token is as follows:-
instrument_dump = kite.instruments("exchange_name")

Example to find instrument token of a particular stocks is given below


instrument_dump = kite.instruments("NFO")
instrument_df = pd.DataFrame(instrument_dump)

def instrumentLookup(symbol):
return
instrument_df[instrument_df.tradingsymbol==symbol].instrume

instrumentLookup(‘RELIANCE’)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Output:
11577090
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
16.7 Streaming Tick Data
Kite Connect uses a KiteTicker object to connect to zerodha’s socket under the
hood. We need to initialize the KiteTicker objects using API_KEY and
ACCESS_TOKEN. After initialization we need to set various functions with
predefined number of inputs to the object to be executed at various events,
during and after socket connection. These functions include -
1. on_ticks(ws, ticks) - It is executed when the live data is
fetched by the socket.

○ ws - It is the reference to the KiteTicker object


○ ticks - It contains all the data that you receive from the socket

2. on_close(ws, code, reason) - It is triggered when connection to


the socket is closed. Decisions to reconnect or not can be taken
inside this function.

○ ws - It is the reference to the KiteTicker object


○ code - It is the status code received from the socket as to why
the connection was closed.
○ reason - Readable reason for connection closing.

3. on_error(ws, code, reason) - This function is executed when


connection is closed with an error, you can choose to log it or
program it to move further cleanly.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

○ ws - It is the reference to the KiteTicker object


○ code - It is the status code received from the socket as to why
the connection was closed.
○ reason - Readable reason for connection closing.

4. on_connect(ws, response) - This is primarily the first function


which is executed after a connection is established with the
socket. The symbols that you need to get live data from need to
be called using the subscribe function inside this function.

○ ws - It is the reference to the KiteTicker object


○ response - Response received from server on successful
connection.

5. on_message(ws, payload, is_binary) - This is an optional


function which is used to handle messages received from the
server.

○ ws - It is the reference to the KiteTicker object


○ payload - Raw response from the server, received either in
binary or non binary form based on the is_binary value.
○ is_binary - Boolean to check if response(payload) is binary
type.

6. on_reconnect(ws, attempts_count) - It is another optional


function which describes the reconnection of the socket
connection.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

○ ws - It is the reference to the KiteTicker object


○ attempts_count - Current reconnect attempt number.

7. on_noreconnect(ws) - Reverse of on_reconnect function, i.e. it is


executed when reconnection attempts exceed reconnect_tries.

○ ws - It is the reference to the KiteTicker object

8. on_order_update(ws, data) - This is triggered when there is an


order update for the connected user. Although this function is
also optional, yet it can be used to prevent calling the get status
function to check whether or not the order has been updated.

○ ws - It is the reference to the KiteTicker object


○ data - Response of the server when there is an order update for
the connected user.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Sample Socket Code -


# Socket object of kiteconnect
from kiteconnect import KiteTicker
from pprint import pprint
import time
# Initialise
kws = KiteTicker("your_api_key", "your_access_token")

def on_ticks(ws, ticks):


# Callback to receive ticks (live socket data).

pprint(ticks)
def on_connect(ws, response):
# Callback on successful connection.
# Subscribe to a list of
instrument_tokens
# (RELIANCE and ACC here)
ws.subscribe([5633, 738561])
# Set RELIANCE to tick in `full` mode
i.e. to get more data
# for that instrument_tokens
ws.set_mode(ws.MODE_FULL, [738561])
def on_close(ws, code, reason):
# On connection close stop the event
loop.# Reconnection will not happen after executing
ws.stop()`
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

try:
print(f'Server Error {code} : {reason}')
time.sleep(2)
except KeyboardInterrupt:
ws.stop()
# Assign the callbacks.
kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_close = on_close
# Infinite loop on the main thread.
# Nothing after this will run.
kws.connect()

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
16.8 Placing Order
Orders can be placed using the KiteConnect object using the place_order
function. The place_order function takes several inputs based on the order you
want to place and returns an order id, if the order has been placed. The syntax of
place_order is -
place_order( variety, exchange, tradingsymbol, transaction_type, quantity,
product, order_type, price=None, validity=None, disclosed_quantity=None,
trigger_price=None, squareoff=None, stoploss=None, trailing_stoploss=None,
tag=None)

Variety

VARIETY_AMO
VARIETY_BO
VARIETY_CO
VARIETY_REGULAR
Exchange
EXCHANGE_BFO
EXCHANGE_BSE
EXCHANGE_CDS
EXCHANGE_MCX
EXCHANGE_NFO
EXCHANGE_NSE
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

Trading Symbol - Retrieve using the instruments() function


Transaction Type
TRANSACTION_TYPE_BUY
TRANSACTION_TYPE_SELL
Product
PRODUCT_BO
PRODUCT_CNC
PRODUCT_CO
PRODUCT_MIS
PRODUCT_NRML
Order Type
ORDER_TYPE_LIMIT
ORDER_TYPE_MARKET
ORDER_TYPE_SL
ORDER_TYPE_SLM
Validity
VALIDITY_DAY
VALIDITY_IOC
Tag - (Optional) String used to represent a request to the server and is received in
the response in order to create asynchronous behaviour possible if applicable.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
16.9 Cancel Order
Cancel order function takes order id and variety as input of the order you want to
cancel. Order ID can be retrieved after you place an order or through the orders
book.
kite.cancel_order(variety, order_id)

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
16.10 Order History
Order history of all orders can be retrieved using the orders function which
contains the status including order id, order status etc for all your orders of the
day.
kite.orders()
Order details of a specific order can be retrieved using the order_history function
which takes the order id of which you want the details for in this function.
kite.order_history(‘order_id’)

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 17

Technical Indicators & Price Action


techniques

As the name suggests, we used some techniques to derive some meaningful


inferences from stock market data. There are various types of indicators which
are namely Momentum based, volatility based, mean reversion based.
Technical Indicators are mathematical calculations based on historical price
volume or open interest information to predict asset price direction. The
important part of technical analysis is based on analyzing trends, chart patterns,
etc.
Popular technical indicators include:
● MACD: Moving Average Convergence Divergence
● Bollinger Bands
● Average True Range(ATR)
● RSI: Relative Strength Index
● ADX: Average Directional Index
● Supertrend
● Chaikin Money Flow Index(CMF)
● Ichimoku Cloud
● On-Balance Volume(OBV)
In this section, we would be covering how to code technical indicators using
talib library.Installing pyti is pretty simple. It can be installed by the following
command:-
!pip install talib
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
17.1 Import Technical Indicator From Library
The github repository link for talib is https://github.com/mrjbq7/ta-
lib/tree/master/talib

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
17.2 Coding Technical Indicators
17.2.1 MACD
The Moving Average Convergence/Divergence oscillator (MACD) is one of the
simplest and most effective momentum indicators. The MACD turns two trend-
following indicators, moving averages into a momentum oscillator by
subtracting the longer moving average(26) from the shorter one(12).
A signal line is also calculated, which is again a moving average (typically 9
periods) of the MACD line calculated as per the above step.
The MACD line cutting signal line from below signals a bullish period and the
former cutting the latter from above signals a bearish period. This is called a
crossover strategy.
In python:
#using talib module
from talib import MACD
macd,macdsignal,macdhist= MACD(df['close'],
fastperiod=12, slowperiod=26,signalperiod=9)
# another implementation
def MACD(DF,a,b,c):
"""function to calculate MACD
typical values a(fast
MA)=12;b(slow A)=26;c(signal
line MA window) =9
"""
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

df = DF.copy()
df["MA_Fast"]=df["close"].ewm(span=a,
min_periods=a).mean()
df["MA_Slow"]=df["close"].ewm(span=b,
min_periods=b).mean()
df["MACD"]=df["MA_Fast"]-df["MA_Slow"]
df["Signal"]=df["MACD"].ewm(span=c,min_periods=c).mean()
df.dropna(inplace=True)
return df
17.2.2 Bollinger Bands
It is a volatility based indicator. It comprises two lines plotted n (n is typically 2)
standard deviations from an m period simple moving average line (m is typically
20). As volatility increases, the band widens.
In python:
#using talib module
from talib import BBANDS
upperband, middleband, lowerband =
BBANDS(df['close'], timeperiod=5, nbdevup=2,
nbdevdn=2, matype=0)
# another implementation
def bollBnd(DF,n):
df = DF.copy()
df["MA"]= df['close'].rolling(n).mean()
#df["MA"]=
df['close'].ewm(span=n,min_periods=n).mean()
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

df["BB_up"]=df["MA"]+2*
df['close'].rolling(n).std(ddof=0)
#ddof=0 is required since we want to take the
standard deviation of the population and not sample
df["BB_dn"]=df["MA"]-2*df['close'].
rolling(n).std(ddof=0)
#ddof=0 is required since we want to take the
standard deviation of the population and not sample
df["BB_width"] = df["BB_up"] - df["BB_dn"]
df.dropna(inplace=True)
return df

bollBnd(df,10)

17.2.3 ATR(Average True Return)


It is a volatility based indicator. It takes into account the market movement of
each day in either direction and averaging them out. It focuses on the total price
movement and conveys how vividly the market is swinging as it moves.
Traders generally use Bollinger Bands and ATR in conjunction as they approach
volatility differently and are complementary.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

In python:
#using talib module
from talib import ATR
real = ATR(df['high'], df['low'], df['close'],
timeperiod=14)
# another implementation
def atr(DF,n):
"""
function to calculate True Range and
Average True Range
"""
df = DF.copy()
df['H-L']=abs(df['high']-df['low'])
df['H-PC']=abs(df['high']-
df['close'].shift(1))
df['L-PC']=abs(df['low']-
df['close'].shift(1))
df['TR']=df[['H-L','H-PC','L-
PC']].max(axis=1,skipna=False)
df['ATR'] =
df['TR'].ewm(com=n,min_periods=n).mean()
return df['ATR']

atr(df,10)

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

17.2.4 Relative Strength Index


RSI is a momentum oscillator that measures the speed and change of price
movements. RSI value oscillates between 0 and 100 with values above 70,
indicating that the asset has now reached overbought territory. Values below 30
signify oversold territory.
In python:
#using talib module
from talib import RSI
real = RSI(df['close'], timeperiod=14)
# another implementation
def rsi(df, n):
delta = df["close"].diff().dropna()
u = delta * 0
d = u.copy()
u[delta > 0] = delta[delta > 0]
d[delta < 0] = -delta[delta < 0]
u[u.index[n-1]] = np.mean( u[:n])
#first value is average of gains
u = u.drop(u.index[:(n-1)])
d[d.index[n-1]] = np.mean( d[:n])
d = d.drop(d.index[:(n-1)])
rs=u.ewm(com=n,min_periods=n).mean()
/d.ewm(com=n, min_periods=n).mean()
return 100 - 100 / (1+rs)
rsi(df,10)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

17.2.5 Average Directional Index


It is a way of measuring the strength of underlying trends. Its values range from
0 to 100 and quantify the strength of a trend as per below:
● 0-25 absent or weak trend
● 25-50 strong trend
● 50-75 very strong trend
● 75-100 extremely strong trend
ADX is non-directional, meaning the ADX value makes no inference about the
direction of the trend but only the strength of the trend. The calculation involves
finding both positive and negative directional movement and then calculating the
smoothed average difference of these.
In python:
#using talib module
from talib import ADX
real=ADX(df['high'],df['low'], df['close'],
timeperiod=14)
#another implementation
def adx(DF,n):
"function to calculate ADX"
df2 = DF.copy()
df2['H-L']=abs(df2['high']-df2['low'])
df2['H-PC']=abs(df2['high']-
df2['close'].shift(1))
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

df2['L-PC']=abs(df2['low']-
df2['close'].shift(1))
df2['TR']=df2[['H-L','H-PC','L-
PC']].max(axis=1,skipna=False)
df2['DMplus']=np.where((df2['high']-
df2['high'].shift(1))>(df2['low'].shift(1)-
df2['low']), df2['high'] -df2['high'].shift(1),0)

df2['DMplus']=np.w
<0,0,df2['DMplus'])
df2['DMminus']=np.where((df2['low'].shift(1)-
df2['low'])>(df2['high']-
df2['high'].shift(1)),df2['low'].shift(1)-
df2['low'],0)

df2['DMminus']=np.where(df2['DMminus']
<0,0,df2['DMminus'])
TRn = []
DMplusN = []
DMminusN = []
TR = df2['TR'].tolist()
DMplus = df2['DMplus'].tolist()
DMminus = df2['DMminus'].tolist()
for i in range(len(df2)):
if i < n:
TRn.append(np.NaN)
DMplusN.append(np.NaN)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

DMminusN.append(np.NaN)
if i == n:
Rn.append(df2['TR'].rolling(n).sum().tolist()
[n])
DMplusN.append(df2['DMplus'].rolling(n).sum().to
[n])
DMminusN.append(df2['DMminus'].rolling(n).sum().
[n])
elif i > n:
TRn.append(TRn[i-1]- (TRn[i-1]/n)
+ TR[i])
DMplusN.append(DMplusN[i-1] -
(DMplusN[i-1]/n) +DMplus[i])
DMminusN.append(DMminusN[i-1] -
(DMminusN[i-1]/n) + DMminus[i])
df2['TRn'] = np.array(TRn)
df2['DMplusN']=np.array(DMplusN)
df2['DMminusN']=np.array(DMminusN)
df2['DIplusN']=100*
(df2['DMplusN']/df2['TRn'])
df2['DIminusN']=100*
(df2['DMminusN']/df2['TRn'])
df2['DIdiff']=abs(d2['DIplusN']-
df2['DIminusN'])
df2['DIsum']=df2['DIplusN']+df2['DIminusN']
df2['DX']=100*
(df2['DIdiff']/df2['DIsum'])
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

ADX = []
DX = df2['DX'].tolist()
for j in range(len(df2)):
if j < 2*n-1:
ADX.append(np.NaN)
elif j == 2*n-1:
ADX.append(df2['DX'][j-
n+1:j+1].mean())
elif j > 2*n-1:
ADX.append(((n-1)*ADX[j-1] +
DX[j])/n)
df2['ADX']=np.array(ADX)
return df2['ADX']

adx(df,10)

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

17.2.6 Supertrend
As the name suggests, ‘Supertrend’ is a trend-following indicator just like
moving averages and MACD (moving average convergence divergence). It is
plotted on prices and their placement indicates the current trend.
The indicator is easy to use and gives an accurate reading about an ongoing
trend. It is constructed with two parameters, namely period and multiplier. The
default values used while constructing a super-indicator are 10 for average true
range or trading period and three for its multiplier.
The code consists of 3 modules the first two being EMA and ATR which are
required to compute Supertrend values.
In python:
def EMA(df, base, target, period, alpha=False):
con= pd.concat([df[:period]
[base].rolling(window=period).mean(),
df[period:][base]])
if (alpha == True):
df[target] = con.ewm(alpha=1 / period,
adjust=False).mean()

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

else:
df[target] = con.ewm(span=period,
adjust=False).mean()
df[target].fillna(0, inplace=True)
return df
def ATR(df, period, ohlc=['open', 'high', 'low',
'close']):
atr = 'ATR_' + str(period)
if not 'TR' in df.columns:
df['h-l'] = df[ohlc[1]] - df[ohlc[2]]
df['h-yc'] = abs(df[ohlc[1]] -
df[ohlc[3]].shift())
df['l-yc'] = abs(df[ohlc[2]] -
df[ohlc[3]].shift())
df['TR'] = df[['h-l', 'h-yc', 'l-
yc']].max(axis=1)
df.drop(['h-l', 'h-yc', 'l-yc'],
inplace=True, axis=1)

EMA(df, 'TR', atr, period, alpha=True)


return df

def SuperTrend(df, period, multiplier, ohlc=['open',


'high', 'low', 'close']):

ATR(df, period, ohlc=ohlc)


atr = 'ATR_' + str(period)
st = 'ST' #+ str(period) + '_' +
str(multiplier)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

stx = 'STX' # + str(period) + '_' +


str(multiplier)
# Compute basic upper and lower bands
df['basic_ub'] = (df[ohlc[1]] + df[ohlc[2]]) /
2 + multiplier * df[atr]
df['basic_lb'] = (df[ohlc[1]] + df[ohlc[2]]) /
2 - multiplier * df[atr]
# Compute final upper and lower bands
df['final_ub'] = 0.00
df['final_lb'] = 0.00
for i in range(period, len(df)):
df['final_ub'].iat[i]= df['basic_ub'].iat[i]
if df['basic_ub'].iat[i] < df['final_ub'].iat[i-1] or
df[ohlc[3]].iat[i - 1] > df['final_ub'].iat[i - 1]
else df['final_ub'].iat[i - 1]
df['final_lb'].iat[i]= df['basic_lb'].iat[i]
if df['basic_lb'].iat[i] > df['final_lb'].iat[i - 1]
or df[ohlc[3]].iat[i - 1] < df['final_lb'].iat[i - 1]
else df['final_lb'].iat[i - 1]

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

# Set the Supertrend value


df[st] = 0.00
for i in range(period, len(df)):
df[st].iat[i] = df['final_ub'].iat[i] if
df[st].iat[i - 1] == df['final_ub'].iat[i - 1] and
df[ohlc[3]].iat[i] <= df['final_ub'].iat[i] else
df['final_lb'].iat[i] if df[st].iat[i-
1]==df['final_ub'].iat[i - 1] and
df[ohlc[3]].iat[i]>df['final_ub'].iat[i] else
df['final_lb'].iat[i] if
df[st].iat[i -1] == df['final_lb'].iat[i
- 1] and df[ohlc[3]].iat[i] >=
\df['final_lb'].iat[i] else
\df['final_ub'].iat[i] if df[st].iat[i - 1] ==
df['final_lb'].iat[i - 1]
and df[ohlc[3]].iat[i] <
\df['final_lb'].iat[i] else 0.00
# Mark the trend direction up/down
df[stx] = np.where((df[st] > 0.00),
np.where((df[ohlc[3]] < df[st]), 'down', 'up'),
np.NaN)
# Remove basic and final bands from the columns
df.drop(['basic_ub', 'basic_lb', 'final_ub',
'final_lb'], inplace=True, axis=1)
df.fillna(0, inplace=True)
return df
SuperTrend(df,7,3)

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

17.2.7 Chaikin Money Flow (CMF)


Chaikin Money Flow (CMF) developed by Marc Chaikin is a volume-weighted
average of accumulation and distribution over a specified period. The standard
CMF period is 21 days. The principle behind the Chaikin Money Flow is the
nearer the closing price is to the high, the more accumulation has taken place.
Conversely, the nearer the closing price is to the low, the more distribution has
taken place. If the price action consistently closes above the bar's midpoint on
increasing volume, the Chaikin Money Flow will be positive. Conversely, if the
price action consistently closes below the bar's midpoint on increasing volume,
the Chaikin Money Flow will be a negative value.
In python:
def chaikin_money_flow(close_data, high_data,
low_data, volume, period):
"""
Chaikin Money Flow Formula:
CMF = SUM[(((Cn - Ln) - (Hn - Cn)) / (Hn -
Ln)) * V] / SUM(Vn)
"""
catch_errors.check_for_input_len_diff(
close_data, high_data, low_data, volume)
catch_errors.check_for_period_error(close_data,
period)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

close_data = np.array(close_data)
high_data = np.array(high_data)
low_data = np.array(low_data)
volume = np.array(volume)
cmf=[sum((((close_data[idx+1-period:idx+1]-
low_data[idx+1-period:idx+1])-(high_data[idx+1-
period:idx+1]-
close_data[idx+1- period:idx+1]))/(high_data[idx+1
period:idx+1]-low_data[idx+1-
period:idx+1]))*volume[idx+1-
period:idx+1])/sum(volume[idx+1- period:idx+1])for
idx in range(period-1, len(close_data))]

cmf=fill_for_noncomputable_vals(close_data,
cmf)
return cmf

17.2.8 Ichimoku Cloud


The Ichimoku Cloud is a collection of technical indicators that show support and
resistance levels, as well as momentum and trend direction. It does this by taking
multiple averages and plotting them on the chart. It also uses these figures to
compute a "cloud" which attempts to forecast where the price may find support
or resistance in the future.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

def conversion_base_line_helper(data, period):


"" The only real difference between TenkanSen
and KijunSen is the period value"""
catch_errors.check_for_period_error(data,
period)
cblh = [(np.max(data[idx+1-period:idx+1])
+np.min(data[idx+1- period:idx+1])) / 2 for idx in
range(period-1, len(data))]
cblh = fill_for_noncomputable_vals(data, cblh)
return cblh

def tenkansen(data, period=9):


""" TenkanSen (Conversion Line)
Formula:
(H + L) / 2 :: default period=9
"""
ts = conversion_base_line_helper(data, period)
return ts

def kijunsen(data, period=26):


"""
KijunSen (Base Line) Formula:
(H + L) / 2 :: default period=26
"""
ks = conversion_base_line_helper(data, period)
return ks
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

def chiku_span(data):
"""
Chiku Span (Lagging Span)
Formula: Close shifted back 26 bars
"""
cs = data[25::]
return cs

def senkou_a(data):
"""
Senkou A (Leading Span A) Formula:
(TenkanSen + KijunSen) / 2 :: Shift Forward 26
bars
"""
sa = (tenkansen(data) + kijunsen(data)) / 2
# shift forward
shift_by = np.repeat(np.nan, 26)
sa = np.append(shift_by, sa)
return sa

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
def senkou_b(data, period=52):
"""
Senkou B (Leading Span B)
Formula: (H + L) / 2 :: default period=52 ::
shifted forward 26 bars
"""
sb = conversion_base_line_helper(data, period)
shift_by = np.repeat(np.nan, 26)
sb = np.append(shift_by, sb)
return sb

17.2.9 On Balance Volume


On-balance volume (OBV) is a technical trading momentum indicator that uses
volume flow to predict changes in stock price. Joseph Granville first developed
the OBV metric in the 1963 book Granville's New Key to Stock Market Profits.
Granville believed that volume was the key force behind markets and designed
OBV to project when major moves in the markets would occur based on volume
changes.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
def on_balance_volume(close_data, volume):
"""
On Balance Volume.
Formula:
start = 1
if CLOSEt > CLOSEt-1
obv = obvt-1 + volumet
elif CLOSEt < CLOSEt-1
obv = obvt-1 - volumet
elif CLOSEt == CLOSTt-1
obv = obvt-1
"""
catch_errors.check_for_input_len_diff(close_data,
volume)
obv = np.zeros(len(volume))
obv[0] = 1

for idx in range(1, len(obv)):


if close_data[idx] > close_data[idx-1]:
obv[idx] = obv[idx-1] + volume[idx]

elif close_data[idx] < close_data[idx-1]:


obv[idx] = obv[idx-1] - volume[idx]
elif close_data[idx] == close_data[idx-1]:
obv[idx] = obv[idx-1]
return obv
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
17.3 Price Action Techniques
Price action is a branch of technical analysis concerning price bar patterns. This
trading philosophy asset price action with chart patterns. The key terms in these
concepts are Support, Resistance, Higher Highs, Lower Lows, Swing Trading,
Momentum trading etc (Google them if you already don’t know about them).
Price action based indicators predict the price action.
Some popular price action based candlestick patterns include:
● Doji
● Hammer
● Shooting star
● Marubozu
17.3.1 Doji
A candle in which open and close are apparently the same i.e. length of the
candle is zero is called a doji. It looks like a cross or an inverted cross, the size
of the wicks is generally irrelevant.
Doji represents uncertainty on both the buyers as well as sellers. It can signal
both trend reversal or breakout on the pattern in which it occurs.
In python:
#using talib module
from talib import CDLDOJI
integer = CDLDOJI(open, high, low, close)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

#another implementation
def doji(ohlc_df):
"""
returns dataframe with doji candle col
umn
"""
df = ohlc_df.copy()
avg_candle_size = abs(df["close"] -
df["open"]).median()
df["doji"] = abs(df["close"] - df["open"])
<= (0.05 * avg_candle_size)
return df

17.3.2 Hammer
A candle in which the lower wick is at least twice the size of the body. Body can
be red or green (bearish or bullish). Upper wick should be small or non-existent.
This candle is viewed as a bullish reversal candlestick when occurring during a
downtrend.
In python:
#using talib module
from talib import CDLHAMMER
integer = CDLHAMMER(open, high, low, close)
def hammer(ohlc_df):
df = ohlc_df.copy()
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
df["hammer"]=(((df["high"]- df["low"]) >3*
(df["open"]-df["close"]))&((df["close"] -
df["low"])/(0.001+df["high"]-df["low"])>0.6) &
((df["open"]-df["low"])/(.001 + df["high"] -
df["low"])>0.6))&(abs(df["close"]- df["open"] ) > 0.1*
(df["high"] - df["low"]))
return df
hammer(df)

17.3.3 Shooting Star


A candle in which the upper wick is at least twice the size of the body, just
opposite of the hammer. Body can be red or green (red is preferred). Lower wick
should be small or non existent.
This candle is viewed as a bearish reversal candlestick when occurring during an
uptrend.
In python:
#using talib module
from talib import CDLSHOOTINGSTAR
integer = CDLSHOOTINGSTAR(open, high, low, close)
def shooting_star(ohlc_df):
"""
returns dataframe with shooting star
candle column
"""
df = ohlc_df.copy()

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
df["sstar"] = (((df["high"] - df["low"])>3*
(df["open"] - df["close"])) & ((df["high"] -
df["close"])/(.001 + df["high"] - df["low"]) > 0.6)
& ((df["high"] - df["open"])/(.001 +
df["high"] - df["low"]) > 0.6))
& (abs(df["close"] - df["open"]) > 0.1*
(df["high"] - df["low"]))
return df
shooting_star(df)

17.3.4 Marubozu
A candle which is long and sturdy with a very small or non existent wick. Body
can be red or green with green signifying bulls in complete control whereas red
signifies bears to have complete control.
This candle can signal both breakout or trend reversal depending on where it
occurs in the chart.
In python:
#using talib module
#using talib module
from talib import CDLMARUBOZU
integer = CDLMARUBOZU(df['open'],
df['high'], df['low'], df['close'])

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

#another implementation
def maru_bozu(ohlc_df):
"""returns dataframe with maru bozu candle
column"""
df = ohlc_df.copy()
avg_candle_size = abs(df["close"] -
df["open"]).median()
df["h-c"] = df["high"]-df["close"]
df["l-o"] = df["low"]-df["open"]
df["h-o"] = df["high"]-df["open"]
df["l-c"] = df["low"]-df["close"]
df["maru_bozu"] = np.where((df["close"] -
df["open"]>2*avg_candle_size)&(df[["h-c","l-
o"]].max(axis=1)
<0.005*avg_candle_size),"maru_bozu_green",np.where((df["open"]-
close "] > 2*avg_candle_size) & (abs(df[["h-o","l-
c"]]).max(axis=1)<0.005* avg_candle_size
),"maru_bozu_red",False))

df.drop(["h-c","l-o","h-o","l-
c"],axis=1,inplace=True)
return df
maru_bozu(df)

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 18

Handling Streaming Tick Data

What we receive from any broker is tick data. Tick data basically corresponds to
any transaction made by buyer and seller.
Zerodha generally streams 1-2 ticks per second. These ticks are useful when we
are into HFT, but we need to re-sample it for our use.
Re-sampling is the process of converting granular data into a higher time frame
by storing them in a database and converting it into the timeframe we require.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
18.1 Streaming Data To CSV
Live data for any stock is retrieved from zerodha using sockets. We can stream
live data using Zerodha’s KiteTicker object. While streaming the data we can
store all ticks for all tokens and store it in a dictionary. After the market closes or
when the current time exceeds the endtime of the code then we can convert this
dictionary into pandas DataFrame and save them into separate csv files
containing time stamps and their corresponding last traded price at that moment.

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

18.2 Converting Ticks To Candles


Tick data that we receive from the socket is often not used as is, but it needs to
be converted into candle data to determine OHLC and then be used for further
calculations. The easiest way to convert this tick data into candle data is to store
all the ltp values during the candle duration and once that duration is over then
we can convert all the last traded prices into open, high, low and close; then we
can finally discard the old ltp data and start recording new data for the next
candle.

# importing necessary modules
from selenium import webdriver
from selenium.webdriver.support.ui import
WebDriverWait
from selenium.common.exceptions import
TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import
expected_conditions as EC
import datetime
from kiteconnect import KiteTicker
from kiteconnect import KiteConnect
import pandas as pd
import time
from furl import furl

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

# class for single instrument data


class pocket:
def __init__(self,instrumentToken):
self.instrumentToken = instrumentToken
self.ltp = []
self.open = []
self.high = []
self.low = []
self.close = []
self.timeStamp = []
self.newData = 0
# Function to convert ltp data to ohlc
def ohlc(self):
if(self.ltp):

self.timeStamp.append(datetime.datetime.now())
self.open.append(self.ltp[0])
self.high.append(max(self.ltp))
self.low.append(min(self.ltp))
self.close.append(self.ltp[-1])
self.ltp = []
# Function to set ltp value
def setLtp(self,ltp):
self.ltp.append(ltp)
# Function to get candles dataframe
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
def getOhlc(self):
data = pd.DataFrame(data={
'timeStamp' : self.timeStamp,
'Open' : self.open,
'High' : self.high,
'Low' : self.low,
'Close' : self.close,
},columns=[
'timeStamp','Open','High','Low','Close'] )
data = data.set_index('timeStamp')
return data

# class to store all pocket data


class database:
def __init__(self, tokens,
startTime,delay):
self.pockets = {}
self.startTime = startTime
self.delay = delay
self.execution = startTime + delay
for token in tokens:
self.pockets[token] = pocket(token)

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
# Function to get pocket object by token number
def getPocket(self,token):
return self.pockets[token]
# Setting ltp value based on token
def setVal(self,token,ltp):
self.getPocket(token).setLtp(ltp)
# Function to check of candle time is
executed
def checkCandle(self):

if(datetime.datetime.now()>self.execution):
self.execution += self.delay
for token in self.pockets:
self.pockets[token].ohlc()
# Set the new candle to be
available
self.pockets[token].newData
= 1
# Function to get candles dataframe of token
def getOhlc(self,token):
return self.getPocket(token).getOhlc()
# Function to print dataframe of token
pocket
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

# if new candle is formed


def newCandle(self,token):
if(self.getPocket(token).newData):
self.getPocket(token).newData = 0
print('\n',token)
print(self.getOhlc(token))
# zerodha credentials
api_key = "your api_key"
api_secret = "your api_secret"
username = "your username"
password = "your password"
pin = "your pin"
request_token = "your request_token"
# function to wait for elements on page load for
selenium
def getCssElement( driver , cssSelector ):
return WebDriverWait( driver, 100
).until( EC.presence_of_element_located( (
By.CSS_SELECTOR, cssSelector ) ) )
#function to login to zerodha using selenium
def autologin():
kite = KiteConnect(api_key=api_key)
service =
webdriver.chrome.service.Service('./chromedriver')
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

service.start()
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options = options.to_capabilities()
driver =
webdriver.Remote(service.service_url, options)
driver.get(kite.login_url())
passwordField = getCssElement( driver ,
"input[placeholder=Password]" )
passwordField.send_keys( password )

userNameField = getCssElement( driver ,


"input[placeholder='User ID']" )
userNameField.send_keys( username )
loginButton = getCssElement( driver ,
"button[type=submit]" )
loginButton.click()
WebDriverWait(driver,
100).until(EC.presence_of_element_located((By.CLASS_NAME,
'twofa- value')))
pinField =
driver.find_element_by_class_name('twofa-
value').find_element_by_xpath(".//input[1]")
pinField.send_keys( pin )
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

loginButton = getCssElement( driver ,


"button[type=submit]" )
loginButton.click()
while True:
try:

request_token=furl(driver.current_url).args['request_token']
break
except:
time.sleep(1)
kite = KiteConnect(api_key=api_key)
data =
kite.generate_session(request_token,
api_secret=api_secret)
with open('access_token.txt', 'w') as
file:
file.write(data["access_token"])
driver.quit()

autologin()
# retrieving access token from saved file
access_token_zerodha =
open("access_token.txt",'r').read()
# Tokens to subscribe
# (RELIANCE and ACC here)
TOKENS = [738561, 5633]

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

# #creating kite connect object


kite = KiteConnect(api_key=api_key)
# # setting access token ti kite connect object
kite.set_access_token(access_token_zerodha)
# time at which code starts
STARTTIME = datetime.datetime.now()
#time at which code ends
ENDTIME
= datetime.datetime.now().replace(hour=15,minute=30,s
#duration of a candle
DELAY =
datetime.timedelta(hours=0,minutes=1,seconds=0)
# Initiating Database
DATABASE = database(TOKENS,STARTTIME,DELAY)
#wai-ts till start time
while datetime.datetime.now()<STARTTIME:
pass
#kite ticker object to receive data from zerodha
kws = KiteTicker(api_key, access_token_zerodha)
#function to run when data is coming from zerodha
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
def on_ticks(ws, ticks):
global DATABASE
#creating new candles based on execution
time
#recording current data to database for
all tickers
DATABASE.checkCandle()
for x in ticks:

DATABASE.setVal(x['instrument_token'],x['last_price'])
DATABASE.newCandle(x['instrument_token'])
#if current time is greater than ENDTIME
the stop the code
if(datetime.datetime.now()>ENDTIME):
print("Market is closed now...")
ws.stop()
#function to run when connection is established
to zerodha
def on_connect(ws, response):
# Callback on successful connect.
ws.subscribe(TOKENS)

#funcion to run on connection close


def on_close(ws, code, reason):
# On connection close stop the
main loop

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

# Reconnection will not happen after executing


`ws.stop()`
print(code)
print(reason)
ws.stop()
# Assign the callbacks.
kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_close = on_close
# Infinite loop on the main thread. Nothing after
this will run.
# You have to use the pre-defined callbacks to
manage subscriptions.
kws.connect()

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
18.3 Place Order Based On Strategy
This code is used to place orders based on a simple strategy. The strategy here is
that if we get 3 continuous increasing highs then we buy that stock and if we get
3 continuous decreasing lows then we sell that stock.
# importing necessary modules
from selenium import webdriver
from selenium.webdriver.support.ui import
WebDriverWait
from selenium.common.exceptions import
TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import
expected_conditions as EC
import datetime
from kiteconnect import KiteTicker
from kiteconnect import KiteConnect
import pandas as pd
import time
from furl import furl
# class for single instrument data
class pocket:
def __init__(self,instrumentToken):
self.instrumentToken = instrumentToken
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

self.ltp = []
self.open = []
self.high = []
self.low = []
self.close = []
self.timeStamp = []
self.newData = 0
# Function to convert ltp data to ohlc
def ohlc(self):
if(self.ltp):

self.timeStamp.append(datetime.datetime.now())
self.open.append(self.ltp[0])
self.high.append(max(self.ltp))
self.low.append(min(self.ltp))
self.close.append(self.ltp[-1])
self.ltp = []
# Function to set ltp value
def setLtp(self,ltp):
self.ltp.append(ltp)
# Function to get candles dataframe
def getOhlc(self):
data = pd.DataFrame(
data={
'timeStamp' : self.timeStamp,
'Open' : self.open,
'High' : self.high,
'Low' : self.low,
'Close' : self.close,
},
columns=
['timeStamp','Open','High','Low','Close']
)
data = data.set_index('timeStamp')
return data
# class to store all pocket data
class database:
def __init__(self,tokens,startTime,delay):
self.pockets = {}
self.startTime = startTime
self.delay = delay
self.execution = startTime + delay
for token in tokens:
self.pockets[token] = pocket(token)
# Function to get pocket object by
token number
def getPocket(self,token):
return self.pockets[token]
# Setting ltp value based on token
def setVal(self,token,ltp):
self.getPocket(token).setLtp(ltp)

# Function to check of candle time is


executed

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

def checkCandle(self):
if(datetime.datetime.now()>self.execution):
self.execution += self.delay
for token in self.pockets:
self.pockets[token].ohlc()
# Set the new candle to be
available
self.pockets[token].newData = 1
# Function to get candles dataframe of
token
def getOhlc(self,token):
return self.getPocket(token).getOhlc()
# Function to print dataframe of token
pocket
# if new candle is formed
def newCandle(self,token):
if(self.getPocket(token).newData):
self.getPocket(token).newData = 0
print('\n',token)
print(self.getOhlc(token))
# zerodha credentials
api_key = "your api_key"
api_secret = "your api_secret"

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

username = "your username"


password = "your password"
pin = "your pin"
# function to wait for elements on page load for
selenium
def getCssElement( driver , cssSelector ):
return WebDriverWait( driver, 100
).until( EC.presence_of_element_located( (
By.CSS_SELECTOR, cssSelector ) ) )
#function to login to zerodha using selenium
def autologin():
kite = KiteConnect(api_key=api_key)
service =
webdriver.chrome.service.Service('./chromedriver')
service.start()
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options = options.to_capabilities()
driver =
webdriver.Remote(service.service_url, options)
driver.get(kite.login_url())
passwordField = getCssElement( driver ,
"input[placeholder=Password]" )
passwordField.send_keys( password )
userNameField = getCssElement( driver ,
"input[placeholder='User ID']" )
userNameField.send_keys( username )
loginButton = getCssElement( driver ,
"button[type=submit]" )
loginButton.click()
WebDriverWait(driver,
100).until(EC.presence_of_element_located((By.CLASS_NAME,
'twofa- value')))
pinField =
driver.find_element_by_class_name('twofa-
value').find_element_by_xpath(".//input[1]")
pinField.send_keys( pin )
loginButton = getCssElement( driver ,
"button[type=submit]" )
loginButton.click()
while True:
try:

request_token=furl(driver.current_url).args['request_tok
break
except:
time.sleep(1)
kite = KiteConnect(api_key=api_key)
data =
kite.generate_session(request_token,
api_secret=api_secret)
with open('access_token.txt', 'w') as
file:

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

file.write(data["access_token"])
driver.quit()
autologin()
# retrieving access token from saved file
access_token_zerodha =
open("access_token.txt",'r').read()
# Tokens to subscribe
# (RELIANCE and ACC here)
TOKENS = [738561, 5633]
# #creating kite connect object
kite = KiteConnect(api_key=api_key)
# # setting access token ti kite connect object
kite.set_access_token(access_token_zerodha)
# time at which code starts
STARTTIME = datetime.datetime.now()
#time at which code ends
ENDTIME =
datetime.datetime.now().replace(hour=15,minute=30,second=0)
#duration of a candle
DELAY =
datetime.timedelta(hours=0,minutes=1,seconds=0)
# Initiating Database
DATABASE = database(TOKENS,STARTTIME,DELAY)

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

#waits till start time


while datetime.datetime.now()<STARTTIME:
pass

#kite ticker object to receive data from zerodha


kws = KiteTicker(api_key, access_token_zerodha)
#function to run when data is coming from zerodha
def on_ticks(ws, ticks):
global DATABASE
#creating new candles based on execution
time
#recording current data to database for
all tickers
DATAb BASE.checkCandle()
for x in ticks:

DATABASE.setVal(x['instrument_token'],x['last_price'])
DATABASE.newCandle(x['instrument_token'])
# Strategy to buy after 3 continuous
increasing
# highs and sell after 3 continuous
decreasing lows

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

if
len(DATABASE.getOhlc(x['instrument_token']))>3:

tempDb =
DATABASE.getOhlc(x['instrument_token'])
if(tempDb.iloc[-1]['High']>tempDb.iloc[-2]
['High'] and tempDb.iloc[-2]
['High']>tempDb.iloc[-3]['High']):
order_id=
kite.place_order(tradingsymbol=x['instrument_token'],
exchange=kite.EXCHANGE_NSE,
transaction_type=kite.TRANSACTION_TYPE_BUY,
quantity=1,
order_type=kite.ORDER_TYPE_MARKET, prod
print(oid)
elif(tempDb.iloc[-1]['Low']
<tempDb.iloc[-2]['Low'] and tempDb.iloc[-2]
['Low']>tempDb.iloc[-3]['Low']):
order_id =
kite.place_order(tradingsymbol=x['instrument_token'],exchange=k
transaction_type=kite.TRANSACTION_TYPE_SELL,quantit
order_type=kite.ORDER_TYPE_MARKET,product=kite.PROD
print(oid)
#if current time is greater than ENDTIME
the stop the code
if(datetime.datetime.now()>ENDTIME):
print("Market is closed now...")
ws.stop()
#function to run when connection is established
to zerodha
def on_connect(ws, response):
# Callback on successful connect.
ws.subscribe(TOKENS)
#funcion to run on connection close
def on_close(ws, code, reason):
# On connection close stop the main loop
# Reconnection will not happen after
executing `ws.stop()`
print(code)
print(reason)
ws.stop()
#Assign the callbacks.
kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_close = on_close

__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/

# Infinite loop on the main thread. Nothing after


this will run.
# You have to use the pre-defined callbacks to
manage subscriptions.
kws.connect()
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
Appendix
print: python function used to output data
function:A function is a block of code which only runs when it is called. You can
pass data known as a parameter as a function. A function can return data as a
result.
api: An application program interface (API) is a set of routines, protocols, and
tools for building software applications.
import: python keyword used to get external function into current code
object: an instance of a class
class: A Class is like an object constructor, or a "blueprint" for creating objects.
type: python function used to find the data type of a variable
requests: python library to create get, post, delete etc. requests.
kiteconnect: Zerodha’s python api for retrieving data, placing orders etc.
input: python function to take input in python
pandas: python library to manage data
def : python keyword to define functions
stock : underlying instrument available for sale or purchase over exchange
zerodha : Indian financial service company, that offers retail and institutional
broking, currencies and commodities trading, mutual funds, and bonds.
time : python library to handle time
ticks : dictionary object containing data for a single stock for a single transaction
live data
ltp : last traded price of a stock
pip : python library installation and management software
dictionary: python data type which stores data as key value pair
list : python data type to store data at continuous indices
dataframe: data type of pandas library in python to store data as a table of
indices and headers
kiteticker : kite connect object for live data
datetime : python library to handle date and time
numpy : python library to handle complex arithmetic operations as a group
(array, vector etc.)
series : pandas data type which represents a row or a column which combine to
become a data frame
selenium : python library for browser automation
webdriver : selenium object to handle various browsers like chrome, Firefox etc
socket : A network socket is a software structure within a network node of a
computer network that serves as an endpoint for sending and receiving data
across the network.
trading : Trade in stock markets means the transfer (in exchange for money) of a
stock or security from a seller to a buyer.
library : a collection of predefined function, classes, and variable to be used in
other codes
exchange : A stock exchange is a facility where stockbrokers and traders can
buy and sell securities, such as shares of stock and bonds and other financial
instruments.
Jupyter-notebook: The Jupyter Notebook is an open-source web application that
allows you to create and share documents that contain live code, equations,
visualizations and narrative text.
stoploss : A stop-loss order is an order placed with a broker to buy or sell once
the stock reaches a certain price. A stop-loss is designed to limit an investor's
loss on security position.
float : python data type representing numbers containing decimal
append : function to insert elements in python list
set: python data type which stores only unique elements
streaming : Streaming data is data that is continuously generated by different
sources. Such data should be processed incrementally using Stream Processing
technique without having access to all of the data
keyword : Keywords are the reserved words in Python. We cannot use a
keyword as a variable name, function name or any other identifier.
break : python keyword to exit a loop
candle : A candlestick chart is a style of financial chart used to describe price
movements of a security, derivative, or currency.
tuple : A tuple is a collection of objects which are ordered and immutable.
Tuples are sequences, just like lists. The differences between tuples and lists are,
the tuples cannot be changed unlike lists and tuples use parentheses, whereas
lists use square brackets.
indicators: Technical Indicator is essentially a mathematical representation
based on data sets such as price (high, low, open, close, etc.) or volume of
security to forecast price trends.
split : python function to split a string based on input string
timestamp : a string representation of datetime object
lambda : python keyword to generate single line functions
matplotlib : python library to generate graphs
seaborn : python library to create graphs based on matplotlib
range : python function to create generators for numbers
ohlc : shart for for -> open high low and close
arrays : python numpy data type to represent mathematical arrays
try-except: python keyword to catch and handle errors
sleep : python function to delay execution of further lines
pprint : python library to print data types in readable form
comments : python statements which are not actually executed but are written
for human readability of code
len : python function to determine the length of a string
strip : python function to remove white spaces before and after a string
pyplot : matplotlib.pyplot is a collection of functions that make matplotlib work
like MATLAB. Each pyplot function makes some change to a figure: e.g.,
creates a figure, creates a plotting area in a figure, plots some lines in a plotting
area, decorates the plot with labels, etc.
os : This module provides a portable way of using operating system dependent
functionality.
github : GitHub is a Git repository hosting service, but it adds many of its own
features. While Git is a command line tool, GitHub provides a Web-based
graphical interface. It also provides access control and several collaboration
features, such as a wikis and basic task management tools for every project.
csv : comma separated values (csv) is a file type to store data like in excel
sql : SQL is a domain-specific language used in programming and designed for
managing data held in a relational database management system, or for stream
processing in a relational data stream management system.
io : The io module provides Python’s main facilities for dealing with various
types of I/O.
str : python representation of string (set of characters)
immutable : unchanging over time or unable to be changed.
json : JavaScript Object Notation is an open standard file format, and data
interchange format, that uses human-readable text to store and transmit data
objects consisting of attribute–value pairs and array data types.
logging : python library used to log outputs
squareoff : Squaring off is a trading style used by investors/traders mostly in day
trading, in which a trader buys or sells a particular quantity of an asset (mostly
stocks) and later in the day reverses the transaction, in the hope of earning a
profit (price difference net of broker charges and tax
asynchronous: Asynchronous programming is a means of parallel programming
in which a unit of work runs separately from the main application thread and
notifies the calling thread of its completion, failure or progress.
timedelta : python datetime object to define time duration
global : keyword to declare variables to be used in and out of every variable

You might also like