Git Product home page Git Product logo

jugaad-trader's Introduction

Free Zerodha API - jugaad-trader

Jugaad trader implements reverse engineered API for Zerodha in python (hence the name Jugaad). With this library you can programatically execute trades, retrieve your order and trade books, holdings, margins among other things.

Documentation - https://marketsetup.in/documentation/jugaad-trader/

Installation

pip install jugaad-trader

Quick start

Step 1 - Log in to Zerodha account with jtrader CLI

$ jtrader zerodha startsession
User ID >: Zerodha User Id
Password >:
Pin >:
Logged in successfully

Step 2 - Instantiate Zerodha and issue commands

from jugaad_trader import Zerodha
kite = Zerodha()
 
# Set access token loads the stored session.
# Name chosen to keep it compatible with kiteconnect.
kite.set_access_token()

# Get profile
profile = kite.profile()
print(profile)

How to contribute

Refer this document how to contribute - https://github.com/jugaad-py/jugaad-trader/blob/master/contributing.md

Articles and examples using Jugaad-Trader

https://marketsetup.in/tags/jugaad-trader/

jugaad-trader's People

Contributors

abc-git avatar iamknownstranger avatar sevakram avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jugaad-trader's Issues

Error placing multiple orders Zerodha

HTTPSConnectionPool(host='kite.zerodha.com', port=443): Max retries exceeded with url: /oms/quote/ltp?i=9957378 (Caused by SSLError(SSLError("read error: Error([('SSL routines', 'ssl3_get_record', 'decryption failed or bad record mac')])")))

I'm using multithreading to place errors this error is being raised despite multiple exceptions handling.

Not able to install jugaad-trader on windows using pip

Describe the bug
Getting Error while installing package using pip on windows

Code snippet
pip install jugaad-trader

