Skip to content

Commit

Permalink
patch for TradingView search API change to v3
Browse files Browse the repository at this point in the history
 - Tradingview have changed their search API to "v3". In addition,
   their Nginx frontend now blocks requests with Origin+Referer other
   than their own site.
 - fixes rongardF#45
 - version bumped to 2.1.0_issue45
 - only tested with Python 3.12

Changes in this commit:
	modified:   __init__.py
	modified:   main.py
  • Loading branch information
dietmarb01 committed May 5, 2024
1 parent e6f6aaa commit b73f7d1
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
2 changes: 1 addition & 1 deletion tvDatafeed/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
from .datafeed import TvDatafeedLive
from .consumer import Consumer

__version__ = "2.1.0"
__version__ = "2.1.0_issue45"
13 changes: 8 additions & 5 deletions tvDatafeed/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,10 @@ class Interval(enum.Enum):

class TvDatafeed:
__sign_in_url = 'https://www.tradingview.com/accounts/signin/'
__search_url = 'https://symbol-search.tradingview.com/symbol_search/?text={}&hl=1&exchange={}&lang=en&type=&domain=production'
__search_url = 'https://symbol-search.tradingview.com/symbol_search/v3/?text={}&hl=1&exchange={}&lang=en&search_type=&domain=production'
__ws_headers = json.dumps({"Origin": "https://data.tradingview.com"})
__signin_headers = {'Referer': 'https://www.tradingview.com'}
__search_headers = {'Referer': 'https://www.tradingview.com', 'Origin': 'https://data.tradingview.com'}
__ws_timeout = 5

def __init__(
Expand Down Expand Up @@ -294,11 +295,13 @@ def search_symbol(self, text: str, exchange: str = ''):

symbols_list = []
try:
resp = requests.get(url)
# Need Referer _and_ Origin headers, otherwise their Nginx frontend returns 403 :-(
resp = requests.get(url, headers=self.__search_headers, timeout=60)
resp.raise_for_status()

symbols_list = json.loads(resp.text.replace(
'</em>', '').replace('<em>', ''))
except Exception as e:
# As of v3, this returns a dict: {'symbols_remaining':<int>, 'symbols': [...]}
symbols_list = json.loads(resp.text).get('symbols', [])
except Exception as e: # pylint: disable=broad-exception-caught
logger.error(e)

return symbols_list
Expand Down

0 comments on commit b73f7d1

Please sign in to comment.