python - 从 python 中的 tradingview 访问私有 websocket 数据
问题描述
我可以使用此代码获取实时代码数据和之前的 500-100 蜡烛图数据,但我无法获取 CME_MINI:ESH2021 未延迟的数据。我相信 TradingView 在公共流中延迟了 600 秒。我确实为数据付费,我可以在网络客户端上提取它,但我无法在 python 上获取非延迟数据,因为我不确定如何通过 python 登录到 TradingView。如果有人知道我如何修复我的代码来做我想做的事,我将非常感谢您的意见或任何建议。
from websocket import create_connection
import json
import random
import string
import re
from datetime import datetime
from time import sleep
def filter_raw_message(text):
try:
found = re.search('"p":(.+?"}"])}', text).group(1)
print(found)
return found
except AttributeError:
print("error")
def generateSession():
stringLength=12
letters = string.ascii_lowercase
random_string= ''.join(random.choice(letters) for i in range(stringLength))
return "qs_" +random_string
def generateChartSession():
stringLength=12
letters = string.ascii_lowercase
random_string= ''.join(random.choice(letters) for i in range(stringLength))
return "cs_" +random_string
def prependHeader(st):
return "~m~" + str(len(st)) + "~m~" + st
def constructMessage(func, paramList):
#json_mylist = json.dumps(mylist, separators=(',', ':'))
return json.dumps({
"m":func,
"p":paramList
}, separators=(',', ':'))
def createMessage(func, paramList):
return prependHeader(constructMessage(func, paramList))
def sendRawMessage(ws, message):
ws.send(prependHeader(message))
def sendMessage(ws, func, args):
ws.send(createMessage(func, args))
# Initialize the headers needed for the websocket connection
headers = json.dumps({
'Connection': 'upgrade',
'Host': 'data.tradingview.com',
'Origin': 'https://data.tradingview.com',
'Cache-Control': 'no-cache',
'Upgrade': 'websocket',
'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
'Sec-WebSocket-Key': '1H41q97V8BbMKUq0knV1UA==',
'Sec-WebSocket-Version': '13',
'User-Agent': 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36 Edg/83.0.478.56',
'Pragma': 'no-cache',
'Upgrade': 'websocket'
})
# Then create a connection to the tunnel
ws = create_connection(
'wss://data.tradingview.com/socket.io/websocket',headers=headers)
session= generateSession()
print("session generated {}".format(session))
chart_session= generateChartSession()
print("chart_session generated {}".format(chart_session))
symbol = "CME_MINI:ESH2021"
timeframe = "5"
candles = 100
# Then send a message through the tunnel
sendMessage(ws, "set_auth_token", ["unauthorized_user_token"])
sendMessage(ws, "chart_create_session", [chart_session, ""])
sendMessage(ws, "quote_create_session", [session])
sendMessage(ws,"quote_set_fields", [session,"ch","chp","current_session","description","local_description","language","exchange","fractional","is_tradable","lp","lp_time","minmov","minmove2","original_name","pricescale","pro_name","short_name","type","update_mode","volume","currency_code","rchp","rtc"])
sendMessage(ws, "quote_add_symbols",[session, symbol, {"flags":['force_permission']}])
theString1 = "={\"symbol\":\""
theString2 = "\",\"adjustment\":\"splits\"}"
theString3 = theString1 + symbol + theString2
sendMessage(ws, "resolve_symbol", [chart_session, "symbol_" + timeframe, theString3])
sendMessage(ws, "create_series", [chart_session,"s" + timeframe,"s" + timeframe,"symbol_" + timeframe,timeframe,candles])
sendMessage(ws, "quote_fast_symbols", [session,symbol])
sendMessage(ws, "create_study", [chart_session,"st" + timeframe,"st" + timeframe,"s" + timeframe,"Volume@tv-basicstudies-118",{"length":20,"col_prev_close":"false"}])
sendMessage(ws, "quote_hibernate_all", [session])
# Printing all the result
a=""
while True:
try:
sleep(1)
result = ws.recv()
pattern = re.compile("~m~\d+~m~~h~\d+$")
if pattern.match(result):
ws.recv()
ws.send(result)
print("\n\n\n hhhhhhhhhhhhhhhhhhhhhh "+ str(result) + "\n\n")
print(result)
a=a+result+"\n"
except Exception as e:
print(e)
break
解决方案
推荐阅读
- graph - 图数据库中的建模时间
- python - 这些功能是如何实现的?
- powershell - Powershell远程:具有嵌套函数的函数
- java - 为什么 apache http 客户端比 java 中的 URL.openConnection 慢 2 倍?
- mysql - 如何在存在时选择列的值
- android - Room:错误:不确定如何将 Cursor 转换为此方法的返回类型(void)
- c++ - 将 bmp 文件加载到 TSpeedButton
- javascript - 如何替换 ie 的 Object.entries?
- assembly - 关于单步执行代码与在 GDB 中转储内存内容的不同指令
- node.js - 如何在没有循环依赖的情况下在环回 4 上实现自引用模型