Skip to content

Commit

Permalink
doc formating and update read.md file
Browse files Browse the repository at this point in the history
  • Loading branch information
vikassharma545 committed Jun 11, 2023
1 parent a905b15 commit b5d8c35
Show file tree
Hide file tree
Showing 2 changed files with 201 additions and 52 deletions.
114 changes: 63 additions & 51 deletions PyKite.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,7 @@
import os
import json

try:
import requests
except:
os.system("pip install requests")

try:
import pyotp
except:
os.system("pip install pyotp")

try:
import pandas as pd
except:
os.system("pip install pandas")
import pyotp
import requests
import pandas as pd

class pykite:
"""
Expand Down Expand Up @@ -91,7 +78,6 @@ class __urls:

portfolio_positions = "/portfolio/positions"
portfolio_holdings = "/portfolio/holdings"
portfolio_holdings_auction = "/portfolio/holdings/auctions"
portfolio_positions_convert = "/portfolio/positions" # not working

market_quote = "/quote"
Expand Down Expand Up @@ -160,11 +146,19 @@ def __init__(self, userid='', password='', twofa='', key_type="totp", enctoken=N
self.root_url = "https://api.kite.trade"
self.header = {"Authorization": f"enctoken {self.enctoken}"}
self.urls = self.__urls()

def profile(self):
"""
Get user profile details.
"""
response = self.session.get(f"{self.root_url}{self.urls.user_profile}", headers=self.header).json()
return response

def margin(self, segment=None):
def margins(self, segment=None):
"""
Get account balance and cash margin details for a particular segment.
- `segment` is the trading segment (eg: equity or commodity)
"""

if segment:
response = self.session.get(f"{self.root_url}{self.urls.user_margins_segment.format(segment=segment)}", headers=self.header).json()
Expand All @@ -174,20 +168,33 @@ def margin(self, segment=None):

# orderbook and tradebook
def orders(self):
"""Get list of orders."""
"""
Get list of orders.
"""
response = self.session.get(f"{self.root_url}{self.urls.orders}", headers=self.header).json()
return response

def trades(self):
"""
Retrieve the list of trades executed (all or ones under a particular order).
An order can be executed in tranches based on market conditions.
These trades are individually recorded under an order.
"""
response = self.session.get(f"{self.root_url}{self.urls.trades}", headers=self.header).json()
return response

def positions(self):
"""
Retrieve the list of positions.
"""
response = self.session.get(f"{self.root_url}{self.urls.portfolio_positions}", headers=self.header).json()
return response

def holdings(self):
"""
Retrieve the list of equity holdings.
"""
response = self.session.get(f"{self.root_url}{self.urls.portfolio_holdings}", headers=self.header).json()
return response

def order_history(self, order_id):
"""
Get history of individual order.
Expand Down Expand Up @@ -219,15 +226,18 @@ def place_order(self,
iceberg_quantity=None,
auction_number=None,
tag=None):
"""Place an order."""
"""
Place an order.
"""
params = locals()
del (params["self"])

for k in list(params.keys()):
if params[k] is None:
del (params[k])

return self.session.post(f"{self.root_url}{self.urls.order_place.format(variety = variety)}", data=params, headers=self.header)
response = self.session.post(f"{self.root_url}{self.urls.order_place.format(variety = variety)}", data=params, headers=self.header).json()
return response['message']

