Hedging Strategies Utilizing Delta Exchange API in Python

Identify ATM Strike Price Symbol through Search and Sorting Method for Trading Straddle Strategy:


For Instructions Watch The Video Here:



import requests 
import pandas as pd

underlying_asset_symbols='BTC'
expiry_date='02-09-2026'

url=f"https://api.india.delta.exchange/v2/tickers?contract_types=call_options,put_options&underlying_asset_symbols={underlying_asset_symbols}&expiry_date={expiry_date}"

df=pd.json_normalize(requests.get(url).json().get('result'))
df['strike_price']=pd.to_numeric(df['strike_price'])
spot_price=df['spot_price'].astype(float).loc[0]
atm_strike=df.loc[(df['strike_price']-spot_price).abs().idxmin(), 'strike_price']
date=expiry_date.replace('-','')
ce_symbol=f'C-{underlying_asset_symbols}-{atm_strike}-{date}'
pe_symbol=f'P-{underlying_asset_symbols}-{atm_strike}-{date}'
print(ce_symbol,pe_symbol)

Ant-A3 API - The Official Python SDK for Smart Trading

How to Begin an Options Hedging Strategy in Python:


For Instructions Watch The Video Here:



from TradeMaster.TradeSync import *
import dbm
db=dbm.open('alicedb','r')
username=db['username'].decode()
api_secret=db['api_secret'].decode()
authCode='authCode'
trade=TradeHub(user_id=username,auth_code=authCode,secret_key=api_secret)
trade.get_session_id()
tradingsymbol='NIFTY'
expiry=0
display_interval='1'
symbol=pd.DataFrame(trade.get_Underlying(exchange=Exchange.NSE_FO)['result'][0]['list_underlying'])
UNDERLYING=symbol[symbol[0]==tradingsymbol].to_string(index=False,header=None)
expiry = trade.get_Underlying_expiry(exchange=Exchange.NSE_FO, underlying=UNDERLYING)['result'][0]['underlying_expiry'][expiry]
data = trade.get_Option_chain(exchange=Exchange.NSE_FO, underlying=UNDERLYING, interval=display_interval, expiry=expiry)['result'][0]['data']
df = pd.json_normalize(data, sep='_')
print(df)
last_price=df['strikeprice'].astype(float).iloc[int(display_interval)]
strikelevel=df['strikeprice'].astype(float).diff().iloc[1]
strikeprice=strikelevel*round(last_price/strikelevel)
ce_itm=strikeprice-strikelevel
print(ce_itm)

Easy Fetch of Option Chain Terminal Data Utilzing Alice Blue ANT-A3 API in Python:


For Instructions Watch The Video Here:


  
from TradeMaster.TradeSync import *
import dbm
db=dbm.open('alicedb','r')
username=db['username'].decode()
api_secret=db['api_secret'].decode()
authCode='authCode'
trade=TradeHub(user_id=username,auth_code=authCode,secret_key=api_secret)
trade.get_session_id()
tradingsymbol='WIPRO'
symbol=pd.DataFrame(trade.get_Underlying(exchange=Exchange.NSE_FO)['result'][0]['list_underlying'])
UNDERLYING=symbol[symbol[0]==tradingsymbol].to_string(index=False,header=None)
expiry = trade.get_Underlying_expiry(exchange=Exchange.NSE_FO, underlying=UNDERLYING)['result'][0]['underlying_expiry'][0]
data = trade.get_Option_chain(exchange=Exchange.NSE_FO, underlying=UNDERLYING, interval='9', expiry=expiry)['result'][0]['data']
df = pd.json_normalize(data, sep='_')
print(df)
 
 

Visualize Indian Stock Market Historical Data from ANT-A3 API Utilizing Python:


For Instructions Watch The Video Here:


  
from TradeMaster.TradeSync import *
import dbm
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
import mplfinance as mpf
db=dbm.open('alicedb','r')
username=db['username'].decode()
api_secret=db['api_secret'].decode()
authCode='authCode'
trade=TradeHub(user_id=username,auth_code=authCode,secret_key=api_secret)
trade.get_session_id()
data=trade.get_HistoricalData(instrument=trade.get_instrument(exchange=Exchange.NSE,symbol='TATASTEEL'),
                         resolution='D', # '1' as minute and Expand Further as per interval chart 3, 5.. and for day it goes with 'D'
                         from_datetime=datetime.now() - timedelta(days=7),
                         to_datetime=datetime.now(),
                         indices=False)
df=pd.DataFrame(data)
df['close'].plot()
mpf.plot(df.assign(datetime=lambda d:pd.to_datetime(d['datetime'])).set_index('datetime'),type=
        'candle',style='charles',volume=True)
 
 

If want to check the Ant-A3 API official source library in jupyter notebook then utilize the below code:


  
  import TradeMaster.TradeSync as ts
  %load {ts.__file__}
 

Get Indian Stock Market Historical Data from ANT-A3 API Utilizing Python:


HISTORICAL DATA API — NOTES
* Base URL, endpoint, and payload JSON keys are case-sensitive. Follow the exact format specified in the documentation.
1. Only Day and Minute resolution data is available. Other resolutions (5-min, weekly, etc.) must be derived from these based on your own requirements.
2. Availability on weekdays (Mon–Fri): 5:30 PM to 8:00 AM (next day) only. Not available during market hours.
3. Availability on weekends and holidays: Full day.
Segment-wise Data Availability
--------------------------------
Segment | Data Available
--------------------------------
NSE | 2 years of historical data
NFO | Current expiry data only
CDS | Current expiry data only
MCX | Current expiry data only
BSE | Coming soon
BCD | Coming soon
BFO | Coming soon
--------------------------------

For Instructions Watch The Video Here:


  
from TradeMaster.TradeSync import *
import dbm
from datetime import datetime, timedelta
db=dbm.open('alicedb','r')
username=db['username'].decode()
api_secret=db['api_secret'].decode()
authCode='authCode'
trade=TradeHub(user_id=username,auth_code=authCode,secret_key=api_secret)
trade.get_session_id()
data=trade.get_HistoricalData(instrument=trade.get_instrument(exchange=Exchange.NSE,symbol='TATASTEEL'),
                         resolution='1', # '1' as minute and Expand Further as per interval chart 3, 5.. and for day it goes with 'D'
                         from_datetime=datetime.now() - timedelta(days=7),
                         to_datetime=datetime.now(),
                         indices=False)
print(data)

Call NSE Option Chain Data in a DataFrame:


POST   trade.get_Underlying(exchange=Exchange.NSE_FO)   Fetches the list of available underlyings (indices or symbols) for which Option Chain data can be retrieved.
POST   trade.get_Underlying_expiry(exchange=Exchange.NSE_FO, underlying="TATASTEEL")   Retrieves the list of available expiry dates for a given underlying symbol.
POST   trade.get_Option_chain(exchange=Exchange.NSE_FO,underlying='TATASTEEL',interval='5',expiry='25AUG26')   Fetches the complete Option Chain data for a specific underlying and expiry.

For Instructions Watch The Video Here:


  
from TradeMaster.TradeSync import *
import pandas as pd
import dbm
db=dbm.open('alicedb','r')
username=db['username'].decode()
api_secret=db['api_secret'].decode()
trade=TradeHub(user_id=username,auth_code='authCode',secret_key=api_secret)
trade.get_session_id()
UNDERLYING = "TATASTEEL"
expiry = trade.get_Underlying_expiry(exchange=Exchange.NSE_FO, underlying=UNDERLYING)['result'][0]['underlying_expiry'][0]
data = trade.get_Option_chain(exchange=Exchange.NSE_FO, underlying=UNDERLYING, interval='2', expiry=expiry)['result'][0]['data']

rows = [{'strike': r['strikeprice'], **{f"CE_{k}": v for k, v in r['CE'].items()}, **{f"PE_{k}": v for k, v in r['PE'].items()}} for r in data]

df = pd.DataFrame(data)
print(df)
df.to_csv(f"{UNDERLYING}_option_chain.csv", index=False)

ICICI Direct Automate Trades Utilizing Free of Cost Breeze Connect API in Python

Breeze API: Registration & Login Guide

Breeze API: Checksum Computation & Login

1. App Registration (OAuth 2.0)

Authentication follows the OAuth 2.0 protocol to ensure all request fields are protected from tampering.

To register an app on the Breeze API portal, provide the following:

  • App Name
  • Redirect URL: https://127.0.0.1

After successful registration, you will receive a unique pair of keys:

  • App Key: The unique identity of your application within the API system.
  • Secret Key: Used to encrypt messages sent from your client to the API.

2. Required Request Parameters

Every API request must include the following components:

  • App Key
  • Secret Key
  • Session Token

3. Login Flow

Initiate the login process by navigating to the login URL with your URL-encoded App Key:

https://api.icicidirect.com/apiuser/login?api_key=Your_AppKey

  1. Upon successful login, retrieve the API_Session value displayed in your browser's address bar.
  2. Pass this API_Session value under the key SessionToken in the CustomerDetails API.
  3. The API will respond with a session_token.
  4. Use this session_token as the SessionToken to authenticate all subsequent API requests.

