"For GUIDANCE On Programmatic Trading WhatsApp Profit Adda Web @ +91-7795780804"

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.

Visit Delta Exchange India

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()