Error
C:\Users\ArthBalodiya>pip install jugaad-trader
Collecting jugaad-trader
Using cached jugaad_trader-0.18-py3-none-any.whl (11 kB)
Collecting requests==2.23.0 (from jugaad-trader)
Using cached requests-2.23.0-py2.py3-none-any.whl (58 kB)
Collecting websockets==8.1 (from jugaad-trader)
Using cached websockets-8.1-cp312-cp312-win_amd64.whl
Collecting kiteconnect==3.8.2 (from jugaad-trader)
Using cached kiteconnect-3.8.2.tar.gz (24 kB)
Preparing metadata (setup.py) ... done
Collecting beautifulsoup4 (from jugaad-trader)
Using cached beautifulsoup4-4.12.2-py3-none-any.whl (142 kB)
Collecting Click==7.1.2 (from jugaad-trader)
Using cached click-7.1.2-py2.py3-none-any.whl (82 kB)
Requirement already satisfied: six in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from jugaad-trader) (1.16.0)
Requirement already satisfied: pyOpenSSL>=17.5.0 in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from kiteconnect==3.8.2->jugaad-trader) (23.3.0)
Collecting enum34>=1.1.6 (from kiteconnect==3.8.2->jugaad-trader)
Using cached enum34-1.1.10-py3-none-any.whl (11 kB)
Requirement already satisfied: python-dateutil>=2.6.1 in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from kiteconnect==3.8.2->jugaad-trader) (2.8.2)
Requirement already satisfied: autobahn>=17.10.1 in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from autobahn[twisted]>=17.10.1->kiteconnect==3.8.2->jugaad-trader) (19.11.2)
Requirement already satisfied: pywin32 in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from kiteconnect==3.8.2->jugaad-trader) (306)
Collecting chardet<4,>=3.0.2 (from requests==2.23.0->jugaad-trader)
Using cached chardet-3.0.4-py2.py3-none-any.whl (133 kB)
Collecting idna<3,>=2.5 (from requests==2.23.0->jugaad-trader)
Using cached idna-2.10-py2.py3-none-any.whl (58 kB)
Collecting urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 (from requests==2.23.0->jugaad-trader)
Using cached urllib3-1.25.11-py2.py3-none-any.whl (127 kB)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from requests==2.23.0->jugaad-trader) (2023.7.22)
Collecting soupsieve>1.2 (from beautifulsoup4->jugaad-trader)
Using cached soupsieve-2.5-py3-none-any.whl.metadata (4.7 kB)
Requirement already satisfied: txaio>=18.8.1 in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from autobahn>=17.10.1->autobahn[twisted]>=17.10.1->kiteconnect==3.8.2->jugaad-trader) (23.1.1)
Requirement already satisfied: cryptography>=2.7 in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from autobahn>=17.10.1->autobahn[twisted]>=17.10.1->kiteconnect==3.8.2->jugaad-trader) (41.0.5)
Requirement already satisfied: zope.interface>=3.6.0 in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from autobahn[twisted]>=17.10.1->kiteconnect==3.8.2->jugaad-trader) (6.1)
Requirement already satisfied: Twisted>=12.1.0 in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from autobahn[twisted]>=17.10.1->kiteconnect==3.8.2->jugaad-trader) (23.10.0)
Requirement already satisfied: cffi>=1.12 in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from cryptography>=2.7->autobahn>=17.10.1->autobahn[twisted]>=17.10.1->kiteconnect==3.8.2->jugaad-trader) (1.16.0)
Requirement already satisfied: attrs>=21.3.0 in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from Twisted>=12.1.0->autobahn[twisted]>=17.10.1->kiteconnect==3.8.2->jugaad-trader) (23.1.0)
Requirement already satisfied: automat>=0.8.0 in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from Twisted>=12.1.0->autobahn[twisted]>=17.10.1->kiteconnect==3.8.2->jugaad-trader) (22.10.0)
Requirement already satisfied: constantly>=15.1 in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from Twisted>=12.1.0->autobahn[twisted]>=17.10.1->kiteconnect==3.8.2->jugaad-trader) (23.10.4)
Requirement already satisfied: hyperlink>=17.1.1 in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from Twisted>=12.1.0->autobahn[twisted]>=17.10.1->kiteconnect==3.8.2->jugaad-trader) (21.0.0)
Requirement already satisfied: incremental>=22.10.0 in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from Twisted>=12.1.0->autobahn[twisted]>=17.10.1->kiteconnect==3.8.2->jugaad-trader) (22.10.0)
Requirement already satisfied: twisted-iocpsupport<2,>=1.0.2 in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from Twisted>=12.1.0->autobahn[twisted]>=17.10.1->kiteconnect==3.8.2->jugaad-trader) (1.0.4)
Requirement already satisfied: typing-extensions>=4.2.0 in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from Twisted>=12.1.0->autobahn[twisted]>=17.10.1->kiteconnect==3.8.2->jugaad-trader) (4.8.0)
Requirement already satisfied: setuptools in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from zope.interface>=3.6.0->autobahn[twisted]>=17.10.1->kiteconnect==3.8.2->jugaad-trader) (68.2.2)
Requirement already satisfied: pycparser in c:\users\arthbalodiya\appdata\local\programs\python\python312\lib\site-packages (from cffi>=1.12->cryptography>=2.7->autobahn>=17.10.1->autobahn[twisted]>=17.10.1->kiteconnect==3.8.2->jugaad-trader) (2.21)
Using cached soupsieve-2.5-py3-none-any.whl (36 kB)
Building wheels for collected packages: kiteconnect
Building wheel for kiteconnect (setup.py) ... done
WARNING: Legacy build of wheel for 'kiteconnect' created no files.
Command arguments: 'C:\Users\ArthBalodiya\AppData\Local\Programs\Python\Python312\python.exe' -u -c '
exec(compile('"'"''"'"''"'"'
This is -- a caller that pip uses to run setup.py

  • It imports setuptools before invoking setup.py, to enable projects that directly
    import from distutils.core to work with newer packaging standards.
  • It provides a clear error message when setuptools is not installed.
  • It sets sys.argv[0] to the underlying setup.py, when invoking setup.py so
    setuptools doesn'"'"'t think the script is -c. This avoids the following warning:
    manifest_maker: standard file '"'"'-c'"'"' not found".
  • It generates a shim setup.py, for handling setup.cfg-only projects.
    import os, sys, tokenize

try:
import setuptools
except ImportError as error:
print(
"ERROR: Can not execute setup.py since setuptools is not available in "
"the build environment.",
file=sys.stderr,
)
sys.exit(1)

file = %r
sys.argv[0] = file

if os.path.exists(file):
filename = file
with tokenize.open(file) as f:
setup_py_code = f.read()
else:
filename = ""
setup_py_code = "from setuptools import setup; setup()"

exec(compile(setup_py_code, filename, "exec"))
'"'"''"'"''"'"' % ('"'"'C:\Users\ArthBalodiya\AppData\Local\Temp\pip-install-5ytn5nih\kiteconnect_8ebc7e056cb54c589028e52658b79a30\setup.py'"'"',), "", "exec"))' bdist_wheel -d 'C:\Users\ArthBalodiya\AppData\Local\Temp\pip-wheel-09as7xw9'
Command output: [use --verbose to show]
Running setup.py clean for kiteconnect
Failed to build kiteconnect
ERROR: Could not build wheels for kiteconnect, which is required to install pyproject.toml-based projects

Console portfolio doesn't work any more

Describe the bug
When trying to do a .portfolio() on console object, it fails with

InputException: Missing or empty field `date`

From inspecting request from Console, now looks like 'date' query param, e.g. ?date=2021-09-03, is mandatory now.

Code snippet

from jugaad_trader import Console
c = Console(z)  # z is the logged-in Zerodha() object
c.login()
c.portfolio()

Error
(ipython shell output)

~/.myvenv/lib/python3.9/site-packages/jugaad_trader-0.18-py3.9.egg/jugaad_trader/zerodha.py in generic_function(**kwargs)
    317             if route == "portfolio":
    318                 kwargs["date"] = datetime.date.today().isoformat()
--> 319             return self._get(route, params=kwargs)
    320         generic_function.__doc__ = docstring
    321         return generic_function

~/.myvenv/lib/python3.9/site-packages/kiteconnect-3.9.4-py3.9.egg/kiteconnect/connect.py in _get(self, route, url_args, params, is_json)
    834     def _get(self, route, url_args=None, params=None, is_json=False):
    835         """Alias for sending a GET request."""
--> 836         return self._request(route, "GET", url_args=url_args, params=params, is_json=is_json)
    837
    838     def _post(self, route, url_args=None, params=None, is_json=False, query_params=None):

~/.myvenv/lib/python3.9/site-packages/jugaad_trader-0.18-py3.9.egg/jugaad_trader/zerodha.py in _request(self, route, method, url_args, params, is_json, query_params)
    193                 # native Kite errors
    194                 exp = getattr(ex, data["error_type"], ex.GeneralException)
--> 195                 raise exp(data["message"], code=r.status_code)
    196
    197             return data["data"]

InputException: Missing or empty field `date`

Fix
Console object's generic_function can be edited to add these two lines:

         def generic_function(**kwargs):
+            if route == "portfolio":
+                kwargs["date"] = datetime.date.today().isoformat()
             return self._get(route, params=kwargs)
         generic_function.__doc__ = docstring
         return generic_function

Hacky, but works!

Additional context
Note that I could only make it work after reverting the commit which broke Console access i.e. c0947e1, part of #23. Related issue #15 .

No jtrader cli in Ubuntu

I installed Jugaad Trader using
pip3 install jugaad-trader

but jtrader CLI is not available

user@homepc:~/devel/temp$ jtrader zerodha startsession

I get the following error
jtrader: command not found

Place Order API results in error.

Change the default value from "Day" to "DAY", and this should work.

How did you manage to create this. Highly appreciated. Wonderful!!
Any option to get market data as well?

AttributeError: 'Retry' object has no attribute 'method_whitelist'

When trying to fetch any of the data like kite.margins() or kite.orders(), I'm getting error
AttributeError: 'Retry' object has no attribute 'method_whitelist'

Traceback (most recent call last):
File "/Users/usr/Documents/Projects/Python//jugaad_trader_sample.py", line 58, in
margins = kite.margins()
File "/Users/usr/opt/anaconda3/lib/python3.7/site-packages/kiteconnect/connect.py", line 315, in margins
return self._get("user.margins")
File "/Users/usr/opt/anaconda3/lib/python3.7/site-packages/kiteconnect/connect.py", line 817, in _get
return self._request(route, "GET", params)
File "/Users/usr/opt/anaconda3/lib/python3.7/site-packages/jugaad_trader/zerodha.py", line 167, in _request
raise e
File "/Users/usr/opt/anaconda3/lib/python3.7/site-packages/jugaad_trader/zerodha.py", line 163, in _request
proxies=self.proxies)
File "/Users/usr/opt/anaconda3/lib/python3.7/site-packages/requests/sessions.py", line 530, in request
resp = self.send(prep, **send_kwargs)
File "/Users/usr/opt/anaconda3/lib/python3.7/site-packages/requests/sessions.py", line 643, in send
r = adapter.send(request, **kwargs)
File "/Users/usr/opt/anaconda3/lib/python3.7/site-packages/requests/adapters.py", line 449, in send
timeout=timeout
File "/Users/usr/opt/anaconda3/lib/python3.7/site-packages/urllib3/connectionpool.py", line 805, in urlopen
if retries.is_retry(method, response.status, has_retry_after):
File "/Users/usr/opt/anaconda3/lib/python3.7/site-packages/urllib3/util/retry.py", line 343, in is_retry
if not self._is_method_retryable(method):
File "/Users/usr/opt/anaconda3/lib/python3.7/site-packages/urllib3/util/retry.py", line 331, in _is_method_retryable
if self.method_whitelist and method.upper() not in self.method_whitelist:
AttributeError: 'Retry' object has no attribute 'method_whitelist'

How do I solve this?

AttributeError: 'Zerodha' object has no attribute 'ticker'

from jugaad_trader import Zerodha
import logging
from jugaad_trader import Zerodha

kite = Zerodha()

Set access token loads the stored session.

Name chosen to keep it compatible with kiteconnect.

kite.set_access_token()

kws = kite.ticker()

Error:

kws = kite.ticker()

AttributeError: 'Zerodha' object has no attribute 'ticker'

Regarding creating the lambda function

I am trying to deploy the code of jugad trader on AWS lambda but getting multiple error of dependency.
As per the instruction of creating the layer I am created python folder and in that pip install jugaad-trader -t . once that is done I have zipped it then uploaded in layer

Code snippet

import json
#from kiteconnect import KiteConnect
from jugaad_trader import Zerodha

def lambda_handler(event, context):
# TODO implement
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}