Setup and Installation

Open your terminal or command prompt.
Type pip install breeze-connect to get the official Python SDK.
Open your Python editor or Jupyter Notebook
Get the token from the redirect url as this https://www.profitaddaweb.com/?apisession=your_session_token then paste that token in the given below code with api key, secret and generating session token then go with order placement and queries you prefer.


Video Tutorial

For a visual walkthrough of the process, refer to the official YouTube tutorial:


from breeze_connect import BreezeConnect
import dbm
db=dbm.open('config','r')
api_key=db['api_key'].decode()
api_secret=db['api_secret'].decode()

breeze=BreezeConnect(api_key=api_key)
breeze.generate_session(api_secret=api_secret,session_token='your_session_token')

print(breeze.get_demat_holdings())

Key Rules and Limits


Cost: Completely free of charge for all ICICI Direct customers.
Rate Limits: Maximum of 100 API calls per minute and 5,000 calls per day.
Requirements: An active ICICI Direct trading account and a registered app session token generated daily.

NSE India API Live Analysis Variations Index Gainers in Python

India VIX in Decision Making Fetching Data Directly from NSE India API


Follow the Instructions from the Video then go for the Code Input:

 
import requests
import pandas as pd

url='https://www.nseindia.com/api/equity-stockIndices?index=INDIA VIX'

headers={
    'User-Agent' : 'Mozilla/5.0'

}

response=requests.get(url,headers=headers)
data=response.json()
print(data)


df=pd.concat([pd.DataFrame(data['data'])[['symbol','lastPrice']]])
print(df)

Most Active Securities by Volume NSE India API Live Analysis


Follow the Instructions from the Video then go for the Code Input:

  
import requests
import pandas as pd  

url='https://www.nseindia.com/api/live-analysis-most-active-securities?index=volume'
headers={
    'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebkit/537.36',
    'Accept-Language' : 'en-US, en; q=0.9'
}

response=requests.get(url,headers=headers)
data=response.json()
    


df=pd.concat([pd.DataFrame(data['data'])[['symbol','lastPrice','totalTradedVolume']] ])
df_sorted=df.sort_values('lastPrice').reset_index(drop=True)
print(df_sorted.to_string(index=False))

Most Active Securities by Value NSE India API Live Analysis


Follow the Instructions from the Video then go for the Code Input:

  
import requests   
import pandas as pd  

url='https://www.nseindia.com/api/live-analysis-most-active-securities?index=value'

headers={
    'User-Agent' : 'Mozilla/5.0'

}

response=requests.get(url,headers=headers)
data=response.json()


df=pd.concat([pd.DataFrame(data['data'])[['symbol','lastPrice','totalTradedValue','lastUpdateTime']]])
df_sorted=df.sort_values('lastPrice').reset_index(drop=True)

print(df_sorted.to_string(index=False))

NSE India API Live Analysis Variations Index Gainers in Python


Follow the Instructions from the Video then go for the Code Input:

  
import json
import pandas as pd  

with open('gain.json','r') as f:
    data=json.load(f)
    
categories=['NIFTY', 'BANKNIFTY','NIFTYNEXT50','SecGtr20','SecLwr20','FOSec','allSec']

df=pd.concat([pd.DataFrame(data[cat]['data'])[['symbol','ltp']] for cat in categories if cat in data])
df_sorted=df.sort_values('ltp').reset_index(drop=True)
print(df_sorted.to_string(index=False))

Read NSE Gainers Data Directly from NSE India API


Follow the Instructions from the Video then go for the Code Input:

  
import requests
import pandas as pd  

url='https://www.nseindia.com/api/live-analysis-variations?index=gainers'
headers={
    'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebkit/537.36',
    'Accept-Language' : 'en-US, en; q=0.9'
}

response=requests.get(url,headers=headers)
data=response.json()
    
categories=['FOSec']

df=pd.concat([pd.DataFrame(data[cat]['data'])[['symbol','ltp']] for cat in categories if cat in data])
df_sorted=df.sort_values('ltp').reset_index(drop=True)
print(df_sorted.to_string(index=False))

Visualization of Machine Learning and Data Utilizing Huggingface GenAI API in Python

GenAI for ML with Simple Prompt in Python for Cleaning, Processing and Visualization


For Instructions Follow the above Video then go For the Code Input:



import requests, json
import pandas as pd  

key=open('rhf_api_key.txt','r').read().strip()
def get_mcqs(topic):

	r=requests.post('https://router.huggingface.co/v1/chat/completions',
	headers={'Authorization': f'Bearer {key}'},

	json={
		'model': 'arcee-ai/Trinity-Large-Thinking:featherless-ai',
		'messages':[{'role':'user','content':f'5 MCQs about:{topic} with options such as A, B, C, D. Return Valid JSON array'} 
	]
	}
		)

	content=r.json()['choices'][0]['message']['content']

	return json.loads(content)

data=get_mcqs('Machine Learning Python')
# print(data)
print(pd.DataFrame(data).to_csv('data.csv',index=False))


Visualize ML MCQs & Generate Image Utilizing GenAI Data in Python


For Instructions Follow the above Video then go For the Code Input:



import pandas as pd, matplotlib.pyplot as plt, ast 

df=pd.read_csv('data.csv')
df['options']=df['options'].apply(lambda x: ast.literal_eval(x) if isinstance(x, str) else x)

fig,ax = plt.subplots(figsize=(8.5, 11)); ax.axis('off')
y=0.96

for i,(q, opts, ans) in enumerate(zip(df['question'], df['options'], df['answer']),1):
	ax.text(0.05,y,f"{i}.{q}", fontsize=10, weight='bold',wrap=True); y-=0.05
	for o in opts:
		c=o[0]==ans.strip()
		ax.text(0.08,(y:=y-0.036), f"{'*' if c else 'o'} {o}",
			fontsize=9, color='green' if c else 'black', wrap=True)

	y-=0.09
# plt.show()
plt.savefig('mcq.png',dpi=150,bbox_inches='tight')

Generative AI Utilizing Google Generative AI API in Python

Decision Tree Learning Price Action Sentiment Analysis Utilizing Generative AI in Python:


For Instructions Follow the above Video then go For the Code Input:



import graphviz
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn.feature_extraction.text import TfidfVectorizer
news = [
    "BTCUSD consolidates in the early morning, showing a slight positive drift from ~107,000 to ~107,500 with low volume.",
    "A strong bullish impulse propels BTCUSD higher in the late morning, breaking previous resistance levels and reaching ~109,500, confirmed by high buying volume.",
    "Mid-day period sees BTCUSD consolidating after the initial rally, ranging between ~109,000 and ~109,500, often indicative of an accumulation phase before a further move.",
    "Another powerful bullish surge pushes BTCUSD to new daily highs above 111,000 in the afternoon, accompanied by very high buying volume.",
    "Late trading hours witness profit-taking, causing BTCUSD to pull back from its daily peak towards ~110,000, indicating short-term bearish pressure."
]
labels = [
    1,  # Initial slight positive drift
    1,  # Strong bullish impulse with high volume
    1,  # Consolidation in an uptrend, typically a continuation pattern
    1,  # Second powerful bullish surge to new highs
    -1  # Profit-taking and short-term pullback
]
vec=TfidfVectorizer(max_features=10)
X=vec.fit_transform(news)
clf=DecisionTreeClassifier(max_depth=3,random_state=42).fit(X,labels)
dot=export_graphviz(clf,
                   out_file=None,
                   feature_names=vec.get_feature_names_out(),
                   class_names=['Negative','Positive'],
                   filled=True,rounded=True)
graphviz.Source(dot).render('sentiment_tree',format='png',cleanup=True)
from IPython.display import Image, display
display(Image('senti2.png'))

For Decision Tree Classifier Flow Chart Anlysis Checkout this Code:


import requests
import base64
api_key=open('genai_api_key.txt','r').read().strip()
chart=base64.b64encode(open('sentiment_tree.png','rb').read()).decode("utf-8")
url="https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent"

print(requests.post(
	url,
	headers={'x-goog-api-key':api_key},
	json={'contents':[{
	'parts':[{'text':'Analyse this Flow Chart and Provide me the Details in Few Words and Let me Know Whether it is Positive or Negative'},
             {'inline_data':{'mime_type':'image/jpeg',
                             'data':chart
                 
             }}
             
            ]
	}]}
	).json()['candidates'][0]['content']['parts'][0]['text'])

Price Action Sentiment Analysis Utilizing Generative AI with Chartbot in Python:


For Instructions Follow the above Video then go For the Code Input:



import requests
import base64
api_key=open('genai_api_key.txt','r').read().strip()
chart=base64.b64encode(open('chart.png','rb').read()).decode("utf-8")
url="https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent"
prompt = '''
You are a professional price action and news analyser.
Look carefully at the given candlestick with moving average and volume chart image.

Based on the visible trend, candle patterns, volume behavior and News,
generate high-quality sentiment such as 1: Positive, -1: Negative.

Output strictly in valid list format like this:

Each news should include:
financial_news = [
    "summarized news 1",
    "summarized news 2 and so on....",
]


sentiments = [1, -1 and so on...]  # 1: Positive, -1: Negative
'''
response=requests.post(
	url,
	headers={'x-goog-api-key':api_key},
	json={'contents':[{
	'parts':[{'text':prompt},
             {'inline_data':{'mime_type':'image/jpeg',
                             'data':chart
                 
             }}
             
            ]
	}]}
	).json()['candidates'][0]['content']['parts'][0]['text']
print(response)

Generative AI Utilizing Google Generative AI API in Python:


For Instructions Follow the above and below Video then go For the Code Input:



Follow this Shorts Video as well for Instructions to get your Google Generative AI API Key:



import requests
api_key=open('genai_api_key.txt','r').read().strip()
url="https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent"

print(requests.post(
	url,
	headers={'x-goog-api-key':api_key},
	json={'contents':[{
	'parts':[{'text':'Explain AI in few words'}]
	}]}
	).json()['candidates'][0]['content']['parts'][0]['text'])

Price Action Analysis Utilizing Generative AI API and Chartbot in Python:


For Instructions Follow the above Video then go For the Code Input:



import requests
import base64
api_key=open('genai_api_key.txt','r').read().strip()
chart=base64.b64encode(open('18_10_25.png','rb').read()).decode("utf-8")
url="https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent"

print(requests.post(
	url,
	headers={'x-goog-api-key':api_key},
	json={'contents':[{
	'parts':[{'text':'Analyse this Chart and Provide me the Details of Price Action it Consists'},
             {'inline_data':{'mime_type':'image/jpeg',
                             'data':chart
                 
             }}
             
            ]
	}]}
	).json()['candidates'][0]['content']['parts'][0]['text'])

Output of Price Action Analysis as a Generated Response in Text:


This chart displays the BTCUSD pair on a 15-minute candlestick timeframe, along with trading volume, covering approximately 22 hours from October 17th, 21:00 to October 18th, around 19:00. Here's a detailed analysis of the price action and volume: **Overall Trend & Volatility:** The chart shows a period of significant volatility followed by consolidation, an attempted rally, and then another pullback. The price initially surged, then underwent a sharp correction, followed by a long period of range-bound trading with relatively lower volume, before a moderate bullish push and subsequent rejection. **Key Price Action & Volume Details:** 1. **Oct 17, 21:00 - Oct 18, ~01:00 (Initial Volatility & Peak):** * **Price Action:** The period begins with a strong bullish impulse. BTCUSD quickly rises from approximately **106000** to its peak around **107300 - 107350**. This rapid ascent is characterized by multiple large green candlesticks with some upper wicks, indicating initial strong buying pressure. * After reaching the peak, there's an immediate and sharp reversal. Large red candlesticks dominate, pushing the price back down quickly towards **106200**. There's a slight bounce from this level, but another attempt to reach the prior high is rejected around **107250**, confirming significant resistance. The price then falls further, establishing a temporary bottom around **106200**. * **Volume:** This entire initial phase sees the highest trading volume on the chart. Both the strong bullish push and the subsequent sharp bearish correction are accompanied by very large volume bars (both green and red), indicating high market participation and conviction in these movements. The peak volume occurs during the initial ascent and the subsequent sharp drop, suggesting strong contention between buyers and sellers. 2. **Oct 18, ~01:00 - Oct 18, ~12:00 (Consolidation & Lower Volume):** * **Price Action:** Following the initial volatility, the market enters a prolonged period of consolidation. The price largely trades in a range between **106200** (acting as support) and **107000** (acting as resistance), with some attempts to break higher failing around **106750 - 107000**. * The candlesticks become smaller and choppier, indicative of indecision. There are minor fluctuations up and down within this range, but no clear sustained direction. Several minor rallies are quickly met with selling pressure, and minor dips find buying support. * **Volume:** Volume significantly drops during this phase compared to the initial hours. The volume bars are generally small, reflecting a lack of strong conviction from either buyers or sellers. This is typical for a consolidation phase where market participants are waiting for a clearer direction. 3. **Oct 18, ~12:00 - Oct 18, ~16:00 (Afternoon Rally Attempt):** * **Price Action:** Around 12:00, the price finds strong support again at the **106200 - 106250** level. A new bullish impulse begins, pushing the price upward. It climbs steadily, forming several green candlesticks, reaching approximately **107000 - 107100**. This attempt looks more concerted than the earlier bounces within the consolidation range. * However, the rally again meets resistance at or just below the previous high/resistance zone of **107200 - 107300**. Price fails to break decisively above **107100**. * **Volume:** This rally is accompanied by a noticeable increase in volume, especially during the initial green candles from 12:00 to 13:00. This suggests renewed buying interest and confirms the strength behind this specific upward move. However, as the price approaches the resistance level, volume slightly decreases or becomes mixed, hinting at exhaustion or strong selling pressure entering the market. 4. **Oct 18, ~16:00 - End of Chart (~19:00):** * **Price Action:** After failing to break through the **107000 - 107100** resistance, the price experiences another sharp rejection. Several large red candlesticks quickly push the price back down to around **106750**. * In the final hours shown, the price attempts to stabilize around **106750**, forming smaller green and red candles, but the immediate trend is bearish following the rejection from the afternoon high. * **Volume:** The rejection from the 107000-107100 area is accompanied by a spike in red volume bars, indicating renewed selling pressure. Subsequent volume remains moderate as the price tries to find a new equilibrium. **Key Levels Identified:** * **Resistance:** * **107200 - 107350:** A very strong resistance zone, acting as a ceiling for price rallies. * **107000 - 107100:** A significant psychological and technical resistance level, repeatedly tested and rejected. * **Support:** * **106200 - 106250:** A clear support level, where the price has bounced multiple times after significant drops. * **106750:** An immediate, minor support level formed towards the end of the chart after the latest pullback. In summary, the chart depicts a volatile 22-hour period for BTCUSD, starting with a high-volume surge and crash, followed by a long period of low-volume consolidation within a relatively tight range. A subsequent rally attempt on increasing volume was ultimately rejected by established resistance, leading to another pullback. The market appears to be struggling to break above the **107000-107300** resistance zone.

Deep Learning for Stock Price Prediction

Deep Learning for Stock Close Price Prediction based on Open Price:


For Instructions Follow the above Video then go For the Code Input:



import os
os.environ['TF_CPP_MIN_LOG']='2'
import requests 
import pandas as pd  
from datetime import datetime, timedelta 
import matplotlib.pyplot as plt 
#import tensorflow
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

#get btcusd data from delta exchnage india
base_url="https://api.india.delta.exchange"
url=f"{base_url}/v2/history/candles"
end=int(datetime.now().timestamp())
start=int((datetime.now()-timedelta(days=1)).timestamp())
params={
    'symbol':'BTCUSD',
    'resolution':'15m',
    'start':start,
    'end':end
}
r=requests.get(url,params=params)
data=r.json().get('result',[])
df=pd.DataFrame(data,columns=['time','open','high','low','close','volume']).sort_values('time')
df['time']=pd.to_datetime(df['time'],unit='s')
df['time']=df['time'].dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')
df.set_index('time',inplace=True)
#feature and target
X=df[['open']]
y=df['close']
#model
model=Sequential([Dense(64,activation='relu'),
    Dense(32,activation='relu'),
    Dense(1)
    ])
model.compile(optimizer='adam',loss='mse',metrics=['mae'])

model.fit(X,y,epochs=50)

#predict
predict=model.predict(X)

#plot
plt.plot(df.index,y,label='actual')
plt.plot(df.index,predict,label='predicted',linestyle='--')
plt.show()


Delta Exchange API in Python

Trade Futures & Options on Bitcoin and Ether Elevate your F&O trading with 24/7 open markets, efficient margining and INR settlement

Open Online Delta Exchange India Trading Account Fill the Form with Details as Required.

Click Here to Visit Delta Exchange India

Retrieve HTML Option Chain Data Table Every 30s Utilizing FastAPI:


For Instructions Watch The Video Here:



import requests 
import pandas as pd
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
app=FastAPI()
@app.get("/",response_class=HTMLResponse)
def option_table():
    underlying_asset_symbols='XAUT'
    expiry_date='22-08-2026'

    url=f"https://api.india.delta.exchange/v2/tickers?contract_types=call_options,put_options&underlying_asset_symbols={underlying_asset_symbols}&expiry_date={expiry_date}"

    df=pd.json_normalize(requests.get(url).json().get('result'))
    df=df[['spot_price','symbol','product_id','mark_high_24h','mark_price','mark_low_24h']]
    return HTMLResponse(f"""
        
        {df.to_html(index=False)}
        """
        )

GET Gold Token (XAUT) Option Chain Data from a Single API Call in Python:


For Instructions Watch The Video Here:



import requests 
import pandas as pd

underlying_asset_symbols='XAUT'
expiry_date='22-08-2026'

