Squashed 'utils_v2/' content from commit 8bb584e4

git-subtree-dir: utils_v2
git-subtree-split: 8bb584e4734606740c0b42d51bc7fd458c39031a
This commit is contained in:
2025-01-15 12:12:45 +05:30
commit 3a64ea7efe
194 changed files with 144267 additions and 0 deletions
+182
View File
@@ -0,0 +1,182 @@
"""
AUTHOR:
Khushal P Soonderji
DATE:
Friday, 27th Dec., 2024.
OBJECTIVE:
To provide a data model for describing the API response from Zerodha's Kite APIs.
REFERENCES:
N/A
DOWNLOADS:
N/A
"""
# *****************************************************************************************************************
# ***** ****
# *** IMPORT ***
# ***** ****
# *****************************************************************************************************************
# To make sibling directories accessible for imports:
import sys
sys.path.append(".")
sys.path.append("..")
# For making data behaviour_models:
from pydantic import BaseModel, Field, field_validator, model_validator
from typing import Optional, Literal, Union, Dict, List, Any
# My utils:
from utils_v2.string import json
from utils_v2.string import regex
# *****************************************************************************************************************
# ***** ****
# *** MACROS / ONE-TIME INIT ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** VARIABLES ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** FUNCTIONS ***
# ***** ****
# *****************************************************************************************************************
class ZerodhaKiteApiResponse(BaseModel):
action: str = Field(frozen = True, default = None)
url: str = Field(frozen = True)
method: str = Field(frozen = True)
response: Any = None
httpCode: int = None
success: bool = False
message: str = None
data: Any = None
errorType: str = None
exception: Any = None
# ┏┓ ┏•
# ┃ ┏┓┏┓╋┓┏┓
# ┗┛┗┛┛┗┛┗┗┫
# ┛
class Config:
extra = "forbid"
# ┏┓ ┏┓
# ┃ ┓┏┏╋┏┓┏┳┓ ┣ ┓┏┏┓┏┏
# ┗┛┗┻┛┗┗┛┛┗┗ ┻ ┗┻┛┗┗┛
def to_markdown(self) -> str:
"""
Use this to summarize the values held in this instance into a markdown-formatted string that can be sent out to
admins on chat apps like Telegram.
:return: A string in markdown format.
"""
if self.exception: message = "❌ *ZERODHA (KITE) API EXCEPTION:* ❌\n\n"
else: message = "*ZERODHA (KITE) RESPONSE:*\n\n"
message += f"*ACTION:*\n`{self.action}`\n\n"
message += f"*URL:*\n`{self.url}`\n\n"
message += f"*METHOD:*\n`{self.method}`\n\n"
message += f"*RESPONSE:*\n`{self.response}`\n\n"
message += f"*SUCCESS:*\n`{self.success}`\n\n"
message += f"*ERROR TYPE:*\n`{self.errorType}`\n\n"
message += f"*MESSAGE:*\n`{self.message}`\n\n"
message += f"*EXCEPTION:*\n`{self.exception.__class__.__name__}: {str(self.exception)}`\n\n"
return message
async def get_content(self) -> bytes:
"""
Get the raw binary content of the body of the response.
:return: Raw bytes from the response payload.
"""
try: return self.response.content
except: return b""
async def get_json(self, note_error: bool = False) -> dict | list:
"""
Get the JSON from the body of the response.
:return: A dict or list that represents the JSON payload received in the response.
"""
try:
response_json = self.response.json()
if note_error: await self.note_error(response_json)
return response_json
except: return {}
async def note_error(self, response_json: dict = None) -> None:
"""
Zerodha has two standard response structures - one for success, one for failure. Refer to their documentation.
DOCUMENTATION:
01. https://kite.trade/docs/connect/v3/response-structure/
:return: None.
"""
# If no API was called, we make no changes:
if self.response is None:
return None
# If any API was called:
response_json = response_json or await self.get_json()
response_status = response_json["status"]
# If the API call was successful:
if response_status == "success":
self.success = True
# If the API call failed:
else:
self.success = False
self.errorType = response_json["error_type"]
self.message = response_json["message"]
if isinstance(self.message, str): self.message.replace("`", "'")
# *****************************************************************************************************************
# ***** ****
# *** MAIN PROGRAM ***
# ***** ****
# *****************************************************************************************************************
if __name__ == "__main__":
pass
+248
View File
@@ -0,0 +1,248 @@
"""
AUTHOR:
Khushal P Soonderji
DATE:
Saturday, 21st Dec., 2024.
OBJECTIVE:
To provide a data model for describing the tokens to be used for Zerodha Kite.
REFERENCES:
N/A
DOWNLOADS:
N/A
"""
# *****************************************************************************************************************
# ***** ****
# *** IMPORT ***
# ***** ****
# *****************************************************************************************************************
# To make sibling directories accessible for imports:
import sys
sys.path.append(".")
sys.path.append("..")
# For making data behaviour_models:
from pydantic import BaseModel, Field, field_validator, model_validator, AwareDatetime
from typing import Optional, Literal, Union, Dict, List, Any
# Related to Google:
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
# My utils:
from utils_v2.string import json
from utils_v2.string import regex
from utils_v2.date_time import date_time
# To work with date and time:
import datetime
import dateparser
# To make API calls:
import httpx
# *****************************************************************************************************************
# ***** ****
# *** MACROS / ONE-TIME INIT ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** VARIABLES ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** FUNCTIONS ***
# ***** ****
# *****************************************************************************************************************
class ZerodhaKiteAuthTokens(BaseModel):
userType: str | None = Field(
description = "the type of the user",
default = None,
alias = "user_type",
examples = ["individual/ind_with_nom"]
)
userId: str = Field(
description = "the id of the user as assigned by zerodha",
alias = "user_id",
examples = ["ABC123"]
)
email: str | None = Field(
description = "the email id of the user",
default = None,
alias = "email"
)
name: str = Field(
description = "the name of the user",
alias = "user_name"
)
displayName: str | None = Field(
description = "the short display name of the user",
default = None,
alias = "user_shortname"
)
displayPictureUrl: str | None = Field(
description = "the display picture of the user",
default = None,
alias = "avatar_url"
)
exchanges: List[str] = Field(
description = "the list of exchanges this user can trade on",
alias = "exchanges"
)
products: List[str] = Field(
description = "the list of products (offered by the broker) this user can avail",
alias = "products"
)
orderTypes: List[str] = Field(
description = "the list of order types this user can place",
alias = "order_types"
)
accessToken: str = Field(
description = "the main access token to be used in actual requests",
alias = "access_token"
)
refreshToken: str | None = Field(
description = "token to be used to refresh the access token; may not be provided",
default = None,
alias = "refresh_token"
)
publicToken: str | None = Field(
description = "undocumented on their official documentation",
default = None,
alias = "public_token"
)
loginTs: AwareDatetime = Field(
description = "the time (utc) at which this user logged in",
alias = "login_time"
)
# ┏┓ ┏•
# ┃ ┏┓┏┓╋┓┏┓
# ┗┛┗┛┛┗┛┗┗┫
# ┛
class Config:
extra = "ignore"
populate_by_name = True
# ┓┏ ┓• ┓ •
# ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
# ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗
@field_validator("loginTs", mode = "before")
def parse_dates(cls, value):
if not isinstance(value, datetime.datetime):
parsed = date_time.parse_date_time(
value,
date_formats = ["%Y-%m-%d %H:%M:%S"],
timezone = date_time.TIMEZONE_IST
)
value = parsed if isinstance(parsed, datetime.datetime) else dateparser.parse(value)
if isinstance(value, datetime.datetime): value = date_time.to_timezone(value, date_time.TIMEZONE_UTC)
return value
# ┏┓ •
# ┃┃┏┓┏┓┏┓┏┓┏┓╋┓┏┓┏
# ┣┛┛ ┗┛┣┛┗ ┛ ┗┗┗ ┛
# ┛
pass
# ┏┓ ┏┓
# ┃ ┓┏┏╋┏┓┏┳┓ ┣ ┓┏┏┓┏┏
# ┗┛┗┻┛┗┗┛┛┗┗ ┻ ┗┻┛┗┗┛
pass
# *****************************************************************************************************************
# ***** ****
# *** MAIN PROGRAM ***
# ***** ****
# *****************************************************************************************************************
if __name__ == "__main__":
sample_token = {
"user_type": "individual/ind_with_nom",
"email": "khushalpradipsoonderji@gmail.com",
"user_name": "Khushal Pradip Soonderji",
"user_shortname": "Khushal",
"broker": "ZERODHA",
"exchanges": [
"NSE",
"BSE",
"NFO",
"MF"
],
"products": [
"CNC",
"NRML",
"MIS",
"BO",
"CO"
],
"order_types": [
"MARKET",
"LIMIT",
"SL",
"SL-M"
],
"avatar_url": None,
"user_id": "ABC123",
"api_key": "same-as-api-key-input-to-this-func",
"access_token": "use-this-for-subsequent-activities-like-data-feeds",
"public_token": "???",
"refresh_token": "",
"enctoken": "???",
"login_time": "2024-12-20 13:23:20",
"meta": {
"demat_consent": "consent"
}
}
model = ZerodhaKiteAuthTokens(**sample_token)
print(json.to_string(model.model_dump(), default = str))
+222
View File
@@ -0,0 +1,222 @@
"""
AUTHOR:
Khushal P Soonderji
DATE:
Monday, 6th Jan., 2024.
OBJECTIVE:
To provide a data model for describing the instruments supported by Zerodha Kite.
REFERENCES:
N/A
DOWNLOADS:
N/A
"""
# *****************************************************************************************************************
# ***** ****
# *** IMPORT ***
# ***** ****
# *****************************************************************************************************************
# To make sibling directories accessible for imports:
import sys
sys.path.append(".")
sys.path.append("..")
# For system-level activities:
import io
# For making data behaviour_models:
from pydantic import BaseModel, Field, field_validator, model_validator, AwareDatetime
from typing import Optional, Literal, Union, Dict, List, Any
# Related to Google:
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
# My utils:
from utils_v2.string import json
from utils_v2.string import regex
from utils_v2.date_time import date_time
# To work with date and time:
import datetime
import dateparser
# For working with tabulated data:
import pandas as pd
# To make API calls:
import httpx
# *****************************************************************************************************************
# ***** ****
# *** MACROS / ONE-TIME INIT ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** VARIABLES ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** FUNCTIONS ***
# ***** ****
# *****************************************************************************************************************
class ZerodhaKiteInstrument(BaseModel):
instrumentToken: int = Field(
description = "The token by which Zerodha recognizes this instrument.",
frozen = True,
alias = "instrument_token"
)
exchangeToken: int | str = Field(
description = "The way the exchange recognizes this instrument.",
frozen = True,
alias = "exchange_token"
)
symbol: str | None = Field(
description = "The trading symbol pf this instrument.",
frozen = True,
alias = "tradingsymbol"
)
name: str | None = Field(
description = "The name of the company (for stocks), or the trading symbol (for derivatives).",
frozen = True,
alias = "name"
)
ltp: float | int = Field(
description = "The last price at which this instrument was traded.",
frozen = True,
alias = "last_price"
)
expiry: str | None = Field(
description = "The expiry date (if derivative).",
frozen = True,
alias = "expiry"
)
strike: float | int | None = Field(
description = "The strike price (if option).",
frozen = True,
alias = "strike"
)
tickSize: float | int = Field(
description = "The minimum value by which the price must move to change.",
frozen = True,
alias = "tick_size"
)
lotSize: float | int = Field(
description = "The minimum trading qty. (if derivative).",
frozen = True,
alias = "lot_size"
)
segment: str = Field(
description = "The segment that the instrument belongs to.",
frozen = True,
alias = "segment"
)
instrumentType: str = Field(
description = "the subtype of the 'segment'.",
frozen = True,
alias = "instrument_type"
)
exchange: str = Field(
description = "The exchange on which this instrument is traded.",
alias = "exchange"
)
# ┏┓ ┏•
# ┃ ┏┓┏┓╋┓┏┓
# ┗┛┗┛┛┗┛┗┗┫
# ┛
class Config:
extra = "ignore"
populate_by_name = True
# ┓┏ ┓• ┓ •
# ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
# ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗
pass
# ┏┓ •
# ┃┃┏┓┏┓┏┓┏┓┏┓╋┓┏┓┏
# ┣┛┛ ┗┛┣┛┗ ┛ ┗┗┗ ┛
# ┛
pass
# ┏┓ ┏┓
# ┃ ┓┏┏╋┏┓┏┳┓ ┣ ┓┏┏┓┏┏
# ┗┛┗┻┛┗┗┛┛┗┗ ┻ ┗┻┛┗┗┛
def __str__(self):
return f"{self.exchange}:{self.symbol}"
def __repr__(self):
return str(self)
@staticmethod
def from_api_data(api_data: bytes | io.BytesIO | pd.DataFrame | List[dict] | dict) -> "ZerodhaKiteInstrument":
# Convert the input to a list of dicts:
if isinstance(api_data, bytes): api_data = io.BytesIO(api_data)
if isinstance(api_data, io.BytesIO): api_data = pd.read_csv(api_data)
if isinstance(api_data, pd.DataFrame):
api_data = api_data.map(lambda x: None if pd.isna(x) else x)
api_data = api_data.to_dict(orient = "records")
if isinstance(api_data, dict): api_data = [api_data]
# Model the records and return the values:
modelled_instruments = [ZerodhaKiteInstrument(**instrument) for instrument in api_data]
return modelled_instruments
# *****************************************************************************************************************
# ***** ****
# *** MAIN PROGRAM ***
# ***** ****
# *****************************************************************************************************************
if __name__ == "__main__":
pass
+358
View File
@@ -0,0 +1,358 @@
"""
AUTHOR:
Khushal P Soonderji
DATE:
Tuesday, 7th jan., 2024.
OBJECTIVE:
To provide a structure to represent trading tick updates from Zerodha.
REFERENCES:
N/A
DOWNLOADS:
N/A
"""
# *****************************************************************************************************************
# ***** ****
# *** IMPORT ***
# ***** ****
# *****************************************************************************************************************
# To make sibling directories accessible for imports:
import sys
sys.path.append(".")
sys.path.append("..")
# For making data behaviour_models:
from pydantic import BaseModel, Field, field_validator, PastDatetime, model_validator, AwareDatetime, computed_field
from typing import Optional, Literal, Union, List
# My utils:
from utils_v2.string import json
from utils_v2.string import regex
from utils_v2.date_time import date_time
# To work with date and time:
import datetime
# *****************************************************************************************************************
# ***** ****
# *** MACROS / ONE-TIME INIT ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** VARIABLES ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** FUNCTIONS ***
# ***** ****
# *****************************************************************************************************************
class OneZerodhaKiteMarketDepth(BaseModel):
price: float = Field(
description = "a price at which trader(s) are willing to trade this instrument",
frozen = True,
alias = "price"
)
qty: int = Field(
description = "the no. of shares available at the above price",
frozen = True,
alias = "quantity"
)
orders: int = Field(
description = "how many orders have contributed to the above quantity",
frozen = True,
alias = "orders"
)
@computed_field
def lqdty(self) -> float:
return self.price * self.qty
# ┏┓ ┏•
# ┃ ┏┓┏┓╋┓┏┓
# ┗┛┗┛┛┗┛┗┗┫
# ┛
class Config:
extra = "forbid"
# ---------------------------------------------------------------------------------------------------------------------
class ZerodhaKiteMarketDepth(BaseModel):
buy: List[OneZerodhaKiteMarketDepth] = Field(
description = "the buying side market depth",
frozen = True
)
sell: List[OneZerodhaKiteMarketDepth] = Field(
description = "the selling side market depth",
frozen = True
)
# ┏┓ ┏•
# ┃ ┏┓┏┓╋┓┏┓
# ┗┛┗┛┛┗┛┗┗┫
# ┛
class Config:
extra = "forbid"
# ┓┏ ┓• ┓ •
# ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
# ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗
@field_validator("buy", mode = "after")
def sort_buying_depth(cls, value):
value.sort(key = lambda x: x.price, reverse = True)
return value
@field_validator("sell", mode = "after")
def sort_selling_depth(cls, value):
value.sort(key = lambda x: x.price, reverse = False)
return value
# ---------------------------------------------------------------------------------------------------------------------
class ZerodhaKiteTick(BaseModel):
tickMode: Literal["ltp", "quote", "full"] = Field(
description = "The mode in which this tick was received.",
frozen = True
)
instrumentToken: int = Field(
description = "The code by which Zerodha identifies this instrument.",
frozen = True
)
tradeable: bool = Field(
description = "Whether, or not, this instrument is tradeable.",
frozen = True
)
exchange: str = Field(
description = "The exchange on which this instrument gets traded.",
frozen = True
)
prevClose: float | None = Field(
description = "The previous session's closing price for this instrument.",
frozen = True,
default = None,
validate_default = True
)
ltp: float = Field(
description = "The last price of this instrument.",
frozen = True
)
qty: int | None = Field(
description = "How many units were traded in this tick.",
frozen = True,
default = None,
validate_default = True
)
chg: float | None = Field(
description = "The absolute change since the previous close.",
frozen = True,
default = None,
validate_default = True
)
pChg: float | None = Field(
description = "The percentage change since the previous close.",
frozen = True,
default = None,
validate_default = True
)
o: float | None = Field(
description = "This session's open price.",
frozen = True,
default = None,
validate_default = True
)
h: float | None = Field(
description = "This session's highest price.",
frozen = True,
default = None,
validate_default = True
)
l: float | None = Field(
description = "This session's lowest price.",
frozen = True,
default = None,
validate_default = True
)
c: float | None = Field(
description = "This session's close price; typically the same as the LTP.",
frozen = True,
default = None,
validate_default = True
)
totVol: int | None = Field(
description = "The total volume of this instrument that has been traded in this session.",
frozen = True,
default = None,
validate_default = True
)
vwap: float | None = Field(
description = "The volume weighted average price in this session.",
frozen = True,
default = None,
validate_default = True
)
totBuyQty: int | None = Field(
description = "The total open buy qty. on the exchange for this symbol.",
frozen = True,
default = None,
validate_default = True
)
totSellQty: int | None = Field(
description = "The total open sell qty. on the exchange for this symbol.",
frozen = True,
default = None,
validate_default = True
)
oi: int | None = Field(
description = "The total open interest of this instrument (if derivative).",
frozen = True,
default = None,
validate_default = True
)
oiDayHigh: int | None = Field(
description = "This session's highest open interest of this instrument (if derivative).",
frozen = True,
default = None,
validate_default = True
)
oiDayLow: int | None = Field(
description = "This session's lowest open interest of this instrument (if derivative).",
frozen = True,
default = None,
validate_default = True
)
tradeTs: AwareDatetime | None = Field(
description = "The last trade time (UTC) of this instrument.",
frozen = True,
default = None,
validate_default = True
)
tradeTz: str | None = Field(
description = "The timezone (pytz compatible) in which the last trade time should be interpreted.",
frozen = True,
default = None,
validate_default = True,
examples = ["UTC", "Asia/Kolkata"]
)
exchgTs: AwareDatetime | None = Field(
description = "The time (UTC) at which this update was received from the exchange.",
frozen = True,
default = None,
validate_default = True
)
exchgTz: str | None = Field(
description = "The timezone (pytz compatible) in which the exchange's time should be interpreted.",
frozen = True,
default = None,
validate_default = True,
examples = ["UTC", "Asia/Kolkata"]
)
depth: ZerodhaKiteMarketDepth | None = Field(
description = "The market depth data for this instrument at the time of this tick.",
frozen = True,
default = None,
validate_default = True
)
# ┏┓ ┏┓ ┓ ┏┓• ┓ ┓
# ┣┫┓┏╋┏┓━━┃ ┏┓┏┳┓┏┓┓┏╋┏┓┏┫ ┣ ┓┏┓┃┏┫┏
# ┛┗┗┻┗┗┛ ┗┛┗┛┛┗┗┣┛┗┻┗┗ ┗┻ ┻ ┗┗ ┗┗┻┛
# ┛
pass
# ┏┓ ┏•
# ┃ ┏┓┏┓╋┓┏┓
# ┗┛┗┛┛┗┛┗┗┫
# ┛
class Config:
extra = "forbid"
# ┏┓ ┏┓
# ┃ ┓┏┏╋┏┓┏┳┓ ┣ ┓┏┏┓┏┏
# ┗┛┗┻┛┗┗┛┛┗┗ ┻ ┗┻┛┗┗┛
pass
# ┓┏ ┓• ┓ •
# ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
# ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗
pass
# *****************************************************************************************************************
# ***** ****
# *** MAIN PROGRAM ***
# ***** ****
# *****************************************************************************************************************
if __name__ == "__main__":
pass
+257
View File
@@ -0,0 +1,257 @@
"""
AUTHOR:
Khushal P Soonderji
DATE:
Monday, 6th Jan., 2024.
OBJECTIVE:
To provide a data model for describing the margin/funds of a user of Zerodha Kite.
REFERENCES:
N/A
DOWNLOADS:
N/A
"""
# *****************************************************************************************************************
# ***** ****
# *** IMPORT ***
# ***** ****
# *****************************************************************************************************************
# To make sibling directories accessible for imports:
import sys
sys.path.append(".")
sys.path.append("..")
# For making data behaviour_models:
from pydantic import BaseModel, Field, field_validator, model_validator, AwareDatetime
from typing import Optional, Literal, Union, Dict, List, Any
# Related to Google:
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
# My utils:
from utils_v2.string import json
from utils_v2.string import regex
from utils_v2.date_time import date_time
# To work with date and time:
import datetime
import dateparser
# To make API calls:
import httpx
# *****************************************************************************************************************
# ***** ****
# *** MACROS / ONE-TIME INIT ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** VARIABLES ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** FUNCTIONS ***
# ***** ****
# *****************************************************************************************************************
class AvailableFunds(BaseModel):
adhocMargin: float | int = Field(default = 0, alias = "adhoc_margin")
cash: float | int = Field(default = 0, alias = "cash")
openingBalance: float | int = Field(default = 0, alias = "opening_balance")
liveBalance: float | int = Field(default = 0, alias = "live_balance")
collateral: float | int = Field(default = 0, alias = "collateral")
intradayPayin: float | int = Field(default = 0, alias = "intraday_payin")
# ┏┓ ┏•
# ┃ ┏┓┏┓╋┓┏┓
# ┗┛┗┛┛┗┛┗┗┫
# ┛
class Config:
extra = "ignore"
populate_by_name = True
# ┓┏ ┓• ┓ •
# ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
# ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗
pass
# ┏┓ •
# ┃┃┏┓┏┓┏┓┏┓┏┓╋┓┏┓┏
# ┣┛┛ ┗┛┣┛┗ ┛ ┗┗┗ ┛
# ┛
pass
# ┏┓ ┏┓
# ┃ ┓┏┏╋┏┓┏┳┓ ┣ ┓┏┏┓┏┏
# ┗┛┗┻┛┗┗┛┛┗┗ ┻ ┗┻┛┗┗┛
pass
# ---------------------------------------------------------------------------------------------------------------------
class UtilizedFunds(BaseModel):
debits: float | int = Field(default = 0, alias = "debits")
exposure: float | int = Field(default = 0, alias = "exposure")
m2mRealized: float | int = Field(default = 0, alias = "m2m_realised")
m2mUnrealized: float | int = Field(default = 0, alias = "m2m_unrealised")
optionPremium: float | int = Field(default = 0, alias = "option_premium")
payout: float | int = Field(default = 0, alias = "payout")
span: float | int = Field(default = 0, alias = "span")
holdingSales: float | int = Field(default = 0, alias = "holding_sales")
turnover: float | int = Field(default = 0, alias = "turnover")
liquidCollateral: float | int = Field(default = 0, alias = "liquid_collateral")
stockCollateral: float | int = Field(default = 0, alias = "stock_collateral")
equity: float | int = Field(default = 0, alias = "equity")
delivery: float | int = Field(default = 0, alias = "delivery")
# ┏┓ ┏•
# ┃ ┏┓┏┓╋┓┏┓
# ┗┛┗┛┛┗┛┗┗┫
# ┛
class Config:
extra = "ignore"
populate_by_name = True
# ┓┏ ┓• ┓ •
# ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
# ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗
pass
# ┏┓ •
# ┃┃┏┓┏┓┏┓┏┓┏┓╋┓┏┓┏
# ┣┛┛ ┗┛┣┛┗ ┛ ┗┗┗ ┛
# ┛
pass
# ┏┓ ┏┓
# ┃ ┓┏┏╋┏┓┏┳┓ ┣ ┓┏┏┓┏┏
# ┗┛┗┻┛┗┗┛┛┗┗ ┻ ┗┻┛┗┗┛
pass
# ---------------------------------------------------------------------------------------------------------------------
class SegmentInfo(BaseModel):
enabled: bool = Field(default = False, alias = "enabled")
net: float | int = Field(default = 0, alias = "net")
available: AvailableFunds = Field(default = AvailableFunds(), alias = "available")
utilized: UtilizedFunds = Field(default = UtilizedFunds(), alias = "utilised")
# ┏┓ ┏•
# ┃ ┏┓┏┓╋┓┏┓
# ┗┛┗┛┛┗┛┗┗┫
# ┛
class Config:
extra = "ignore"
populate_by_name = True
# ┓┏ ┓• ┓ •
# ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
# ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗
pass
# ┏┓ •
# ┃┃┏┓┏┓┏┓┏┓┏┓╋┓┏┓┏
# ┣┛┛ ┗┛┣┛┗ ┛ ┗┗┗ ┛
# ┛
pass
# ┏┓ ┏┓
# ┃ ┓┏┏╋┏┓┏┳┓ ┣ ┓┏┏┓┏┏
# ┗┛┗┻┛┗┗┛┛┗┗ ┻ ┗┻┛┗┗┛
pass
# ---------------------------------------------------------------------------------------------------------------------
class ZerodhaKiteUserFunds(BaseModel):
equity: SegmentInfo = Field(default = SegmentInfo(), alias = "equity")
commodity: SegmentInfo = Field(default = SegmentInfo(), alias = "commodity")
# ┏┓ ┏•
# ┃ ┏┓┏┓╋┓┏┓
# ┗┛┗┛┛┗┛┗┗┫
# ┛
class Config:
extra = "ignore"
populate_by_name = True
# ┓┏ ┓• ┓ •
# ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
# ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗
pass
# ┏┓ •
# ┃┃┏┓┏┓┏┓┏┓┏┓╋┓┏┓┏
# ┣┛┛ ┗┛┣┛┗ ┛ ┗┗┗ ┛
# ┛
pass
# ┏┓ ┏┓
# ┃ ┓┏┏╋┏┓┏┳┓ ┣ ┓┏┏┓┏┏
# ┗┛┗┻┛┗┗┛┛┗┗ ┻ ┗┻┛┗┗┛
pass
# *****************************************************************************************************************
# ***** ****
# *** MAIN PROGRAM ***
# ***** ****
# *****************************************************************************************************************
if __name__ == "__main__":
pass
+177
View File
@@ -0,0 +1,177 @@
"""
AUTHOR:
Khushal P Soonderji
DATE:
Monday, 6th Jan., 2024.
OBJECTIVE:
To provide a data model for describing the profile of a user of Zerodha Kite.
REFERENCES:
N/A
DOWNLOADS:
N/A
"""
# *****************************************************************************************************************
# ***** ****
# *** IMPORT ***
# ***** ****
# *****************************************************************************************************************
# To make sibling directories accessible for imports:
import sys
sys.path.append(".")
sys.path.append("..")
# For making data behaviour_models:
from pydantic import BaseModel, Field, field_validator, model_validator, AwareDatetime
from typing import Optional, Literal, Union, Dict, List, Any
# Related to Google:
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
# My utils:
from utils_v2.string import json
from utils_v2.string import regex
from utils_v2.date_time import date_time
# To work with date and time:
import datetime
import dateparser
# To make API calls:
import httpx
# *****************************************************************************************************************
# ***** ****
# *** MACROS / ONE-TIME INIT ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** VARIABLES ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** FUNCTIONS ***
# ***** ****
# *****************************************************************************************************************
class ZerodhaKiteUserProfile(BaseModel):
userType: str | None = Field(
description = "the type of the user",
default = None,
alias = "user_type",
examples = ["individual/ind_with_nom"]
)
userId: str = Field(
description = "the id of the user as assigned by zerodha",
alias = "user_id",
examples = ["ABC123"]
)
email: str | None = Field(
description = "the email id of the user",
default = None,
alias = "email"
)
name: str = Field(
description = "the name of the user",
alias = "user_name"
)
displayName: str | None = Field(
description = "the short display name of the user",
default = None,
alias = "user_shortname"
)
displayPictureUrl: str | None = Field(
description = "the display picture of the user",
default = None,
alias = "avatar_url"
)
exchanges: List[str] = Field(
description = "the list of exchanges this user can trade on",
alias = "exchanges"
)
products: List[str] = Field(
description = "the list of products (offered by the broker) this user can avail",
alias = "products"
)
orderTypes: List[str] = Field(
description = "the list of order types this user can place",
alias = "order_types"
)
# ┏┓ ┏•
# ┃ ┏┓┏┓╋┓┏┓
# ┗┛┗┛┛┗┛┗┗┫
# ┛
class Config:
extra = "ignore"
populate_by_name = True
# ┓┏ ┓• ┓ •
# ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
# ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗
pass
# ┏┓ •
# ┃┃┏┓┏┓┏┓┏┓┏┓╋┓┏┓┏
# ┣┛┛ ┗┛┣┛┗ ┛ ┗┗┗ ┛
# ┛
pass
# ┏┓ ┏┓
# ┃ ┓┏┏╋┏┓┏┳┓ ┣ ┓┏┏┓┏┏
# ┗┛┗┻┛┗┗┛┛┗┗ ┻ ┗┻┛┗┗┛
pass
# *****************************************************************************************************************
# ***** ****
# *** MAIN PROGRAM ***
# ***** ****
# *****************************************************************************************************************
if __name__ == "__main__":
pass