Error

Below is the error with cryptography library

Test Event Name
test

Response
{
"errorMessage": "Unable to import module 'lambda_function'"
}

Function Logs
START RequestId: 0ae8436a-b7f0-4e33-b799-34559934c0fa Version: $LATEST
Unable to import module 'lambda_function': No module named 'cryptography.hazmat.bindings._openssl'

END RequestId: 0ae8436a-b7f0-4e33-b799-34559934c0fa
REPORT RequestId: 0ae8436a-b7f0-4e33-b799-34559934c0fa Duration: 0.50 ms Billed Duration: 1 ms Memory Size: 128 MB Max Memory Used: 77 MB Init Duration: 993.97 ms

Request ID
0ae8436a-b7f0-4e33-b799-34559934c0fa

Additional context
Trying to figure out dependency or steps by step to create or is there any need of modification. Please let me know in case any additional information is required

3 minute data

hi,

  1. is it possible to get 3 min open, close data for banknifty.
  2. is it possible to get data in reverse order? like in date most recent data in first row.
    thanks

kiteconnect.exceptions.TokenException: Incorrect `api_key` or `access_token`.

While accessing historical data getting below error

request - data = kite.historical_data( 'ADANIPORTS' , 'NSE:' , 5, '5minute', False, False)

Response -
kiteconnect.exceptions.TokenException: Incorrect api_key or access_token.
C:\Users\ABC\AppData\Local\Programs\Python\Python37-32\python.exe "C:/Users/ABC/Documents/Personal/Study Material/jugaad-trader-master/ZKiteTicks.py"
Traceback (most recent call last):
File "C:/Users/ABC/Documents/Personal/Study Material/jugaad-trader-master/ZKiteTicks.py", line 75, in
data = kite.historical_data( 'ADANIPORTS' , 'NSE:' , 5, '5minute', False, False)
File "C:\Users\ABC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kiteconnect\connect.py", line 630, in historical_data
"oi": 1 if oi else 0
File "C:\Users\ABC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kiteconnect\connect.py", line 817, in _get
return self._request(route, "GET", params)
File "C:\Users\ABC\Documents\TIME\jugaad-trader-master\jugaad_trader\zerodha.py", line 188, in _request
raise exp(data["message"], code=r.status_code)
kiteconnect.exceptions.TokenException: Incorrect api_key or access_token.