url=f"https://api.india.delta.exchange/v2/tickers?contract_types=call_options,put_options&underlying_asset_symbols={underlying_asset_symbols}&expiry_date={expiry_date}"

df_option=pd.json_normalize(requests.get(url).json().get('result')).head(10)
print(df_option)

Websocket Feed Private Channels Utilizing API of Delta Exchange India:


For Instructions Follow the Above Video then go For the Code Input:




import websocket
import hashlib
import hmac
import json
import time
from crud import api_key, api_secret

# production websocket base url and api keys/secrets
WEBSOCKET_URL = "wss://socket.india.delta.exchange"
API_KEY = api_key
API_SECRET = api_secret

def on_error(ws, error):
    print(f"Socket Error: {error}")

def on_close(ws, close_status_code, close_msg):
    print(f"Socket closed with status: {close_status_code} and message: {close_msg}")

def on_open(ws):
    print(f"Socket opened")
    # api key authentication
    send_authentication(ws)

def send_authentication(ws):
    method = 'GET'
    timestamp = str(int(time.time()))
    path = '/live'
    signature_data = method + timestamp + path
    signature = generate_signature(API_SECRET, signature_data)
    ws.send(json.dumps({
        "type": "key-auth",
        "payload": {
            "api-key": API_KEY,
            "signature": signature,
            "timestamp": timestamp
        }
    }))

def generate_signature(secret, message):
    message = bytes(message, 'utf-8')
    secret = bytes(secret, 'utf-8')
    hash = hmac.new(secret, message, hashlib.sha256)
    return hash.hexdigest()

def on_message(ws, json_message):
    message = json.loads(json_message)
    # subscribe private channels after successful authentication
    if message['type'] == 'key-auth':
        if message['success']:
            print("Authentication successful")
            # subscribe orders channel for order updates for all contracts
            subscribe(ws, "orders", ["all"])
            # subscribe positions channel for position updates for all contracts
            subscribe(ws, "positions", ["all"])
        else:
            print("Authentication failed")
            print(message)
    else:
        print(json_message)

def subscribe(ws, channel, symbols):
    payload = {
        "type": "subscribe",
        "payload": {
            "channels": [
                {
                    "name": channel,
                    "symbols": symbols
                }
            ]
        }
    }
    ws.send(json.dumps(payload))

if __name__ == "__main__":
  ws = websocket.WebSocketApp(WEBSOCKET_URL, on_message=on_message, on_error=on_error, on_close=on_close)
  ws.on_open = on_open
  ws.run_forever() # runs indefinitely


GET Option Chain Data from a Single API Call in Python:


For Instructions Follow the Above Video then go For the Code Input:




import requests 

underlying_asset_symbols='BTC'
expiry_date='26-10-2025'

url=f"https://api.india.delta.exchange/v2/tickers?contract_types=call_options,put_options&underlying_asset_symbols={underlying_asset_symbols}&expiry_date={expiry_date}"

print(requests.get(url).json())

Websocket Feed Public Channels Utilizing API of Delta Exchange India:


For Instructions Follow the Above Video then go For the Code Input:




import websocket
import json

# production websocket base url
WEBSOCKET_URL = "wss://socket.india.delta.exchange"

def on_error(ws, error):
    print(f"Socket Error: {error}")

def on_close(ws, close_status_code, close_msg):
    print(f"Socket closed with status: {close_status_code} and message: {close_msg}")

def on_open(ws):
  print(f"Socket opened")
  # subscribe tickers of perpetual futures - BTCUSD & ETHUSD, call option C-BTC-95200-200225 and put option - P-BTC-95200-200225
  subscribe(ws, "v2/ticker", ["BTCUSD", "ETHUSD"])
  # subscribe 1 minute ohlc candlestick of perpetual futures - MARK:BTCUSD(mark price) & ETHUSD(ltp), call option C-BTC-95200-200225(ltp) and put option - P-BTC-95200-200225(ltp).
  subscribe(ws, "candlestick_1m", ["MARK:BTCUSD", "ETHUSD"])

def subscribe(ws, channel, symbols):
    payload = {
        "type": "subscribe",
        "payload": {
            "channels": [
                {
                    "name": channel,
                    "symbols": symbols
                }
            ]
        }
    }
    ws.send(json.dumps(payload))

def on_message(ws, message):
    # print json response
    message_json = json.loads(message)
    print(message_json)

if __name__ == "__main__":
  ws = websocket.WebSocketApp(WEBSOCKET_URL, on_message=on_message, on_error=on_error, on_close=on_close)
  ws.on_open = on_open
  ws.run_forever() # runs indefinitely


Place Bracket Order as an Automated Take Profit and Stop Loss Order in Delta:


For Instructions Follow the Video then go For the Code Input:




from cred import *  
import time, hashlib, hmac, requests, json

def generate_signature(secret, msg:str): 
    return hmac.new(secret.encode(), msg.encode(), hashlib.sha256).hexdigest()

method="POST" 
timestamp=str(int(time.time()))
base_url="https://api.india.delta.exchange"
path="/v2/orders/bracket"
url=base_url + path 


body_string={
  "product_id": 86667,
  "product_symbol": "P-BTC-112000-260925",
  "stop_loss_order": {
    "order_type": "market_order",
    "stop_price": "1600"
  },
  "take_profit_order": {
    "order_type": "market_order",
    "stop_price": "100"
  },
  "bracket_stop_trigger_method": "last_traded_price"
}

body=json.dumps(body_string)


signature_data=method + timestamp + path + body
signature=generate_signature(api_secret, signature_data)

headers={
    "api-key":api_key,
    "timestamp":timestamp,
    "signature":signature,
    "Content-Type":"application/json"
}
boid=requests.post(url,headers=headers,data=body)
print(boid.json())



Get Wallet Balances of Delta Exchange India using API in Python:


For Instructions Follow the Video then go For the Code Input:



from cred import *
from delta_rest_client import DeltaRestClient


delta_client = DeltaRestClient(
  base_url='https://api.india.delta.exchange',
  api_key=api_key,
  api_secret=api_secret
)

assets=delta_client.get_assets()

for asset in assets:
  balance=delta_client.get_balances(asset['id'])
  if balance:
    print(balance['asset_id'])

Add Customized | Additional | Subplots such as MACD Indicator to Candlestick Plots:


For Instructions Follow the Video then go For the Code Input:



import requests 
import pandas as pd  
from datetime import datetime, timedelta 
import mplfinance as mpf
base_url="https://api.india.delta.exchange"
url=f"{base_url}/v2/history/candles"
end=int(datetime.now().timestamp())
start=int((datetime.now()-timedelta(days=1)).timestamp())
params={
    'symbol':'BTCUSD',
    'resolution':'15m',
    'start':start,
    'end':end
}
r=requests.get(url,params=params)
data=r.json().get('result',[])
df=pd.DataFrame(data,columns=['time','open','high','low','close','volume']).sort_values('time')
df['time']=pd.to_datetime(df['time'],unit='s')
df['time']=df['time'].dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')
df.set_index('time',inplace=True)
fastperiod=df['close'].ewm(span=12,adjust=False).mean()
slowperiod=df['close'].ewm(span=26,adjust=False).mean()
df['MACD']=fastperiod - slowperiod
df['Signal']=df['MACD'].ewm(span=9,adjust=False).mean()
df['Histogram']=df['MACD'] - df['Signal']
add_plots=[
mpf.make_addplot(df['MACD'],panel=2,color='blue',ylabel='MACD'),
mpf.make_addplot(df['Signal'],panel=2,color='orange'),
mpf.make_addplot(df['Histogram'],type='bar',panel=2,color='gray')
]
mpf.plot(df,type='candle',style='charles',volume=True,addplot=add_plots,title='BTCUSD 15-Minute Candlestick Chart')

Authenticate to Place Orders or Fetch Account related information using Delta API:


For Instructions Follow the Video then go For the Code Input:



from cred import *  
import time, hashlib, hmac, requests 

def generate_signature(secret, msg:str): 
    return hmac.new(secret.encode(), msg.encode(), hashlib.sha256).hexdigest()

method="GET" 
timestamp=str(int(time.time()))
base_url="https://api.india.delta.exchange"
path="/v2/positions"
url=base_url + path 

query_string="?product_id=27"

payload=""

signature_data=method + timestamp + path + query_string + payload 
signature=generate_signature(api_secret, signature_data)

headers={
    "api-key":api_key,
    "timestamp":timestamp,
    "signature":signature,
    "Content-Type":"application/json"
}
positions=requests.get(url,headers=headers,params={"product_id":27})
print(positions.json())

Option Chain Bitcoin - ATM,OTM,ITM Fetched for BTC | ETH Option Trading:


For Instructions Follow the Video then go For the Code Input:



from cred import *
from delta_rest_client import DeltaRestClient
import pandas as pd 

