├── README.md ├── requirements.txt └── tradingView.py /README.md: -------------------------------------------------------------------------------- 1 | # tradingView-API 2 | tradingview socket api for fetching real time prices. 3 | 4 | ## How to run 5 | 6 | ``` 7 | git clone https://github.com/mohamadkhalaj/tradingView-API.git 8 | cd tradingView-API 9 | pip3 install -r requirements.txt 10 | python3 tradingView.py 11 | ``` 12 | 13 | # How to use 14 | 15 | First you should select category type and searching text (by search() function in the code): 16 | ``` 17 | category list: 'stock' | 'futures' | 'forex' | 'cfd' | 'crypto' | 'index' | 'economic' 18 | ``` 19 | # Example 20 | ```python 21 | data = search('btcusdt', 'crypto') 22 | ``` 23 | 24 | if any results found it will be shown. 25 | 26 | 27 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests==2.22.0 2 | websocket-client==0.53.0 3 | -------------------------------------------------------------------------------- /tradingView.py: -------------------------------------------------------------------------------- 1 | import json 2 | import random 3 | import re 4 | import string 5 | 6 | import requests 7 | from websocket import create_connection 8 | 9 | 10 | # Search for a symbol based on query and category 11 | def search(query, category): 12 | url = f"https://symbol-search.tradingview.com/symbol_search/?text={query}&type={category}" 13 | response = requests.get(url) 14 | 15 | if response.status_code == 200: 16 | data = response.json() 17 | assert len(data) != 0, "Nothing Found." 18 | return data[0] 19 | else: 20 | print("Network Error!") 21 | exit(1) 22 | 23 | 24 | # Generate a random session ID 25 | def generate_session(): 26 | string_length = 12 27 | letters = string.ascii_lowercase 28 | random_string = "".join(random.choice(letters) for _ in range(string_length)) 29 | return "qs_" + random_string 30 | 31 | 32 | # Prepend header to content 33 | def prepend_header(content): 34 | return f"~m~{len(content)}~m~{content}" 35 | 36 | 37 | # Construct a JSON message 38 | def construct_message(func, param_list): 39 | return json.dumps({"m": func, "p": param_list}, separators=(",", ":")) 40 | 41 | 42 | # Create a full message with header 43 | def create_message(func, param_list): 44 | return prepend_header(construct_message(func, param_list)) 45 | 46 | 47 | # Send a message over the WebSocket connection 48 | def send_message(ws, func, args): 49 | ws.send(create_message(func, args)) 50 | 51 | 52 | # Send a ping packet 53 | def send_ping_packet(ws, result): 54 | ping_str = re.findall(".......(.*)", result) 55 | if ping_str: 56 | ping_str = ping_str[0] 57 | ws.send(f"~m~{len(ping_str)}~m~{ping_str}") 58 | 59 | 60 | # Handle WebSocket messages 61 | def socket_job(ws): 62 | while True: 63 | try: 64 | result = ws.recv() 65 | if "quote_completed" in result or "session_id" in result: 66 | continue 67 | res = re.findall("^.*?({.*)$", result) 68 | if res: 69 | json_res = json.loads(res[0]) 70 | if json_res["m"] == "qsd": 71 | prefix = json_res["p"][1] 72 | symbol = prefix["n"] 73 | price = prefix["v"].get("lp", None) 74 | volume = prefix["v"].get("volume", None) 75 | change = prefix["v"].get("ch", None) 76 | change_percentage = prefix["v"].get("chp", None) 77 | print(f"{symbol} -> {price=}, {change=}, {change_percentage=}, {volume=}") 78 | else: 79 | send_ping_packet(ws, result) 80 | except KeyboardInterrupt: 81 | print("\nGoodbye!") 82 | exit(0) 83 | except Exception as e: 84 | print(f"ERROR: {e}\nTradingView message: {result}") 85 | continue 86 | 87 | 88 | # Get symbol ID based on pair and market 89 | def get_symbol_id(pair, market): 90 | data = search(pair, market) 91 | symbol_name = data["symbol"] 92 | broker = data.get("prefix", data["exchange"]) 93 | symbol_id = f"{broker.upper()}:{symbol_name.upper()}" 94 | print(symbol_id, end="\n\n") 95 | return symbol_id 96 | 97 | 98 | # Main function to establish WebSocket connection and start job 99 | def main(pair, market): 100 | symbol_id = get_symbol_id(pair, market) 101 | 102 | trading_view_socket = "wss://data.tradingview.com/socket.io/websocket" 103 | headers = json.dumps({"Origin": "https://data.tradingview.com"}) 104 | ws = create_connection(trading_view_socket, headers=headers) 105 | session = generate_session() 106 | 107 | send_message(ws, "quote_create_session", [session]) 108 | send_message( 109 | ws, 110 | "quote_set_fields", 111 | [ 112 | session, 113 | "lp", 114 | "volume", 115 | "ch", 116 | "chp", 117 | ], 118 | ) 119 | send_message(ws, "quote_add_symbols", [session, symbol_id]) 120 | 121 | socket_job(ws) 122 | 123 | 124 | if __name__ == "__main__": 125 | pair = "btcusdt" 126 | market = "crypto" 127 | main(pair, market) 128 | --------------------------------------------------------------------------------