Process finished with exit code 1

kite.quote/ltp not working

kite.quote(["NSE:INFY", "BSE:INFY"])

D:\anaconda3\lib\site-packages\kiteconnect\connect.py in quote(self, *instruments)
564 ins = instruments[0]
565
--> 566 data = self._get("market.quote", {"i": ins})
567 return {key: self._format_response(data[key]) for key in data}
568

D:\anaconda3\lib\site-packages\kiteconnect\connect.py in _get(self, route, params)
815 def _get(self, route, params=None):
816 """Alias for sending a GET request."""
--> 817 return self._request(route, "GET", params)
818
819 def _post(self, route, params=None):

D:\anaconda3\lib\site-packages\jugaad_trader\zerodha.py in _request(self, route, method, url_args, params, is_json, query_params)
174
175 # native Kite errors
--> 176 exp = getattr(ex, data.get("error_type"), ex.GeneralException)
177 raise exp(data["message"], code=r.status_code)
178

TypeError: getattr(): attribute name must be string

[Enhancement] Need Bracket order functionality

Hi,

Zerodha many time blocks bracket orders due to high volatility for both cash market and FNO. Can we have some kind of feature where we place order with a predefined target and stoploss ?
This feature would also do magic in scalping.
P.S. Zerodha has blocked placing BO for FNO catagory.