delta_client = DeltaRestClient(
  base_url='https://api.india.delta.exchange',
  api_key=api_key,
  api_secret=api_secret
)
spot_symbol='BTCUSD'
strike_level=500
pe_level=-4000
spot_ticker = delta_client.get_ticker(spot_symbol)
spot_price=round(float(spot_ticker['mark_price']))
strike_price=strike_level * round(spot_price/strike_level) + pe_level
pe_symbol=f'P-BTC-{strike_price}-010825'
pe_ticker = delta_client.get_ticker(pe_symbol)
print(pd.json_normalize(pe_ticker).T)

Fetch Order History of Delta Exchange India using Python API:


For Instructions Follow the Video then go For the Code Input:



from cred import *
from delta_rest_client import DeltaRestClient
import pandas as pd 

delta_client = DeltaRestClient(
  base_url='https://api.india.delta.exchange',
  api_key=api_key,
  api_secret=api_secret
)

response = delta_client.get_ticker('P-BTC-114500-010825')
product_id=response['product_id']
query={'product_id':product_id,'product_id':27}
order_history=delta_client.order_history(query,page_size=1)
print(order_history)

How to Cancel Orders in Delta Exchange India Using Python API:


For Instructions Follow the Video then go For the Code Input:



from cred import *
from delta_rest_client import DeltaRestClient
from delta_rest_client import OrderType
import pandas as pd 

delta_client = DeltaRestClient(
  base_url='https://api.india.delta.exchange',
  api_key=api_key,
  api_secret=api_secret
)

response = delta_client.get_ticker('P-BTC-114500-010825')
product_id=response['product_id']
mark_price=round(float(response['mark_price']),1)
print(product_id,mark_price)
position=delta_client.get_margined_position(product_id)
print(position)
entry_price=round(float(position['entry_price']),1)
lqp=round(float(position['liquidation_price']),1)
size=position['size']
print(entry_price,lqp,size)
order_response=delta_client.place_stop_order(product_id=product_id,
  side='buy',
  size=abs(size),
  limit_price=str(lqp - 100),
  order_type=OrderType.LIMIT,
  stop_price=str(lqp - 50))
order_id=order_response['id']
cancel_order=delta_client.cancel_order(product_id,order_id)
print(cancel_order)


Get Margined Position of Delta Exchange India in Python:


For Instructions Follow the Video then go For the Code Input:


Importing credentials and libraries: The code starts by importing credentials (api_key, api_secret) from a cred module and essential components from the delta_rest_client library. Setting up the API client: It initializes a DeltaRestClient with your API keys and base URL to interact with Delta Exchange's REST API. Fetching ticker information: The code requests the latest ticker data for a specific product: 'P-BTC-117500-010825', which is likely a BTC options contract expiring on 01 Aug 2025 with a strike of 117500. Extracting product ID and mark price: From the ticker response, it extracts the product_id and rounds the mark_price to 1 decimal place. Printing basic market data: It prints the product ID and the rounded mark price. Getting open position: It then fetches the user's current margined position for this product using get_margined_position. Extracting position details: It extracts the entry_price, liquidation_price, and size (number of contracts in the position) from the position response. Printing position data: The entry price, liquidation price, and position size are printed for reference. Calculating stop-loss level: A stop-loss order is prepared with a stop_price set 200 points below the liquidation price and a limit_price 150 points below the same. Placing stop-limit order: The code places a buy stop-limit order with: Size = absolute of current position size (to reverse/exit), Limit Price = liquidation_price - 150, Stop Price = liquidation_price - 200, Order Type = LIMIT. Order side logic: The side='buy' indicates this stop-limit order is probably to close a short (sell) position if the price rises toward liquidation. Final confirmation: Prints the order_response from the API, which includes order ID and confirmation details. Summary: This script automates risk management for a short position on a BTC options contract by dynamically placing a buy stop-limit order near the liquidation zone to reduce losses if the market moves against the trade.


from cred import *
from delta_rest_client import DeltaRestClient
from delta_rest_client import OrderType
import pandas as pd 

delta_client = DeltaRestClient(
  base_url='https://api.india.delta.exchange',
  api_key=api_key,
  api_secret=api_secret
)

response = delta_client.get_ticker('P-BTC-117500-010825')
product_id=response['product_id']
mark_price=round(float(response['mark_price']),1)
print(product_id,mark_price)
position=delta_client.get_margined_position(product_id)
print(position)
entry_price=round(float(position['entry_price']),1)
lqp=round(float(position['liquidation_price']),1)
size=position['size']
print(entry_price,lqp,size)
order_response=delta_client.place_stop_order(product_id=product_id,
  side='buy',
  size=abs(size),
  limit_price=str(lqp - 150),
  order_type=OrderType.LIMIT,
  stop_price=str(lqp - 200))
print(order_response)

How to Place Stop Loss Orders in Delta Exchange India Using Python API:


For Instructions Follow the Video then go For the Code Input:



from cred import *
from delta_rest_client import DeltaRestClient
from delta_rest_client import OrderType
import pandas as pd 

delta_client = DeltaRestClient(
  base_url='https://api.india.delta.exchange',
  api_key=api_key,
  api_secret=api_secret
)

response = delta_client.get_ticker('P-BTC-117500-010825')
product_id=response['product_id']
mark_price=round(float(response['mark_price']),1)
print(product_id,mark_price)
position=delta_client.get_position(product_id)
entry_price=round(float(position['entry_price']),1)
size=position['size']
print(entry_price,size)
order_response=delta_client.place_stop_order(product_id=product_id,
  side='buy',
  size=abs(size),
  limit_price=str(entry_price - 200),
  order_type=OrderType.LIMIT,
  stop_price=str(entry_price - 250))
print(order_response)

Get Real-Time Positions Data of Derivatives using Python API:


For Instructions Follow the Video then go For the Code Input:



from cred import *
from delta_rest_client import DeltaRestClient
import pandas as pd 

delta_client = DeltaRestClient(
  base_url='https://api.india.delta.exchange',
  api_key=api_key,
  api_secret=api_secret
)

response = delta_client.get_ticker('P-BTC-114000-250725')
product_id=response['product_id']
mark_price=round(float(response['mark_price']),1)
print(product_id,mark_price)
position=delta_client.get_position(product_id)
entry_price=round(float(position['entry_price']),1)
size=position['size']
print(entry_price,size)

GET Futures | Options OrderBook Depth + Price + Size via Python API:


For Instructions Follow the Video then go For the Code Input:



from cred import *
from delta_rest_client import DeltaRestClient
import pandas as pd 

delta_client = DeltaRestClient(
  base_url='https://api.india.delta.exchange',
  api_key=api_key,
  api_secret=api_secret
)


response = delta_client.get_ticker('P-BTC-116000-250725')
product_id=response['product_id']
mark_price=round(float(response['mark_price']),1)
print(product_id,mark_price)
order_book=delta_client.get_l2_orderbook(product_id)
print(pd.DataFrame(order_book['sell'])['price'])

GET Customized Price | Trade Alert in Telegram Using AWS Lambda:

For Instructions Follow the Video then go For the Code Input:


import requests 
import pandas as pd  
from datetime import datetime, timedelta 
import json
config=open('token_chat_id.txt','r').read()
config=json.loads(config)
token=config['token']
chat_id=config['chat_id']
tele_url=f'https://api.telegram.org/bot{token}'  

base_url="https://api.india.delta.exchange"
url=f"{base_url}/v2/history/candles"
end=int(datetime.now().timestamp())
start=int((datetime.now()-timedelta(days=1)).timestamp())
params={
    'symbol':'BTCUSD',
    'resolution':'1m',
    'start':start,
    'end':end
}
r=requests.get(url,params=params)
data=r.json().get('result',[])
df=pd.DataFrame(data,columns=['time','open','high','low','close','volume'])
if df['close'].iloc[-1] < df['open'].iloc[-1]:
    Candle='RED'
    msg=f"'BTCUSD',{Candle},{df['close'].iloc[-1]},{df['open'].iloc[-1]}"
send_alert=requests.get(f'{tele_url}/sendMessage?chat_id={chat_id}&text={msg}').json()['result']['text']
print(send_alert)

Delta Exchange India Trade API and Ticker in Python:

Generate API Key:


For Instructions Follow the Video then go For the Code Input:


CMD:pip install delta-rest-client


import json
from delta_rest_client import DeltaRestClient
config=open('delta.txt','r').read()
config=json.loads(config)
api_key=config['api_key']
api_secret=config['api_secret']


delta_client = DeltaRestClient(
  base_url='https://api.india.delta.exchange',
  api_key=api_key,
  api_secret=api_secret
)
response = delta_client.get_ticker('C-BTC-94400-280425')
print(response['mark_price'])

Get Product ID for Crypto Trading Symbol Using Delta Exchange API in Python:


For Instructions Follow the Video then go For the Code Input:



import json
from delta_rest_client import DeltaRestClient
config=open('delta.txt','r').read()
config=json.loads(config)
api_key=config['api_key']
api_secret=config['api_secret']


delta_client = DeltaRestClient(
  base_url='https://api.india.delta.exchange',
  api_key=api_key,
  api_secret=api_secret
)
response = delta_client.get_ticker('C-BTC-103800-190525')
print(response['product_id'])