def modify_order(self,
variety,
Expand All @@ -239,34 +249,26 @@ def modify_order(self,
trigger_price=None,
validity=None,
disclosed_quantity=None):

"""Modify an open order."""
"""
Modify an open order.
"""
params = locals()
del (params["self"])

for k in list(params.keys()):
if params[k] is None:
del (params[k])

return self.session.put(f"{self.root_url}{self.urls.order_modify.format(variety = variety, order_id=order_id)}", data=params, headers=self.header)
response = self.session.put(f"{self.root_url}{self.urls.order_modify.format(variety = variety, order_id=order_id)}", data=params, headers=self.header).json()
return response['message']

def cancel_order(self, variety, order_id, parent_order_id=None):
"""Cancel an order."""
"""
Cancel an order.
"""
params = {"parent_order_id": parent_order_id}
return self.session.delete(f"{self.root_url}{self.urls.order_cancel.format(variety = variety, order_id=order_id)}", data=params, headers=self.header)

def positions(self):
"""Retrieve the list of positions."""
response = self.session.get(f"{self.root_url}{self.urls.portfolio_positions}", headers=self.header).json()
return response
def holdings(self):
"""Retrieve the list of equity holdings."""
response = self.session.get(f"{self.root_url}{self.urls.portfolio_holdings}", headers=self.header).json()
return response

def get_auction_instruments(self):
response = self.session.get(f"{self.root_url}{self.urls.portfolio_holdings_auction}", headers=self.header).json()
return response
response = self.session.delete(f"{self.root_url}{self.urls.order_cancel.format(variety = variety, order_id=order_id)}", data=params, headers=self.header).json()
return response['message']

def convert_position(self,
exchange,
Expand All @@ -276,19 +278,25 @@ def convert_position(self,
quantity,
old_product,
new_product):

"""
Modify an open position's product type.
"""
params = locals()
del (params["self"])

"""Modify an open position's product type."""
response = self.session.put(f"{self.root_url}{self.urls.portfolio_positions_convert}", params=params, headers=self.header)
return response
response = self.session.put(f"{self.root_url}{self.urls.portfolio_positions_convert}", params=params, headers=self.header).json()
return response['message']

def instruments(self, exchange=None, download=False, download_path=""):
"""
Fetch Instruments data
- `exchange` is the trading exchange (eg: 'BCD', 'BFO', 'BSE', 'CDS', 'MCX', 'NSE', 'NFO')
"""
instruments = pd.read_csv("https://api.kite.trade/instruments")

if download:
instruments.to_csv(download_path)
instruments.to_csv(download_path, index=False)

if exchange:
instruments = instruments[instruments['exchange'] == exchange].reset_index(drop=True)
Expand All @@ -308,29 +316,33 @@ def quotes(self, instruments):
ins = instruments[0]

response = self.session.get(f"{self.root_url}{self.urls.market_quote}", params={"i": ins}, headers=self.header).json()
return response
return response['data']

def ohlc(self, instruments):
'''
Retrieve OHLC and market depth for list of instruments.
'''

ins = list(instruments)

# If first element is a list then accept it as instruments list for legacy reason
if len(instruments) > 0 and type(instruments[0]) == list:
ins = instruments[0]

response = self.session.get(f"{self.root_url}{self.urls.market_quote_ohlc}", params={"i": ins}, headers=self.header).json()
return response
return response['data']

def ltp(self, instruments):
'''
Retrieve last price for list of instruments.
'''

ins = list(instruments)

# If first element is a list then accept it as instruments list for legacy reason
if len(instruments) > 0 and type(instruments[0]) == list:
ins = instruments[0]

response = self.session.get(f"{self.root_url}{self.urls.market_quote_ltp}", params={"i": ins}, headers=self.header).json()
return response
return response['data']

def order_margins(self, list_of_orders):
"""
Expand Down
139 changes: 138 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,138 @@
# Zerodha-Python Trade-Without-API-Cost
# APICostFree Zerodha Trade
### _An unofficial python library for zerodha trade_

## Prerequisites
* Python >= 3.7

## Requirments
* requests >= 2.28.1 ``` pip install requests```
* pyotp >= 2.8.0 ```pip install pyotp```
* pandas >= 1.5.0 ```pip install pandas```

How to use
```python
from PyKite import pykite
```

Login Method - 1
```python

# using Userid password and totp/pin/totpkey
# condition not use zerodha on browser

kite = pykite(userid="userid", password="password", twofa="twofa", key_type="totp")
```

Login Method - 2
```python
# login directly using entoken copy from browser after login zerodha
# condition not use zerodha web on different pc
# after login don't logout from current session

enctoken = "E0zW+0684kAxZJPbSSIRv1lKIIqM8Iyw2tQ5WVxwg/oDbmclZrakC/poFPpg=="

kite = pykite(enctoken=enctoken)
```

### Notes - You can use zerodha on kite App Mobile

## Usages


### Accounts and trades details
```python
# Get user profile details.
print(kite.profile())

# Get account balance and cash margin.
print(kite.margins())

# Fetch all orders
print(kite.orders())

# Fetch all trades
print(kite.trades())

# Fetch all position
print(kite.positions())

# Get order history for particular order
print(kite.order_history('order_id'))

# Get trades history particular order
print(kite.order_trades('order_id'))
```

### Order placing and modify
```python
# Place an order
print(kite.place_order(variety=kite.VARIETY_REGULAR,
exchange=kite.EXCHANGE_NSE,
tradingsymbol="SBIN",
transaction_type=kite.TRANSACTION_TYPE_BUY,
quantity=10,
product=kite.PRODUCT_CNC,
order_type=kite.ORDER_TYPE_LIMIT,
price=500))


# Modify an order
print(kite.modify_order(variety=kite.VARIETY_REGULAR,
order_id='order_id',
quantity="10",
price=550,
order_type=kite.ORDER_TYPE_LIMIT))

# Cancel an order
print(kite.cancel_order(variety=kite.VARIETY_REGULAR,
order_id='order_id',
parent_order_id='parent_order_id'))


# Convert position
print(kite.convert_position(exchange=kite.EXCHANGE_NSE,
tradingsymbol="SBIN",
transaction_type=kite.TRANSACTION_TYPE_BUY,
position_type=kite.POSITION_TYPE_DAY,
quantity=10,
old_product=kite.PRODUCT_CNC,
new_product=kite.PRODUCT_NRML))

```

### Market data Fetch

```python
# fetch all instruments
instrument_all = kite.instruments()
print(instrument_all)

# # Fetch instrument for particular exchange
instrument_nse = kite.instruments("NSE")
print(instrument_nse)


# # fetch and download instrument file to disk
instrument_nfo = kite.instruments("NFO", download=True, download_path="./instrument_nfo.csv")
print(instrument_nfo)

instrument_list = ["NSE:SBIN", "NSE:HDFC", "NSE:RELIANCE"]

# Retrieve quote for list of instruments.
print(kite.quotes(instrument_list))

# Retrieve OHLC for list of instruments for current day.
print(kite.ltp(instrument_list))

# Retrieve Last trade price for list of instruments.
print(kite.ltp(instrument_list))
```

### Margin detail

```python

```



0 comments on commit b5d8c35

Please sign in to comment.