Not able to use the Console area.. Was Wondering if We can Apply IPO through this functions?

Traceback (most recent call last):
File "f:/./.Jt/Testing Purpose/console.py", line 127, in
test_fund_balance()
File "f:/./.Jt/Testing Purpose/console.py", line 115, in test_fund_balance
v = c.fund_balance()
File "f:..Jt\Testing Purpose\jugaad_trader\zerodha.py", line 302, in generic_function
return self._get(route, params=kwargs)
File "f:..Jt\Testing Purpose\kiteconnect\connect.py", line 856, in _get
return self._request(route, "GET", url_args=url_args, params=params, is_json=is_json)
File "f:..Jt\Testing Purpose\jugaad_trader\zerodha.py", line 174, in _request
raise exp(data["message"], code=r.status_code)
kiteconnect.exceptions.PermissionException: Invalid CSRF token.

Feature enhancement.

Is it possible to get 20 market depth? I know it is now available in API, thought we might have some workaround to get 20 depth as we are using web session

BeautifulSoup Parsing error in using kite.instruments method

Describe the bug
Getting a BeautifulSoup Parsing error on trying to use kite.instruments method in jugaad-trader. Can someone please suggest a workaround for this?

Code snippet
kite = Zerodha()
instrument = kite.instruments(exchange="NFO")

Error
C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\jugaad_trader\zerodha.py:184: **GuessedAtParserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("lxml"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

The code that caused this warning is on line 184 of the file C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\jugaad_trader\zerodha.py. To get rid of this warning, pass the additional argument 'features="lxml"' to the BeautifulSoup constructor.

bs = BeautifulSoup(html)
Expecting value: line 1 column 1 (char 0)**
Traceback (most recent call last):
File "xx", line 86, in
instrument = kite.instruments(exchange="NFO")
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\jugaad_trader\zerodha.py", line 206, in instruments
chunkjs = self.chunk_to_json(js)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\jugaad_trader\zerodha.py", line 198, in chunk_to_json

Additional context
Add any other context about the problem here.

2FA TOTP

Describe the bug
Hi,

I'm using this API since a month. Just started developing Algo. Now Zerodha mandating 2FA TOTP.
Will there be any enhancement to support ?

Connection closed: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (400 - BadRequest))

Describe the bug
I've started getting this Connection closed: 1006 error for the websocket ticker code.

Code snippet
from jugaad_trader import Zerodha

kws = kite.ticker()

def on_ticks(ws, ticks):
# Callback to receive ticks.
print("Ticks: {}".format(ticks))

def on_connect(ws, response):
# Callback on successful connect.
# Subscribe to a list of instrument_tokens (RELIANCE and ACC here).
ws.subscribe([738561, 5633])