How to Place Orders in Delta Exchange using Python API:


For Instructions Follow the Video then go For the Code Input:



import json
from delta_rest_client import DeltaRestClient
from delta_rest_client import OrderType
config=open('delta.txt','r').read()
config=json.loads(config)
api_key=config['api_key']
api_secret=config['api_secret']


delta_client = DeltaRestClient(
  base_url='https://api.india.delta.exchange',
  api_key=api_key,
  api_secret=api_secret
)
response = delta_client.get_ticker('BTCUSD')
product_id=response['product_id']
mark_price=round(float(response['mark_price'])-10,1)
order_response=delta_client.place_order(product_id=product_id,
  side='buy',
  size=1,
  limit_price=mark_price,
  order_type=OrderType.LIMIT)
print(order_response)

GET Historical OHLC Candles Utilizing Delta Exchange API in Python:


For Instructions Follow the Video then go For the Code Input:



import requests 
import pandas as pd  
from datetime import datetime, timedelta 

base_url="https://api.india.delta.exchange"
url=f"{base_url}/v2/history/candles"
end=int(datetime.now().timestamp())
start=int((datetime.now()-timedelta(days=1)).timestamp())
params={
    'symbol':'BTCUSD',
    'resolution':'1m',
    'start':start,
    'end':end
}
r=requests.get(url,params=params)
data=r.json().get('result',[])
df=pd.DataFrame(data,columns=['time','open','high','low','close','volume'])
print(df)

Customized Interactive Historical OHLC Candlestick Chart Using Delta Exchange API:


For Instructions Follow the Video then go For the Code Input:



import requests 
import pandas as pd  
from datetime import datetime, timedelta 
import mplfinance as mpf
base_url="https://api.india.delta.exchange"
url=f"{base_url}/v2/history/candles"
end=int(datetime.now().timestamp())
start=int((datetime.now()-timedelta(days=1)).timestamp())
params={
    'symbol':'BTCUSD',
    'resolution':'15m',
    'start':start,
    'end':end
}
r=requests.get(url,params=params)
data=r.json().get('result',[])
df=pd.DataFrame(data,columns=['time','open','high','low','close','volume']).sort_values('time')
df['time']=pd.to_datetime(df['time'],unit='s')
df['time']=df['time'].dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')
df.set_index('time',inplace=True)
mpf.plot(df,type='candle',volume=False,style='charles',title='BTCUSD 15-Minute Candlestick Chart')


Customized Interactive Historical OHLC Candlestick Chart Using API Part2:


For Instructions of Connecting Chart GUI Follow the Video then go For the Code Input:



import requests 
import pandas as pd  
from datetime import datetime, timedelta 
import mplfinance as mpf
import toga  
from toga.style import Pack 
base_url="https://api.india.delta.exchange"
url=f"{base_url}/v2/history/candles"
end=int(datetime.now().timestamp())
start=int((datetime.now()-timedelta(days=1)).timestamp())
params={
    'symbol':'BTCUSD',
    'resolution':'5m',
    'start':start,
    'end':end
}
r=requests.get(url,params=params)
data=r.json().get('result',[])
df=pd.DataFrame(data,columns=['time','open','high','low','close','volume']).sort_values('time')
df['time']=pd.to_datetime(df['time'],unit='s')
df['time']=df['time'].dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')
df.set_index('time',inplace=True)
mpf.plot(df,type='candle',volume=False,style='charles',title='BTCUSD 5-Minute Candlestick Chart',savefig=dict(fname='btc_chart.png',dpi=150,pad_inches=0.25,bbox_inches='tight'))
class ChartApp(toga.App):
    def startup(self):
        self.main_window=toga.MainWindow(title=self.formal_name)
        image=toga.Image('btc_chart.png')

        image_view=toga.ImageView(image=image,style=Pack(padding=10))

        self.main_window.content=image_view  
        self.main_window.show()

def main():
    return ChartApp('BTCUSD','369')
main().main_loop()

Customized Interactive Historical OHLC Candlestick Chart Using API Part3:


For Instructions Follow the Video then go For the Code Input:



import requests 
import pandas as pd  
from datetime import datetime, timedelta 
import mplfinance as mpf
import toga  
from toga.style import Pack 
import os
import matplotlib 
matplotlib.use("Agg")



class ChartApp(toga.App):
    def fetch_candlestic_data(self,symbol):
        base_url="https://api.india.delta.exchange"
        url=f"{base_url}/v2/history/candles"
        end=int(datetime.now().timestamp())
        start=int((datetime.now()-timedelta(days=1)).timestamp())
        params={
            'symbol':symbol,
            'resolution':self.resolution,
            'start':start,
            'end':end
        }
        r=requests.get(url,params=params)
        data=r.json().get('result',[])
        df=pd.DataFrame(data,columns=['time','open','high','low','close','volume']).sort_values('time')
        df['time']=pd.to_datetime(df['time'],unit='s')
        df['time']=df['time'].dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')
        df.set_index('time',inplace=True)
        return df
    def startup(self):
        symbol='BTCUSD'
        self.resolution='5m'
        df=self.fetch_candlestic_data(symbol)
        os.makedirs(self.paths.cache,exist_ok=True)
        chart_path=os.path.join(self.paths.cache,f'{symbol}_{self.resolution}_chart.png')
        mpf.plot(df,type='candle',volume=False,style='charles',title=f'{symbol} {self.resolution} Candlestick Chart',savefig=dict(fname=chart_path,dpi=150))
        self.main_window=toga.MainWindow(title=self.formal_name)
        image=toga.Image(chart_path)

        image_view=toga.ImageView(image=image,style=Pack(padding=10))

        self.main_window.content=image_view  
        self.main_window.show()

def main():
    return ChartApp('BTCUSD','369')
main().main_loop()


Zerodha KiteConnect Utilize Free of Cost API to Automate Trades in Python

Zerodha KiteConnect Utilize Free of Cost API to Automate Trades:

Kite Connect is a set of REST-like HTTP APIs that expose many capabilities required to build a complete stock market investment and trading platform. It lets you execute orders in real time (equities, commodities, mutual funds), manage user portfolios, stream live market data over WebSockets, and more.

This module provides an easy to use abstraction over the HTTP APIs. The HTTP calls have been converted to methods and their JSON responses are returned as native Python structures, for example, dicts, lists, bools etc.

The login flow starts by navigating to the public Kite login endpoint.

https://kite.zerodha.com/connect/login?v=3&api_key=xxx

Follow the Above Video for Instructions then go for the Code Input:


from kiteconnect import KiteConnect

api_key=open('api_key.txt','r').read().strip()
api_secret=open('api_secret.txt','r').read().strip()

kite = KiteConnect(api_key=api_key)

access_token=kite.generate_session("your_request_token_here", api_secret=api_secret)

print(access_token['access_token'])

Develop a Stock Portfolio Screener in Excel using Python and Grok Chatbot AI

Develop a Stock Portfolio Screener in Excel using Python and Grok Chatbot AI:


For Instructions Follow the Video then go For the Code Input:



import pandas as pd  
instruments=pd.read_csv('https://assets.upstox.com/market-quote/instruments/exchange/complete.csv.gz')
instruments=instruments[instruments['instrument_type']=='FUTSTK'].sort_values(by='last_price')
instruments['Symbol']=instruments['tradingsymbol'].str.extract(r'([A-Z-&]+)').drop_duplicates()
tradingsymbol=instruments[['Symbol','last_price']]
print(len(tradingsymbol[1:]),tradingsymbol[1:].dropna().set_index('Symbol').to_excel('NSE.xlsx',header=['Price']))


For Instructions Follow the Video then go For the Code Input:



import pandas as pd  
instruments=pd.read_csv('https://assets.upstox.com/market-quote/instruments/exchange/complete.csv.gz')
instruments=instruments[instruments['instrument_type']=='FUTSTK'].sort_values(by='last_price')
instruments['Symbol']=instruments['tradingsymbol'].str.extract(r'([A-Z-&]+)').drop_duplicates()
tradingsymbol=instruments[['Symbol','last_price']].dropna()
tradingsymbol=tradingsymbol[tradingsymbol['last_price'].apply(lambda x:x<500)]
print(len(tradingsymbol[1:]),tradingsymbol[1:].set_index('Symbol').to_excel('NSE_500.xlsx',header=['Price']))

Beeware Toga WebView to Run App in Multiple Platforms

WebView using Python to run app in multiple platforms such as Desktop or Android or IOS:


Follow the Instructions from the Above Video then go for the Code Input:



import toga  

class WebViewApp(toga.App):
	def startup(self):
		self.main_window=toga.MainWindow(title=self.formal_name,size=(800,600))
		self.webview=toga.WebView(url='https://www.profitaddaweb.com')
		self.main_window.content=self.webview
		self.main_window.show()

def main():
	return WebViewApp('WebView App','org.beeware.webviewapp')
if __name__=='__main__':
	main().main_loop()
print(send_alert)

