-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdhan_automate.py
114 lines (98 loc) · 4.25 KB
/
dhan_automate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import requests
import time
import pandas as pd
from websocket import create_connection
# DhanHQ API Credentials (replace with your credentials)
API_KEY = "your_api_key"
ACCESS_TOKEN = "your_access_token"
BASE_URL = "https://api.dhan.co"
# User-Defined Variables
USER_INPUT_STOCKS = 3 # Number of top stocks to trade
DEFAULT_LOT_SIZE = 1 # Default lot size
TRAILING_STOP_LOSS_PERCENT = 20 # Default trailing stop loss percentage
EXIT_TIME = "15:25:00" # Exit all positions before market closes
# Fetch Top Gainers and Losers
def fetch_top_stocks():
url = f"{BASE_URL}/market-data/top-gainers-losers"
headers = {"Authorization": f"Bearer {ACCESS_TOKEN}"}
response = requests.get(url, headers=headers).json()
gainers = response['data']['gainers'][:10] # Fetch top 10 gainers
losers = response['data']['losers'][:10] # Fetch top 10 losers
return gainers, losers
# Determine Market Trend
def determine_market_trend(gainers, losers):
avg_gainers = sum([float(stock['percentageChange']) for stock in gainers]) / len(gainers)
avg_losers = sum([float(stock['percentageChange']) for stock in losers]) / len(losers)
return "bullish" if avg_gainers > abs(avg_losers) else "bearish"
# Check First Two 5-Minute Candles
def check_candles(stock_symbol):
url = f"{BASE_URL}/market-data/candlestick/{stock_symbol}/5m"
headers = {"Authorization": f"Bearer {ACCESS_TOKEN}"}
response = requests.get(url, headers=headers).json()
candles = response['data']['candles'][-2:] # Last two 5-minute candles
if len(candles) < 2:
return False # Not enough data to evaluate
return all(candle['close'] > candle['open'] for candle in candles) # Example for bullish trend
# Place Option Order
def place_order(stock_symbol, option_type, lot_size):
url = f"{BASE_URL}/orders"
headers = {"Authorization": f"Bearer {ACCESS_TOKEN}"}
payload = {
"symbol": stock_symbol,
"transactionType": "BUY",
"orderType": "MARKET",
"quantity": lot_size,
"productType": "INTRADAY",
"optionType": option_type # 'CE' for Call, 'PE' for Put
}
response = requests.post(url, json=payload, headers=headers).json()
return response
# Monitor Trailing Stop Loss
def monitor_trailing_stop_loss(trade_id, entry_price, stop_loss_percent):
current_stop_loss = entry_price * (1 - stop_loss_percent / 100)
while True:
# Fetch live price
url = f"{BASE_URL}/market-data/price/{trade_id}"
headers = {"Authorization": f"Bearer {ACCESS_TOKEN}"}
response = requests.get(url, headers=headers).json()
live_price = float(response['data']['lastTradedPrice'])
# Update trailing stop loss
if live_price > entry_price:
entry_price = live_price
current_stop_loss = entry_price * (1 - stop_loss_percent / 100)
# Exit if stop loss is hit
if live_price <= current_stop_loss:
exit_trade(trade_id)
break
# Exit if time is close to market close
if time.strftime("%H:%M:%S") >= EXIT_TIME:
exit_trade(trade_id)
break
time.sleep(10) # Wait for 10 seconds before the next check
# Exit Trade
def exit_trade(trade_id):
url = f"{BASE_URL}/orders/{trade_id}/cancel"
headers = {"Authorization": f"Bearer {ACCESS_TOKEN}"}
response = requests.post(url, headers=headers).json()
print(f"Trade exited: {response}")
# Main Logic
def main():
gainers, losers = fetch_top_stocks()
trend = determine_market_trend(gainers, losers)
stocks_to_trade = gainers if trend == "bullish" else losers
traded_stocks = 0
for stock in stocks_to_trade:
if traded_stocks >= USER_INPUT_STOCKS:
break
symbol = stock['symbol']
if check_candles(symbol):
option_type = "CE" if trend == "bullish" else "PE"
response = place_order(symbol, option_type, DEFAULT_LOT_SIZE)
print(f"Order placed for {symbol}: {response}")
# Monitor trailing stop loss
entry_price = float(response['data']['price'])
trade_id = response['data']['tradeId']
monitor_trailing_stop_loss(trade_id, entry_price, TRAILING_STOP_LOSS_PERCENT)
traded_stocks += 1
if __name__ == "__main__":
main()