# Set RELIANCE to tick in `full` mode.
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()
ws.stop()

kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_close = on_close

kws.connect()

Error
Connection closed: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (400 - BadRequest))

Unable to use console class

kite = Zerodha() # credentials are passed
kite.login()
Able to see holdings, profile from kite.

console = Console(z=kite)
console.dashboard()

Error message - kiteconnect.exceptions.TokenException: Invalid or expired session.

session is expiring before logging in

`from jugaad_trader import Zerodha

user_id = "USERID"
password = "PASSWORD"
pin = "PIN"

kite = Zerodha(user_id, password, pin)

print(kite.login())

print(kite.orders())

Set access token loads the stored session.

Name chosen to keep it compatible with kiteconnect.

Get profile

print(profile := kite.profile())

Get margin

margins = kite.margins()
print(margins)

Get holdings

holdings = kite.holdings()
print(holdings)

Get today's positions

positions = kite.positions()
print(positions)

Get today's orders

orders = kite.orders()
print(orders)`

Updated code is not packaged to pypi

Describe the issue
When code is updated in the main/master branch it is not being packaged and update din pypi. This is causing a lot of errors, especially if kiteconnect is updated to the latest version.

Error
TypeError: _request() got an unexpected keyword argument 'url args'

Proposed solution

  • Create tags for major version of jugad-trader, that way people can choose the version that works best for them (Similar to how numpy versions can be downloaded.)
  • Create github action to acutomatically update pypi with the lates package (I can help in setting this up)

What is the URL the code is hitting?

This is not really an issue but a clarification on how the code works to fetch historical data from Zerodha? From the code it appears to hit kite.zerodha.com or is the library built from a different source? but kite.zerodha.com doesn't support historical data when I try to access it. What is the api key that needs to be used for fetching historical data?

I am trying to write a java version based on your code, I have successfully logged in, got the encryption key public key etc. But unable to fetch historical data as the API doesn't accept the api_key(I am using kitefront picked up from your code). From what I gather historical data is just via HTTP request, so the missing factor seems to be the URL and the api_key.

Could you throw some light.

pip install not adding files with latest changes

Jugaad trader lib does not show latest changes available in the code.
I tried upgrading jugaad-trader, even I uninstalled it and installed it again using pip but still latest code is not showing up in the lib.

Can anyone please help me here.

Upstox login not working

Describe the bug
Using upstox example not able to login and go further

Code snippet

from jugaad_trader import Upstox
user_id = "123456"
password = "P@ssw0d131"
twofa = "1990"
u = Upstox(user_id, password, twofa)

# Login
u.login()

# Get profile information
profile = u.get_client_info()

Error

python .\jugaad_upstox.py
Traceback (most recent call last):
  File ".\jugaad_upstox.py", line 8, in <module>
    u.login()
  File "D:\Apps\Scoop\apps\python\current\lib\site-packages\jugaad_trader\upstox.py", line 82, in login
    self.loop.run_until_complete(self.connect())
  File "D:\Apps\Scoop\apps\python\current\lib\asyncio\base_events.py", line 616, in run_until_complete
    return future.result()
  File "D:\Apps\Scoop\apps\python\current\lib\site-packages\jugaad_trader\upstox.py", line 45, in connect
    j = json.loads(j)
  File "D:\Apps\Scoop\apps\python\current\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "D:\Apps\Scoop\apps\python\current\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "D:\Apps\Scoop\apps\python\current\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

getting error

ERROR: Could not find a version that satisfies the requirement jugad-trader (from versions: none)
ERROR: No matching distribution found for jugad-trader

public_token not found

@jugaader , really kudos to your work......tremendous effort.

I have found one minor issue:

"self.public_token = j['data']['public_token']", from zerodha.py file, line number 94 getting issue.

Just comment the line, then it is working fabulously

'Zerodha' object has no attribute 'enc_token'

Aftr entering the order paramter set [ copy pasted the code snip to jupyter not]
i got th following error.
Looks related to session info.
PLease advise.

image

image

Additional context
Add any other context about the problem here.

how to refresh the position and holdings?

Describe the bug

