forked from kodebuds/chartink
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvol_worker.py
More file actions
219 lines (177 loc) · 7.16 KB
/
Copy pathvol_worker.py
File metadata and controls
219 lines (177 loc) · 7.16 KB
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import time
import os
import sys
import logging
from datetime import datetime
from dotenv import load_dotenv
from fyers_apiv3 import fyersModel
# Add project root to path
sys.path.append(os.getcwd())
# Load environment variables
load_dotenv(os.path.join(os.getcwd(), 'env', 'fyers.env'))
from core.fyers.auth import FyersAuth
from core.analytics.gex import GEXEngine
from core.analytics.volatility import VolatilityEngine
from core.database import TradeDB
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("vol_worker.log"),
logging.StreamHandler()
]
)
logger = logging.getLogger("VolWorker")
class VolatilityWorker:
def __init__(self, symbol="NSE:NIFTY50-INDEX"):
self.symbol = symbol
self.auth = FyersAuth()
self.fyers = None
# Initialize Engines
self.gex_engine = GEXEngine()
self.vol_engine = VolatilityEngine()
# Initialize DB
try:
self.db = TradeDB()
logger.info("Connected to DuckDB")
except Exception as e:
logger.error(f"DB Connection failed: {e}")
self.db = None
def connect_fyers(self):
"""Ensure Fyers connection is active"""
if not self.auth.is_authenticated():
logger.info("Token expired/missing. Attempting Auto-Login...")
if self.auth.auto_login():
logger.info("Auto-Login Successful")
else:
logger.error("Auto-Login Failed")
return False
self.fyers = fyersModel.FyersModel(
client_id=self.auth.client_id,
token=self.auth.access_token,
is_async=False,
log_path=""
)
return True
def fetch_option_chain(self):
"""Fetch Option Chain for the symbol"""
if not self.fyers:
return None
try:
# Fetch expiry dates first? Or just request chain
# Fyers Option Chain API requires specific symbol format
# e.g. NSE:NIFTY26JAN...
# For simplicity, we use the Option Chain endpoint if available or Quotes
# API v3 Option Chain: data={"symbol":"NSE:NIFTY50-INDEX", "strikecount": 10}
data = {
"symbol": self.symbol,
"strikecount": 20, # Get 20 strikes OTM/ITM
"timestamp": ""
}
response = self.fyers.optionchain(data=data)
if response['s'] != 'ok':
logger.error(f"Option Chain Fetch Failed: {response.get('message')}")
return None
return response['data']
except Exception as e:
logger.error(f"API Error: {e}")
return None
def fetch_spot_price(self):
"""Fetch spot price for underlying index"""
if not self.fyers: return 0
try:
# Assuming NIFTY 50 Index
data = {"symbols": "NSE:NIFTY50-INDEX"}
res = self.fyers.quotes(data=data)
if res['s'] == 'ok' and res['d']:
return res['d'][0]['v'].get('lp', 0)
except Exception as e:
logger.error(f"Spot fetch error: {e}")
return 0
def process_cycle(self):
"""Main processing loop iteration"""
if not self.connect_fyers():
return
logger.info(f"Fetching Option Chain for {self.symbol}...")
chain_data = self.fetch_option_chain()
if not chain_data:
return
# Transform Fyers data to Engine format
options_list = chain_data.get('optionsChain', [])
expiry_list = chain_data.get('expiryData', [])
if not options_list:
logger.warning("No options chain data received")
return
# Extract Spot Price
spot_price = float(options_list[0].get('underlying_value', 0) or 0)
# Fallback if spot is 0 (common in some feeds)
if spot_price == 0:
logger.info("Spot 0 in chain, fetching quote...")
spot_price = self.fetch_spot_price()
if spot_price == 0:
logger.warning("Spot price zero")
return
# Group by Strike
processed_chain = []
# Determine nearest expiry (T)
# Simplified: Use the expiry from the first option contract
# expiry_ts = options_list[0]['expiry_date'] # timestamp
# days_to_expiry = (expiry_ts - time.time()) / (24*3600*365)
# Mocking Days to Expiry for now as 7 days
days_to_expiry = 7.0 / 365.0
# Prepare data for GEX Engine
# We need to aggregate CE and PE for each strike
strikes = {}
for opt in options_list:
strike = float(opt['strike_price'])
if strike not in strikes:
strikes[strike] = {'strike': strike}
# Map Fyers fields
# option_type = 'CE' if opt['option_type'] == 'CE' else 'PE'
# Assuming format: 'NSE:NIFTY24JAN21500CE'
sym = opt['symbol']
otype = 'CE' if sym.endswith('CE') else 'PE'
if otype == 'CE':
strikes[strike]['call_oi'] = opt.get('oi', 0)
strikes[strike]['call_iv'] = opt.get('iv', 0) / 100.0 # Percent to decimal?
strikes[strike]['call_ltp'] = opt.get('ltp', 0)
else:
strikes[strike]['put_oi'] = opt.get('oi', 0)
strikes[strike]['put_iv'] = opt.get('iv', 0) / 100.0
strikes[strike]['put_ltp'] = opt.get('ltp', 0)
formatted_chain = list(strikes.values())
# 1. Calculate GEX
gex_res = self.gex_engine.calculate_net_gex(
spot_price, formatted_chain, days_to_expiry, lot_size=75
)
flip_point = self.gex_engine.find_flip_point(
spot_price, formatted_chain, days_to_expiry, lot_size=75
)
# 2. Calculate Vol Metrics
# Find ATM IV
# Simple Logic: Strike closest to Spot
atm_strike = min(formatted_chain, key=lambda x: abs(x['strike'] - spot_price))
atm_iv = (atm_strike.get('call_iv', 0) + atm_strike.get('put_iv', 0)) / 2
metrics = {
'total_gex': gex_res['total_gex'],
'flip_point': flip_point,
'atm_iv': atm_iv,
'fwd_vol': 0.0 # Needs multiple expiries
}
logger.info(f"Analyzed: Spot={spot_price} GEX={metrics['total_gex']:.2f} Flip={metrics['flip_point']}")
# 3. Save to DB
if self.db:
self.db.insert_vol_metrics(self.symbol, metrics)
def run(self):
logger.info("Starting Volatility Worker...")
while True:
try:
self.process_cycle()
except Exception as e:
logger.error(f"Worker Loop Error: {e}")
logger.info("Sleeping 60s...")
time.sleep(60)
if __name__ == "__main__":
worker = VolatilityWorker()
worker.run()