-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
190 lines (169 loc) · 6.73 KB
/
Copy pathapp.py
File metadata and controls
190 lines (169 loc) · 6.73 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
import os
import logging
from flask import Flask, jsonify
from flask_restful import Api, Resource
from tradingview_ta import TA_Handler, Interval, Exchange
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# Initialize Flask app
app = Flask(__name__)
# Configuration
app.config['ENV'] = os.getenv('FLASK_ENV', 'production')
app.config['DEBUG'] = os.getenv('DEBUG', 'False').lower() == 'true'
# Initialize API
api = Api(app)
# Interval mapping for better maintainability
INTERVAL_MAPPING = {
'1m': Interval.INTERVAL_1_MINUTE,
'5m': Interval.INTERVAL_5_MINUTES,
'15m': Interval.INTERVAL_15_MINUTES,
'30m': Interval.INTERVAL_30_MINUTES,
'1h': Interval.INTERVAL_1_HOUR,
'2h': Interval.INTERVAL_2_HOURS,
'4h': Interval.INTERVAL_4_HOURS,
'1d': Interval.INTERVAL_1_DAY,
'1w': Interval.INTERVAL_1_WEEK,
'1month': Interval.INTERVAL_1_MONTH
}
class APIInfo(Resource):
"""Main API information and usage examples"""
def get(self):
return {
'service': 'TradingView Technical Analysis API',
'version': '2.0.0',
'description': 'Get technical analysis data for stocks, crypto, and forex from TradingView',
'usage': {
'format': '/{symbol}/{screener}/{exchange}/{timeinterval}',
'examples': [
{
'url': '/AAPL/america/NASDAQ/1d',
'description': 'Apple stock daily analysis on NASDAQ'
},
{
'url': '/BTCUSD/crypto/BINANCE/4h',
'description': 'Bitcoin 4-hour analysis on Binance'
},
{
'url': '/EURUSD/forex/FX_IDC/1h',
'description': 'EUR/USD 1-hour forex analysis'
}
]
},
'parameters': {
'symbol': 'Trading symbol (e.g., AAPL, BTCUSD, EURUSD)',
'screener': 'Market screener (america, crypto, forex)',
'exchange': 'Exchange name (NASDAQ, BINANCE, FX_IDC, etc.)',
'timeinterval': f'Time interval {list(INTERVAL_MAPPING.keys())}'
},
'endpoints': {
'health_check': '/health',
'analysis': '/{symbol}/{screener}/{exchange}/{timeinterval}'
}
}, 200
class HealthCheck(Resource):
"""Health check endpoint for monitoring and load balancers"""
def get(self):
return {
'status': 'healthy',
'service': 'TradingView Technical Analysis API',
'version': '2.0.0'
}, 200
class TradingView(Resource):
def get(self, symbol, screener, exchange, timeinterval):
try:
# Validate time interval
if timeinterval not in INTERVAL_MAPPING:
return {
'error': 'Invalid time interval',
'message': f'Supported intervals: {list(INTERVAL_MAPPING.keys())}',
'provided': timeinterval
}, 400
# Log the request
logger.info(f"Processing request: {symbol}/{screener}/{exchange}/{timeinterval}")
# Get time frame
time_frame = INTERVAL_MAPPING[timeinterval]
# Create TA Handler
ta_handler = TA_Handler(
symbol=symbol.upper(),
screener=screener.lower(),
exchange=exchange.upper(),
interval=time_frame
)
# Get analysis
analysis = ta_handler.get_analysis()
if not analysis:
return {
'error': 'Analysis not available',
'message': 'Unable to fetch analysis data for the given parameters'
}, 404
# Return the summary with additional metadata
result = {
'data': analysis.summary,
'symbol': symbol.upper(),
'screener': screener.lower(),
'exchange': exchange.upper(),
'interval': timeinterval,
'timestamp': analysis.time.isoformat() if hasattr(analysis, 'time') and analysis.time else None
}
logger.info(f"Successfully processed: {symbol}/{screener}/{exchange}/{timeinterval}")
return result, 200
except ValueError as ve:
logger.error(f"Value error for {symbol}/{screener}/{exchange}/{timeinterval}: {str(ve)}")
return {
'error': 'Invalid parameters',
'message': str(ve)
}, 400
except Exception as e:
logger.error(f"Error processing {symbol}/{screener}/{exchange}/{timeinterval}: {str(e)}")
return {
'error': 'Internal server error',
'message': 'An error occurred while processing your request'
}, 500
# Error handlers
@app.errorhandler(404)
def not_found(error):
return jsonify({
'error': 'Endpoint not found',
'message': 'The TradingView Technical Analysis API requires specific parameters',
'usage': {
'format': '/{symbol}/{screener}/{exchange}/{timeinterval}',
'examples': [
{
'url': '/AAPL/america/NASDAQ/1d',
'description': 'Apple stock daily analysis on NASDAQ'
},
{
'url': '/BTCUSD/crypto/BINANCE/4h',
'description': 'Bitcoin 4-hour analysis on Binance'
},
{
'url': '/EURUSD/forex/FX_IDC/1h',
'description': 'EUR/USD 1-hour forex analysis'
}
]
},
'parameters': {
'symbol': 'Trading symbol (e.g., AAPL, BTCUSD, EURUSD)',
'screener': 'Market screener (america, crypto, forex)',
'exchange': 'Exchange name (NASDAQ, BINANCE, FX_IDC, etc.)',
'timeinterval': f'Time interval {list(INTERVAL_MAPPING.keys())}'
},
'health_check': '/health'
}), 404
@app.errorhandler(500)
def internal_error(error):
return jsonify({
'error': 'Internal server error',
'message': 'An internal error occurred'
}), 500
# Add resources to API
api.add_resource(APIInfo, '/')
api.add_resource(HealthCheck, '/health')
api.add_resource(TradingView, "/<string:symbol>/<string:screener>/<string:exchange>/<string:timeinterval>")
if __name__ == "__main__":
port = int(os.getenv('PORT', 8000))
app.run(host='0.0.0.0', port=port, debug=app.config['DEBUG'])