Documentation is not clear on how to refresh the data once you have logged in.
I am using this code to calculate my position pnl but the data is not getting updated.

Code snippet

from dotenv import load_dotenv
import os
import pyotp
import time
from jugaad_trader import Zerodha
load_dotenv()

otp_gen = pyotp.TOTP(os.getenv("ZERODHA_TOTP_HASH"))
kite = Zerodha(
    user_id=os.getenv("ZERODHA_ID"), 
    password=os.getenv("ZERODHA_PASSWORD"), 
    twofa=otp_gen.now()
)
kite.login()

while True:
    pnl = 0
    positions = kite.positions()
    for position in positions.get("net"):
        pnl += position.get('pnl')
    print(pnl)
    time.sleep(1)

login problem

:Following error coming while running !pip install jugaad-trader ..plz suggest...tnx
Error: The login session has expired or doesn't exist. Please try again.

Error
Error log

Additional context
Add any other context about the problem here.
jtrader login problem

kite.ltp and kite.quote raising TokenException

Hello

You've done excellent work with the module.
I can't thank you enough for your hard work.

I'm new to Algo Trading I'm trying to use kite.ltp and kite.quote in my system.
The below is exception is being raised

File "/home/ubuntu/charlie/gap_watchlist.py", line 10, in
kite.quote(["NSE:INFY", "BSE:INFY"])
File "/home/ubuntu/.local/lib/python3.8/site-packages/kiteconnect/connect.py", line 566, in quote
data = self._get("market.quote", {"i": ins})
File "/home/ubuntu/.local/lib/python3.8/site-packages/kiteconnect/connect.py", line 817, in _get
return self._request(route, "GET", params)
File "/home/ubuntu/.local/lib/python3.8/site-packages/jugaad_trader/zerodha.py", line 188, in _request
raise exp(data["message"], code=r.status_code)
kiteconnect.exceptions.TokenException: Incorrect api_key or access_token.

DataException

DataException Traceback (most recent call last)
in
70 sr='NFO:NIFTY22'+exp+ str(int(n['atmn'][i])) +'PE'
71 get_data = kite.historical_data(kite.ltp(sr)[sr]['instrument_token'],dates.strftime('%Y-%m-%d'),
---> 72 datee.strftime('%Y-%m-%d'), '15minute',)
73 try:
74 nd1=(pd.DataFrame(get_data))['close'][i]

2 frames
/usr/local/lib/python3.7/dist-packages/jugaad_trader/zerodha.py in _request(self, route, method, parameters)
194 raise ex.DataException("Unknown Content-Type ({content_type}) with response: ({content})".format(
195 content_type=r.headers["content-type"],
--> 196 content=r.content))
197
198 def get_chunk_js(self):

DataException: Unknown Content-Type (text/html; charset=UTF-8) with response: (b'\n\n\n <title>Just a moment...</title>\n \n \n \n \n \n \n\n\n\n

\n
\n

\n <img class="heading-favicon" src="/favicon.ico"\n onerror="this.onerror=null;this.parentNode.removeChild(this)">\n kite.zerodha.com\n

\n

\n Checking if the site connection is secure\n

\n \n
\n
\n \n
\n
\n \n Enable JavaScript and cookies to continue\n \n
\n
\n \n <div id="trk_jschal_js" style="display:none;background-image:url...

Connection closed: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (400 - BadRequest))

Issue #20 persists.

from jugaad_trader import Zerodha

kws = kite.ticker()

def on_ticks(ws, ticks):
    print("Ticks: {}".format(ticks))

def on_connect(ws, response):
    ws.subscribe([738561, 5633])
    ws.set_mode(ws.MODE_FULL, [738561])

def on_close(ws, code, reason):
    ws.stop()

kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_close = on_close

kws.connect()

Error
Connection error: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (400 - BadRequest))
Connection closed: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (400 - BadRequest))

Additional context
This was issue #20 and it persists for me.
Have latest jugaad-trader from source ( this repo )
Have kiteconnect = 4.1.0

Also tested the fix provided by #26 , it doesn't solve the issue.

Will this create any issues on this api acess method?

Starting October 3, 2021, order placements via the Kite Connect API will require the respective accounts to have enabled 2FA TOTP. This does not involve any changes to any of the APIs. You just have to enable 2FA TOTP on your Zerodha account with which you login to Kite Connect. Without this, orders will not go through.