Telegram Bot in Python

Enhance Python Knowledge Create a Python Quiz Telegram Bot:


Follow the Instructions from the Above Video then go for the Code Input:


import nest_asyncio
import asyncio  
from telegram import Update,InlineKeyboardButton,InlineKeyboardMarkup
from telegram.ext import Application,CommandHandler,CallbackQueryHandler
telegram_token=open('token.txt','r').read().strip()
nest_asyncio.apply()
questions =[{"question": "What is the output of: print('Hello, ' + 'World!')?", 
     "options": ["Hello, World!", "HelloWorld!", "Hello, + World!", "Error"], 
     "correct_option": 0},
    {"question": "Which of the following can be used to iterate over a list in Python?", 
     "options": ["for", "while", "map", "All of the above"], 
     "correct_option": 3},
    {"question": "What does the len() function do in Python?", 
     "options": ["Returns the number of elements in a list", "Returns the length of a string", 
     "Returns the number of key-value pairs in a dictionary", "All of the above"], 
     "correct_option": 3},
    {"question": "Which of the following is not a keyword in Python?", 
     "options": ["class", "assert", "none", "pass"], 
     "correct_option": 2},
    {"question": "How do you create a set in Python?", 
     "options": ["[]", "{}", "()", "set()"], 
     "correct_option": 2},
    {"question": "What does NIFTY 50 represent?", 
     "options": ["Top 50 stocks in the BSE", "Top 50 stocks in the NSE", "Top 50 IT companies in India", "The 50 oldest companies in India"], 
     "correct_option": 1},
    {"question": "What is the full form of IPO?", 
     "options": ["Initial Public Offering", "International Portfolio Offering", "Indian Public Organization", "Initial Purchase Offer"], 
     "correct_option": 0},
    {"question": "Which regulatory body governs the securities market in India?", 
     "options": ["SEBI", "RBI", "IRDAI", "PFRDA"], 
     "correct_option": 0},
    {"question": "Which of the following is a stock market index in India?", 
     "options": ["Dow Jones", "FTSE 100", "Sensex", "Nikkei 225"], 
     "correct_option": 2}
]

async def start(update:Update,context) -> None:
    context.user_data['current_question']=0
    context.user_data['correct_answers']=0
    context.user_data['wrong_answers']=0
    await ask_question(update,context)
async def ask_question(update:Update,context) -> None:
    current_question_index=context.user_data['current_question']
    question_data=questions[current_question_index]

    keyboard=[
    [InlineKeyboardButton(option,callback_data=str(index)) for index,option in enumerate(question_data['options']) ]]
    reply_markup=InlineKeyboardMarkup(keyboard)
    if update.message:
        await update.message.reply_text(question_data['question'],reply_markup=reply_markup)
    else:
        query=update.callback_query
        await query.edit_message_text(question_data['question'],reply_markup=reply_markup)
async def button(update:Update,context) -> None:
    query=update.callback_query
    current_question_index=context.user_data['current_question']
    question_data=questions[current_question_index]

    selected_option=int(query.data)
    correct_option=question_data['correct_option']

    if selected_option==correct_option:
        context.user_data['correct_answers']+=1
        await query.answer('Correct!')
    else:
         context.user_data['wrong_answers']+=1
         await query.answer('Wrong!')

    current_question_index += 1
    if current_question_index < len(questions):
        context.user_data['current_question']= current_question_index
        await ask_question(update,context)
    else:
        correct=  context.user_data['correct_answers']
        wrong=context.user_data['wrong_answers']
        await query.edit_message_text(f"Quiz Finished! Played Well: CA:{correct}, WA:{wrong}")

async def main():
    application=Application.builder().token(telegram_token).build()
    application.add_handler(CommandHandler('start',start))
    application.add_handler(CallbackQueryHandler(button))

    await application.run_polling()
if __name__=='__main__':
    asyncio.run(main())

How to Create a Telegram Bot in Python Updated Version:


Follow the Instructions from the Above Video then go for the Code Input:



import requests
token=open('token.txt','r').read().strip()
base_url=f'https://api.telegram.org/bot{token}'  
chat_id=requests.get(f'{base_url}/getUpdates').json()['result'][0]['message']['chat']['id']
text='learning video visit youtube:https://youtube.com/profitadda/videos'
send_alert=requests.get(f'{base_url}/sendMessage?chat_id={chat_id}&text={text}').json()['result']['text']
print(send_alert)

Stock Market Analysis Retention Trades[S.M.A.R.T] Mobile Android Application in Python

Symbol Generator S.M.A.R.T Mobile Android Application in Python:


Follow the Instructions from the Above Video then go for the Code Input:




from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.spinner import Spinner
from kivy.uix.textinput import TextInput  
from kivy.uix.checkbox import CheckBox  

class SymbolGeneratorApp(App):
    def build(self):
        self.layout=BoxLayout(orientation='vertical')
        self.layout.add_widget(Label(text='S.M.A.R.T'))
        self.symbol_spinner=Spinner(text='Select Index Symbol',
            values=('MIDCPNIFTY','FINNIFTY','BANKNIFTY','NIFTY','BANKEX','SENSEX'),
            size_hint=(1,None),
            height=44)
        self.layout.add_widget(self.symbol_spinner)

        self.expiry_input=TextInput(hint_text='Enter Expiry',multiline=False,size_hint=(1,None),height=44)
        self.layout.add_widget(self.expiry_input)
        self.strike_price_input=TextInput(hint_text='Enter Strike Price',multiline=False,size_hint=(1,None),height=44)
        self.layout.add_widget(self.strike_price_input)
        
        option_layout=BoxLayout(size_hint=(1,None),height=44)
        self.ce_checkbox=CheckBox(group='option',active=True)
        option_layout.add_widget(self.ce_checkbox)
        option_layout.add_widget(Label(text='CE'))
        self.pe_checkbox=CheckBox(group='option')
        option_layout.add_widget(self.pe_checkbox)
        option_layout.add_widget(Label(text='PE'))
        self.layout.add_widget(option_layout)

        self.add_symbol_button=Button(text='Generate Symbol',size_hint=(1,None),height=44)
        self.add_symbol_button.bind(on_press=self.add_symbol)
        self.layout.add_widget(self.add_symbol_button)

        self.results_layout=BoxLayout(orientation='vertical',spacing=10)
        self.layout.add_widget( self.results_layout)


        self.symbols=[]
        return self.layout 
        
    def add_symbol(self,instance):
        symbol=self.symbol_spinner.text 
        expiry=self.expiry_input.text 
        strike_price=self.strike_price_input.text   
        option='CE' if self.ce_checkbox.active else 'PE'


        self.symbols.append({'symbol':symbol,
            'expiry':expiry, 
            'strike_price':strike_price,
            'option':option})
        print(symbol)
        self.update_results()
    def update_results(self):
        self.results_layout.clear_widgets()
        for symbol in self.symbols:
            print(f"{symbol['symbol']}")
            symbol_str=f"{symbol['symbol']}{symbol['expiry']}{symbol['strike_price']}{symbol['option']}"

            self.results_layout.add_widget(TextInput(text=symbol_str)) 

          

      


SymbolGeneratorApp().run()


Add Text Input Box and Check Box in S.M.A.R.T Mobile Android Application in Python:


Follow the Instructions from the Above Video then go for the Code Input:



from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.spinner import Spinner
from kivy.uix.textinput import TextInput  
from kivy.uix.checkbox import CheckBox  

class MarginCalculatorApp(App):
    def build(self):
        self.layout=BoxLayout(orientation='vertical')
        self.layout.add_widget(Label(text='S.M.A.R.T'))
        self.symbol_spinner=Spinner(text='Select Index Symbol',
            values=('MIDCPNIFTY','FINNIFTY','BANKNIFTY','NIFTY','BANKEX','SENSEX'),
            size_hint=(1,None),
            height=44)
        self.layout.add_widget(self.symbol_spinner)

        self.expiry_input=TextInput(hint_text='Enter Expiry',multiline=False,size_hint=(1,None),height=44)
        self.layout.add_widget(self.expiry_input)
        self.strike_price_input=TextInput(hint_text='Enter Strike Price',multiline=False,size_hint=(1,None),height=44)
        self.layout.add_widget(self.strike_price_input)
        
        option_layout=BoxLayout(size_hint=(1,None),height=44)
        self.ce_checkbox=CheckBox(group='option',active=True)
        option_layout.add_widget(self.ce_checkbox)
        option_layout.add_widget(Label(text='CE'))
        self.pe_checkbox=CheckBox(group='option')
        option_layout.add_widget(self.pe_checkbox)
        option_layout.add_widget(Label(text='PE'))
        self.layout.add_widget(option_layout)
        return self.layout 


MarginCalculatorApp().run()


Add Drop Down List in S.M.A.R.T Mobile Android Application in Python:


Follow the Instructions from the Above Video then go for the Code Input:



from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.spinner import Spinner

