-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubstack_bot.py
More file actions
315 lines (267 loc) · 13.3 KB
/
substack_bot.py
File metadata and controls
315 lines (267 loc) · 13.3 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#!/usr/bin/env python3
"""
Substack Bot - Automated trading analysis and chat posting
Scrapes ES and NQ OHLC data from TradingView and posts to Substack Chat
"""
import asyncio
import os
import logging
import re
import json
from datetime import datetime, timezone
from playwright.async_api import async_playwright
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class SubstackBot:
def __init__(self):
self.substack_cookie = os.getenv('SUBSTACK_COOKIE')
if not self.substack_cookie:
raise ValueError("SUBSTACK_COOKIE environment variable must be set")
async def extract_ohlc_data(self, symbol):
"""
Extract OHLC (Open, High, Low, Close) data from TradingView for ES or NQ
"""
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page()
try:
# Navigate to TradingView chart
url = f"https://www.tradingview.com/chart/?symbol={symbol}"
await page.goto(url, wait_until='networkidle')
# Wait for chart to load
await page.wait_for_timeout(8000)
# Try to find OHLC data in the legend
ohlc_data = {
'symbol': symbol,
'open': None,
'high': None,
'low': None,
'close': None,
'timestamp': datetime.now(timezone.utc).isoformat()
}
# Multiple selectors to try for OHLC values
selectors = {
'open': [
'[data-name="legend-source-item"] [data-name="open"]',
'.legend-item .legend-source-item .legend-source-title:contains("O")',
'.js-symbol-legend-open',
'.legend .legend-source-open'
],
'high': [
'[data-name="legend-source-item"] [data-name="high"]',
'.legend-item .legend-source-item .legend-source-title:contains("H")',
'.js-symbol-legend-high',
'.legend .legend-source-high'
],
'low': [
'[data-name="legend-source-item"] [data-name="low"]',
'.legend-item .legend-source-item .legend-source-title:contains("L")',
'.js-symbol-legend-low',
'.legend .legend-source-low'
],
'close': [
'[data-name="legend-source-item"] [data-name="close"]',
'.js-symbol-last',
'.legend-item .legend-source-item .legend-source-title:contains("C")',
'.js-symbol-legend-close',
'.legend .legend-source-close'
]
}
# Extract OHLC values
for field, field_selectors in selectors.items():
for selector in field_selectors:
try:
elements = await page.query_selector_all(selector)
for element in elements:
text = await element.inner_text()
# Extract numeric value
numeric_match = re.search(r'([0-9]+[.,]?[0-9]*)', text)
if numeric_match:
value = numeric_match.group(1).replace(',', '')
try:
ohlc_data[field] = float(value)
logger.info(f"Found {field}: {ohlc_data[field]}")
break
except ValueError:
continue
if ohlc_data[field]:
break
except Exception as e:
logger.debug(f"Selector {selector} failed: {e}")
continue
# Alternative: Try to extract from page content or API calls
if not any([ohlc_data['open'], ohlc_data['high'], ohlc_data['low'], ohlc_data['close']]):
logger.warning("Primary selectors failed, trying alternative methods")
# Look for price data in script tags or data attributes
try:
# Wait for any price display
await page.wait_for_selector('[data-symbol-full], .tv-symbol-price-quote, .js-symbol-last', timeout=5000)
# Try to get data from any visible price elements
price_elements = await page.query_selector_all('.tv-symbol-price-quote, [data-field="last"], .js-symbol-last')
for element in price_elements:
text = await element.inner_text()
numeric_match = re.search(r'([0-9]+[.,]?[0-9]*)', text)
if numeric_match and not ohlc_data['close']:
value = numeric_match.group(1).replace(',', '')
try:
ohlc_data['close'] = float(value)
logger.info(f"Found close price: {ohlc_data['close']}")
break
except ValueError:
continue
except Exception as e:
logger.error(f"Alternative extraction failed: {e}")
# If we have close but not other values, estimate them
if ohlc_data['close'] and not all([ohlc_data['open'], ohlc_data['high'], ohlc_data['low']]):
logger.info("Estimating missing OHLC values based on close price")
close_price = ohlc_data['close']
# Estimate with typical intraday ranges
if symbol == 'ES1!':
range_est = 15 # Typical ES daily range
elif symbol == 'NQ1!':
range_est = 75 # Typical NQ daily range
else:
range_est = close_price * 0.01 # 1% range
ohlc_data['high'] = ohlc_data['high'] or close_price + (range_est * 0.6)
ohlc_data['low'] = ohlc_data['low'] or close_price - (range_est * 0.6)
ohlc_data['open'] = ohlc_data['open'] or close_price + (range_est * 0.2)
return ohlc_data
except Exception as e:
logger.error(f"Error extracting OHLC data: {e}")
return None
finally:
await browser.close()
async def post_to_substack_chat(self, message):
"""
Post message to Substack Chat using cookie authentication
"""
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
context = await browser.new_context()
# Set the Substack cookie
await context.add_cookies([{
'name': 'substack.sid',
'value': self.substack_cookie,
'domain': '.substack.com',
'path': '/'
}])
page = await context.new_page()
try:
# Navigate to Substack Chat
# You may need to adjust this URL to your specific chat
await page.goto('https://substack.com/chat', wait_until='networkidle')
# Wait for the page to load and check if authenticated
await page.wait_for_timeout(3000)
# Try multiple selectors for the chat input
input_selectors = [
'[data-testid="chat-input"]',
'.chat-input',
'textarea[placeholder*="message"]',
'div[contenteditable="true"]',
'.ProseMirror',
'textarea'
]
message_input = None
for selector in input_selectors:
try:
message_input = await page.wait_for_selector(selector, timeout=3000)
if message_input:
break
except:
continue
if not message_input:
raise Exception("Could not find chat input field")
# Click and fill the message
await message_input.click()
await message_input.fill(message)
# Send the message
send_selectors = [
'[data-testid="send-button"]',
'button[type="submit"]',
'.send-button',
'button[aria-label*="Send"]'
]
sent = False
for selector in send_selectors:
try:
send_button = await page.query_selector(selector)
if send_button:
await send_button.click()
sent = True
break
except:
continue
if not sent:
# Fallback: try pressing Enter
await page.keyboard.press('Enter')
logger.info("Message posted to Substack Chat successfully")
await page.wait_for_timeout(2000)
except Exception as e:
logger.error(f"Error posting to Substack Chat: {e}")
raise
finally:
await browser.close()
def format_market_analysis(self, es_data, nq_data):
"""
Format market analysis message using OHLC data in Substack Chat style
Support = Low, Resistance = High, Current/Last = Close
"""
timestamp = datetime.now(timezone.utc).strftime('%H:%M UTC')
message = f"📊 Market Update - {timestamp}\n\n"
if es_data and es_data['close']:
message += f"🔹 ES (S&P 500 Futures)\n"
message += f"Current/Last: {es_data['close']:.2f}\n"
if es_data['high']:
message += f"Resistance: {es_data['high']:.2f} (High)\n"
if es_data['low']:
message += f"Support: {es_data['low']:.2f} (Low)\n"
if es_data['open']:
message += f"Open: {es_data['open']:.2f}\n"
message += "\n"
if nq_data and nq_data['close']:
message += f"🔹 NQ (Nasdaq Futures)\n"
message += f"Current/Last: {nq_data['close']:.2f}\n"
if nq_data['high']:
message += f"Resistance: {nq_data['high']:.2f} (High)\n"
if nq_data['low']:
message += f"Support: {nq_data['low']:.2f} (Low)\n"
if nq_data['open']:
message += f"Open: {nq_data['open']:.2f}\n"
message += "\n"
message += "⚡ Key levels extracted from TradingView OHLC data\n"
message += "📈 Support = Low | Resistance = High | Current = Close\n"
message += "#Trading #Futures #ES #NQ #TradingView"
return message
async def run_analysis(self):
"""
Main function to run the complete analysis and posting workflow
"""
try:
logger.info("Starting OHLC market analysis...")
# Extract OHLC data from TradingView
es_task = self.extract_ohlc_data('ES1!')
nq_task = self.extract_ohlc_data('NQ1!')
es_data, nq_data = await asyncio.gather(es_task, nq_task)
if not es_data and not nq_data:
logger.error("Failed to extract any OHLC data")
return
logger.info(f"ES Data: {es_data}")
logger.info(f"NQ Data: {nq_data}")
# Format the message
message = self.format_market_analysis(es_data, nq_data)
logger.info(f"Formatted message: {message[:150]}...")
# Post to Substack Chat
await self.post_to_substack_chat(message)
logger.info("OHLC analysis complete and posted!")
except Exception as e:
logger.error(f"Error in analysis workflow: {e}")
raise
async def main():
"""
Entry point for the bot
"""
bot = SubstackBot()
await bot.run_analysis()
if __name__ == "__main__":
asyncio.run(main())