This is in line with the SEBI Cyber Security regulations and the increased cyber security threat levels in recent times. Moreover, the entire industry may move to mandatory physical 2FA for all logins in the near future.

Learn how to setup TOTP.

Why now? Huge rise cases in cyber security incidents. Every trading platform, API or not, is mandated to have 2FA like the circular says. We already enforce it for certain kinds of trades based on risk. SEBI is aware that the industry at large does not implement 2FA according to the original guidelines and there are indications that it will be enforced soon. When we mandated TOTP for risky trades, phishing and fraud complaints that were a regular feature went down to practically zero. Industry-wide 2FA will significantly reduce fraud and other unregulated activities.

https://kite.trade/forum/discussion/10391/mandatory-totp-for-all-kite-connect-apps

Ticker is Unable to connect.

Unable to connect to Ticker

Sample code being used.

Error
Connection error: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (400 - BadRequest))
Connection closed: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (400 - BadRequest))

Additional context
Add any other context about the problem here.

Session is expiring frequently

@jugaader No words to your work, just simply awesome.

I am using the Zerodha account.

I have some minor issues, Every time session is ending after a couple of minutes in Zerodha API. Is there any way that we can specify the timeout to expire or without the session expire?

Upstox CLI

Write CLI for Upstox similar to Zerodha.

Top level command -
jtrader upstox

Sub-commands-
savecreds
configdir
rm

Skipping startsession for now due to complexities of websocket.

place_order waits indefinitely for response

Describe the bug
place_order waits indefinitely for response, Upstox does not send any response to corresponding guid request

Code snippet

params = {'exchange': 'NSE_EQ',
            'token': '3045',
            'symbol': 'SBIN',
            'series': 'EQ',
            'is_amo': False,
            'order_complexity': 'OCO',
            'order_type': 'L',
            'product': 'I',
            'duration': 'DAY',
            'transaction_type': 'B',
            'price': '203',
            'trigger_price': '0',
            'disclosed_quantity': '0',
            'quantity': '1',
            'square_off': '1',
            'stop_loss': '1',
            'trailing_ticks': '0'}
u.place_order(**params)

Error
No error, but place_order waits indefinitely.

option chain

How to see option strike price quotes with OI or display option chain

issue in asyncio

`
async def fetch_tfa(session, URL, TWOFA_ROUTE, headers, twofa_payload):
"""
two factor authentication
"""
async with session.post(URL + TWOFA_ROUTE, data=twofa_payload) as response:
return response.cookies['enctoken']

async def main(ohlc_table_name, symbol_table_name, ifStock):
"""
Login to Zerodha
"""
URL = "https://kite.zerodha.com/"
LOGIN_ROUTE = "api/login"
TWOFA_ROUTE = "api/twofa"
USER_ID = config.USER_ID
PASSWORD = config.PASSWORD
TWOFA_VALUE = config.TWOFA_VALUE
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/5',
'origin': URL,
'referer': URL,
}
login_payload = {
'user_id': USER_ID,
'password': PASSWORD
}
sem = asyncio.Semaphore(100)
async with aiohttp.ClientSession() as session:
json_load = await asyncio.gather(fetch(session, URL, LOGIN_ROUTE, headers, login_payload))
twofa_payload = {
'user-id': USER_ID,
'request_id': json_load[0]["data"]["request_id"],
'twofa_value': TWOFA_VALUE,
'skip_session': ''
}
resp = await asyncio.gather(fetch_tfa(session, URL, TWOFA_ROUTE, headers, twofa_payload))
enc_token = resp[0].value
header_update = {'authorization': "enctoken{}".format(enc_token),
'referer': 'https://kite.zerodha.com/dashboard',
'x-kite-version': '2.9.10', 'sec-fetch-site': 'same-origin', 'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',}
session.headers.update(header_update)
`

I am getting 403 response in twfa stage. can you point out the possible error?

[Feature] How can I add the kite.order_margins function?

I can see the api endpoint being discussed in the official forums, however I can't seem to figure out how I can add another function.

For that matter, where are the other functions saved in the scripts? Or are they not explicitly defined? Because, if I could see them, I could contribute more similar to them.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.