class MarginCalculatorApp(App):
    def build(self):
        self.layout=BoxLayout(orientation='vertical')
        self.layout.add_widget(Label(text='S.M.A.R.T'))
        self.symbol_spinner=Spinner(text='Select Index Symbol',
            values=('MIDCPNIFTY','FINNIFTY','BANKNIFTY','NIFTY','BANKEX','SENSEX'),
            size_hint=(1,None),
            height=44)
        self.layout.add_widget(self.symbol_spinner)

        return self.layout  
MarginCalculatorApp().run()

Video Player Mobile Android Application in Python:


Follow the Instructions from the Above Video then go for the Code Input:



from kivy.app import App
from kivy.uix.videoplayer import VideoPlayer

class VideoPlayerApp(App):
    def build(self):
        return VideoPlayer(source='ATR.wmv',state='play',options={'allow_stretch':True})
if __name__=='__main__':
    VideoPlayerApp().run()

Stock Market Analysis Retention Trades[S.M.A.R.T] Mobile Android Application in Python:


Follow the Instructions from the Above Video then go for the Code Input:



from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button

class SMARTApp(App):
    def build(self):
        layout=BoxLayout(orientation='vertical')
        layout.add_widget(Label(text='Welcome to Stock Market Analysis Retention Trades[S.M.A.R.T]',font_size='24sp'))
        layout.add_widget(Button(text='Start Learning',on_press=self.on_button_press))
        return layout
    def on_button_press(self,instance):
        print('Button Pressed! Learning in Progress')
if __name__=='__main__':
    SMARTApp().run()


Convert Formulae to Code Technical Indicators in Python

EMA(Exponential Moving Average) Formulae to Code Technical Indicators from Scratch in Python:


Follow Instructions from the Above Video then go for the Code Input.


Import the Libraries:


 import pandas as pd
from fyers_apiv3 import fyersModel
from datetime import datetime,timedelta
import talib
import matplotlib.pyplot as plt
import sys

Call App ID and Access Token for Authorization and Set the Required Input:


client_id=open('app_id.txt','r').read()
token=open('access_token.txt','r').read().strip()
fyers=fyersModel.FyersModel(client_id=client_id,token=token,log_path='C:/Users/your_folder/Desktop/fyers')
days=1
symbol='NSE:NIFTYBANK-INDEX'
interval='1'
now=datetime.now()
from_date=now-timedelta(days=days)
from_date=datetime.strftime(from_date,'%Y-%m-%d')
to_date=datetime.strftime(now,'%Y-%m-%d')
print(now,symbol,interval,from_date,to_date)

Call the Historical Data Function by Using Fyers API:


def historical_data(symbol,interval,from_date,to_date):
    data={'symbol':symbol,
          'resolution':interval,
          'date_format':'1',
          'range_from':from_date,
          'range_to':to_date,
          'cont_flag':'1'
          }
    response=pd.DataFrame(fyers.history(data=data)['candles'],columns=['date','open','high','low','close','volume'])
    return response
df=historical_data(symbol,interval,from_date,to_date)

Define the Exponential Moving Average Function:


def EMA(prices,period):
  ema=[]
  alpha=2/(period+1)
  print(alpha)
  print((1-alpha))
  ema.append(sum(prices[:period])/period)
  for price in prices[period:]:
    ema_prev=ema[-1]
    new_ema=price*alpha+ema_prev*(1-alpha)
    ema.append(new_ema)
  return ema

print(pd.DataFrame(EMA(df['close'],9)))

Show Full Code Input:


 import pandas as pd
from fyers_apiv3 import fyersModel
from datetime import datetime,timedelta
import talib
import matplotlib.pyplot as plt
import sys
client_id=open('app_id.txt','r').read()
token=open('access_token.txt','r').read().strip()
fyers=fyersModel.FyersModel(client_id=client_id,token=token,log_path='C:/Users/your_folder/Desktop/fyers')
days=1
symbol='NSE:NIFTYBANK-INDEX'
interval='1'
now=datetime.now()
from_date=now-timedelta(days=days)
from_date=datetime.strftime(from_date,'%Y-%m-%d')
to_date=datetime.strftime(now,'%Y-%m-%d')
print(now,symbol,interval,from_date,to_date)
def historical_data(symbol,interval,from_date,to_date):
    data={'symbol':symbol,
          'resolution':interval,
          'date_format':'1',
          'range_from':from_date,
          'range_to':to_date,
          'cont_flag':'1'
          }
    response=pd.DataFrame(fyers.history(data=data)['candles'],columns=['date','open','high','low','close','volume'])
    return response
df=historical_data(symbol,interval,from_date,to_date)
def EMA(prices,period):
  ema=[]
  alpha=2/(period+1)
  print(alpha)
  print((1-alpha))
  ema.append(sum(prices[:period])/period)
  for price in prices[period:]:
    ema_prev=ema[-1]
    new_ema=price*alpha+ema_prev*(1-alpha)
    ema.append(new_ema)
  return ema

print(pd.DataFrame(EMA(df['close'],9)))

Convert Formulae to Code Technical Indicators ATR in Python:


Follow Instructions from the Above Video then go for the Code Input.


import pandas as pd
from fyers_apiv3 import fyersModel
from datetime import datetime,timedelta
import numpy as np
client_id=open('app_id.txt','r').read()
token=open('access_token.txt','r').read().strip()
fyers=fyersModel.FyersModel(client_id=client_id,token=token,log_path='C:/Users/VIKASH/Desktop/fyersv3')
days=4
symbol='NSE:NIFTY50-INDEX'
interval='1'
now=datetime.now()
from_date=now-timedelta(days=days)
from_date=datetime.strftime(from_date,'%Y-%m-%d')
to_date=datetime.strftime(now,'%Y-%m-%d')
print(now,symbol,interval,from_date,to_date)
def historical_data(symbol,interval,from_date,to_date):
    data={'symbol':symbol,
          'resolution':interval,
          'date_format':'1',
          'range_from':from_date,
          'range_to':to_date,
          'cont_flag':'1'
          }
    response=pd.DataFrame(fyers.history(data=data)['candles'],columns=['date','open','high','low','close','volume'])
    return response
df=historical_data(symbol,interval,from_date,to_date)
def TR(df):
  df['pc']=df['close'].shift(1)
  df['hl']=df['high']-df['low']
  df['hpc']=np.abs(df['high']-df['pc'])
  df['lpc']=np.abs(df['low']-df['pc'])
  df['tr']=df[['hl','hpc','lpc']].max(axis=1)
  return df['tr']
def ATR(tr,period=14):
  df['True']=tr
  df['atr']=df['True'].ewm(span=period).mean()
  return df['atr']
print(ATR(TR(df),period=14)) 

Convert Formulae to Code Technical Indicators MACD in Python:


Follow Instructions from the Above Video then go for the Code Input.


import requests 
import pandas as pd  
from datetime import datetime, timedelta 
base_url="https://api.india.delta.exchange"
url=f"{base_url}/v2/history/candles"
end=int(datetime.now().timestamp())
start=int((datetime.now()-timedelta(days=1)).timestamp())
params={
    'symbol':'BTCUSD',
    'resolution':'15m',
    'start':start,
    'end':end
}
r=requests.get(url,params=params)
data=r.json().get('result',[])
df=pd.DataFrame(data,columns=['time','open','high','low','close','volume']).sort_values('time')
df['time']=pd.to_datetime(df['time'],unit='s')
df['time']=df['time'].dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')
df.set_index('time',inplace=True)
fastperiod=df['close'].ewm(span=12,adjust=False).mean()
slowperiod=df['close'].ewm(span=26,adjust=False).mean()
df['MACD']=fastperiod - slowperiod
df['Signal']=df['MACD'].ewm(span=9,adjust=False).mean()
df['Histogram']=df['MACD'] - df['Signal']
print(df.tail(5).to_string(index=False))

Rate of Change (ROC) Indicator in Python:


Follow Instructions from the Above Video then go for the Code Input.


import requests 
import pandas as pd  
from datetime import datetime, timedelta 
import mplfinance as mpf
base_url="https://api.india.delta.exchange"
url=f"{base_url}/v2/history/candles"
end=int(datetime.now().timestamp())
start=int((datetime.now()-timedelta(days=1)).timestamp())
params={
    'symbol':'BTCUSD',
    'resolution':'15m',
    'start':start,
    'end':end
}
r=requests.get(url,params=params)
data=r.json().get('result',[])
df=pd.DataFrame(data,columns=['time','open','high','low','close','volume']).sort_values('time')
df['time']=pd.to_datetime(df['time'],unit='s')
df['time']=df['time'].dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')
df.set_index('time',inplace=True)
df['ROC']=df['close'].pct_change(5) * 100
print(df.head(10))
df['ROCF']=((df['close']-df['close'].shift(5))/df['close'].shift(5))*100
print(df['ROCF'].head(10))
add_plots=[
mpf.make_addplot(df['ROC'],panel=2,color='blue',ylabel='ROC')

]
mpf.plot(df,type='candle',style='charles',volume=True,addplot=add_plots,title='BTCUSD 15-Minute Candlestick Chart')