vee 3 years ago
parent
commit
7d62a2ea15
  1. BIN
      .DS_Store
  2. 2
      components/kline/tradingView/chartConfig.js
  3. 1841
      components/kline/tradingView/contract.js
  4. 58
      components/kline/tradingView/datafeed.js
  5. 418
      components/kline/tradingView/datafeed2.js
  6. 130
      components/kline/tradingView/websocket.js
  7. 296
      components/kline/tradingView/websocket2.js

BIN
.DS_Store

Binary file not shown.

2
components/kline/tradingView/chartConfig.js

@ -39,7 +39,7 @@ var chartConfig = {
"header_resolutions", "header_resolutions",
"left_toolbar", "left_toolbar",
"header_screenshot", "header_screenshot",
"header_chart_type", //"header_chart_type",
"header_settings", "header_settings",
"header_fullscreen_button", "header_fullscreen_button",
"header_undo_redo", "header_undo_redo",

1841
components/kline/tradingView/contract.js

File diff suppressed because it is too large

58
components/kline/tradingView/datafeed.js

@ -15,7 +15,7 @@ import {
// 历史数据 第一条数据的 时间撮 因为k线图一次性历史数据只拿一部分,用户吧图往前滑动,就会用这个时间撮去请求更早的 历史数据 // 历史数据 第一条数据的 时间撮 因为k线图一次性历史数据只拿一部分,用户吧图往前滑动,就会用这个时间撮去请求更早的 历史数据
var detafeed_historyTime = null var detafeed_historyTime = 0
// 上一次的 K线周期 切换产品的时候 需要从websock 取消订阅这个 // 上一次的 K线周期 切换产品的时候 需要从websock 取消订阅这个
var detafeed_lastResolution = null var detafeed_lastResolution = null
// 上一次的产品 切换产品的时候 需要从websock 取消订阅这个 // 上一次的产品 切换产品的时候 需要从websock 取消订阅这个
@ -32,7 +32,7 @@ FeedBase.prototype.getSendSymbolName = function(symbolName) {
var name = symbolName.split('/') var name = symbolName.split('/')
return (name[0] + name[1]).toLocaleLowerCase() return (name[0] + name[1]).toLocaleLowerCase()
} }
FeedBase.prototype.resolveSymbol = function(symbolName, onResolve, onError) { FeedBase.prototype.resolveSymbol = function(symbolName, onResolve, onError) {
onResolve({ onResolve({
"name": symbolName, "name": symbolName,
@ -45,15 +45,10 @@ FeedBase.prototype.resolveSymbol = function(symbolName, onResolve, onError) {
"session": "24x7", "session": "24x7",
"type": "bitcoin", "type": "bitcoin",
"volume_precision": 10, "volume_precision": 10,
"has_intraday": true, "has_intraday": true,
"seconds_multipliers":['1', '5', '15', '30', '60', '1D', '1W','1M'], "intraday_multipliers": ['1', '5', '15', '30', '60', '240', '1440'], // 时间
"intraday_multipliers": ['1', '5', '15', '30', '60', '1D', '1W','1M'], "has_weekly_and_monthly": false,
"has_seconds":true, "has_no_volume": false,
"supports_marks": true,
"supports_timescale_marks": true,
"supported_time": true,
"has_weekly_and_monthly": true,
"has_no_volume": true,
"regular_session": "24x7", "regular_session": "24x7",
}) })
@ -70,7 +65,7 @@ FeedBase.prototype.resolveSymbol = function(symbolName, onResolve, onError) {
const resolutionFormat = (resolution, name, to) => { const resolutionFormat = (resolution, name, to) => {
let req = `market.${name}.kline.${resolution}min`; let req = `market.${name}.kline.${resolution}min`;
let minutes = resolution; let minutes = resolution;
console.log(resolution)
if (resolution.includes('D')) { if (resolution.includes('D')) {
if (resolution.length < 2) resolution = '1' + resolution; if (resolution.length < 2) resolution = '1' + resolution;
req = `market.${name}.kline.${parseInt(resolution)}day`; req = `market.${name}.kline.${parseInt(resolution)}day`;
@ -91,12 +86,11 @@ const resolutionFormat = (resolution, name, to) => {
let from = null; let from = null;
if (to) { if (to) {
from = to - 50 * minutes * 500; from = to - 50 * minutes * 60;
if (resolution.includes('M') || resolution.includes('W')) { // 周线月线控制条数,时间超出火币规定范围, ws报错 if (resolution.includes('M') || resolution.includes('W')) { // 周线月线控制条数,时间超出火币规定范围, ws报错
from = to - 50 * minutes * 500; from = to - 50 * minutes * 60;
} }
} }
return { return {
minutes, minutes,
req, req,
@ -106,13 +100,11 @@ const resolutionFormat = (resolution, name, to) => {
}; };
FeedBase.prototype.getBars = function(symbolInfo, resolution, periodParams, onHistoryCallback, onErrorCallback) { FeedBase.prototype.getBars = function(symbolInfo, resolution, periodParams, onHistoryCallback, onErrorCallback) {
console.log("获取历史数据",periodParams) console.log("获取历史数据")
// 切换产品周期 或者 切换产品 会执行这个函数 // 切换产品周期 或者 切换产品 会执行这个函数
let reso = resolutionFormat(resolution, symbolInfo.name, periodParams.to) let reso = resolutionFormat(resolution, symbolInfo.name, periodParams.to > detafeed_historyTime ? periodParams
// if (resolution.includes('M') || resolution.includes('W')|| resolution.includes('D')) { // 周线月线控制条数,时间超出火币规定范围, ws报错 .to :
// reso = resolutionFormat(resolution, symbolInfo.name, periodParams.to) detafeed_historyTime)
// }
// 是历史数据 // 是历史数据
var history = true var history = true
/* /*
@ -135,19 +127,16 @@ FeedBase.prototype.getBars = function(symbolInfo, resolution, periodParams, onHi
第二个参数订阅实时数据 第二个参数订阅实时数据
第三个参数 是否是历史数据 第三个参数 是否是历史数据
*/ */
socket.sendData({ socket.sendData({
event: "req", req: reso.req,
type: "kline", id: "id10",
channel: [reso.req], from: reso.from,
fromDate:reso.from, to: reso.to,
toDate:reso.to
}, reso.req, history) }, reso.req, history)
Event.off('data') Event.off('data')
Event.on('data', data => { Event.on('data', data => {
if (data && Array.isArray(data)) { if (data && Array.isArray(data)) {
// 记录这次请求的时间周期 // 记录这次请求的时间周期
detafeed_lastResolution = resolution detafeed_lastResolution = resolution
@ -162,14 +151,13 @@ FeedBase.prototype.getBars = function(symbolInfo, resolution, periodParams, onHi
i.volume = i.vol i.volume = i.vol
datas.push(i) datas.push(i)
} }
} else { } else {
console.log('进来')
meta = { meta = {
noData: 'no_data', noData: true,
nextTime: detafeed_historyTime nextTime: detafeed_historyTime
} }
} }
onHistoryCallback(datas, {noData:data.length==0}) onHistoryCallback(datas, meta)
} }
}) })
} }

418
components/kline/tradingView/datafeed1.js → components/kline/tradingView/datafeed2.js

@ -1,205 +1,217 @@
/*********************************************/ /*********************************************/
// 次文件只需要关注 getBars 和 subscribeBars 函数即可 // 次文件只需要关注 getBars 和 subscribeBars 函数即可
/******************************************/ /******************************************/
import { import {
socket socket
} from './websocket.js' } from './websocket.js'
import { import {
Event Event
} from './event.js' } from './event.js'
// 历史数据 第一条数据的 时间撮 因为k线图一次性历史数据只拿一部分,用户吧图往前滑动,就会用这个时间撮去请求更早的 历史数据 // 历史数据 第一条数据的 时间撮 因为k线图一次性历史数据只拿一部分,用户吧图往前滑动,就会用这个时间撮去请求更早的 历史数据
var detafeed_historyTime = 0 var detafeed_historyTime = null
// 上一次的 K线周期 切换产品的时候 需要从websock 取消订阅这个 // 上一次的 K线周期 切换产品的时候 需要从websock 取消订阅这个
var detafeed_lastResolution = null var detafeed_lastResolution = null
// 上一次的产品 切换产品的时候 需要从websock 取消订阅这个 // 上一次的产品 切换产品的时候 需要从websock 取消订阅这个
var detafeed_lastSymbol = null var detafeed_lastSymbol = null
function FeedBase() {} function FeedBase() {}
FeedBase.prototype.onReady = function(callback) { FeedBase.prototype.onReady = function(callback) {
callback(this._configuration) callback(this._configuration)
} }
FeedBase.prototype.getSendSymbolName = function(symbolName) { FeedBase.prototype.getSendSymbolName = function(symbolName) {
var name = symbolName.split('/') var name = symbolName.split('/')
return (name[0] + name[1]).toLocaleLowerCase() return (name[0] + name[1]).toLocaleLowerCase()
} }
FeedBase.prototype.resolveSymbol = function(symbolName, onResolve, onError) { FeedBase.prototype.resolveSymbol = function(symbolName, onResolve, onError) {
onResolve({ onResolve({
"name": symbolName, "name": symbolName,
"timezone": "Asia/Shanghai", "timezone": "Asia/Shanghai",
"pricescale": 10000000000000000, "pricescale": 10000000000000000,
"minmov": 1, "minmov": 1,
"minmov2": 0, "minmov2": 0,
"ticker": symbolName, "ticker": symbolName,
"description": "", "description": "",
"session": "24x7", "session": "24x7",
"type": "bitcoin", "type": "bitcoin",
"volume_precision": 10, "volume_precision": 10,
"has_intraday": true, "has_intraday": true,
"intraday_multipliers": ['1', '5', '15', '30', '60', '240', '1440'], // 时间 "seconds_multipliers":['1', '5', '15', '30', '60', '1D', '1W','1M'],
"has_weekly_and_monthly": false, "intraday_multipliers": ['1', '5', '15', '30', '60', '1D', '1W','1M'],
"has_no_volume": false, "has_seconds":true,
"supports_marks": true,
"supports_timescale_marks": true,
"supported_time": true,
"has_weekly_and_monthly": true,
"has_no_volume": true,
"regular_session": "24x7", "regular_session": "24x7",
}) })
} }
/** /**
* 更多时间类型在这里添加 时间类型请看火币文档 * 更多时间类型在这里添加 时间类型请看火币文档
* @param resolution 订阅周期 按照自己喜欢的来 30 30分钟 1D 一天 * @param resolution 订阅周期 按照自己喜欢的来 30 30分钟 1D 一天
* @param name 交易对symbol * @param name 交易对symbol
* @param to 结束时间 * @param to 结束时间
* @returns {object} * @returns {object}
*/ */
const resolutionFormat = (resolution, name, to) => { const resolutionFormat = (resolution, name, to) => {
let req = `market.${name}.kline.${resolution}min`; let req = `market.${name}.kline.${resolution}min`;
let minutes = resolution; let minutes = resolution;
console.log(resolution)
if (resolution.includes('D')) { if (resolution.includes('D')) {
if (resolution.length < 2) resolution = '1' + resolution; if (resolution.length < 2) resolution = '1' + resolution;
req = `market.${name}.kline.${parseInt(resolution)}day`; req = `market.${name}.kline.${parseInt(resolution)}day`;
minutes = parseInt(resolution) * 24 * 60; minutes = parseInt(resolution) * 24 * 60;
} else if (resolution.includes('W')) { } else if (resolution.includes('W')) {
if (resolution.length < 2) resolution = '1' + resolution; if (resolution.length < 2) resolution = '1' + resolution;
req = `market.${name}.kline.${parseInt(resolution)}week`; req = `market.${name}.kline.${parseInt(resolution)}week`;
minutes = parseInt(resolution) * 24 * 60 * 7; minutes = parseInt(resolution) * 24 * 60 * 7;
} else if (resolution.includes('M')) { } else if (resolution.includes('M')) {
if (resolution.length < 2) resolution = '1' + resolution; if (resolution.length < 2) resolution = '1' + resolution;
req = `market.${name}.kline.${parseInt(resolution)}mon`; req = `market.${name}.kline.${parseInt(resolution)}mon`;
minutes = parseInt(resolution) * 24 * 60 * 30; minutes = parseInt(resolution) * 24 * 60 * 30;
} else { } else {
if (resolution / 60 > 1) { if (resolution / 60 > 1) {
req = `market.${name}.kline.${resolution / 60}hour`; req = `market.${name}.kline.${resolution / 60}hour`;
} }
} }
let from = null; let from = null;
if (to) { if (to) {
from = to - 50 * minutes * 60; from = to - 50 * minutes * 500;
if (resolution.includes('M') || resolution.includes('W')) { // 周线月线控制条数,时间超出火币规定范围, ws报错 if (resolution.includes('M') || resolution.includes('W')) { // 周线月线控制条数,时间超出火币规定范围, ws报错
from = to - 50 * minutes * 60; from = to - 50 * minutes * 500;
} }
} }
return {
minutes, return {
req, minutes,
from, req,
to, from,
}; to,
}; };
};
FeedBase.prototype.getBars = function(symbolInfo, resolution, periodParams, onHistoryCallback, onErrorCallback) {
console.log("获取历史数据") FeedBase.prototype.getBars = function(symbolInfo, resolution, periodParams, onHistoryCallback, onErrorCallback) {
// 切换产品周期 或者 切换产品 会执行这个函数 console.log("获取历史数据",periodParams)
let reso = resolutionFormat(resolution, symbolInfo.name, periodParams.to > detafeed_historyTime ? periodParams // 切换产品周期 或者 切换产品 会执行这个函数
.to : let reso = resolutionFormat(resolution, symbolInfo.name, periodParams.to)
detafeed_historyTime) // if (resolution.includes('M') || resolution.includes('W')|| resolution.includes('D')) { // 周线月线控制条数,时间超出火币规定范围, ws报错
// 是历史数据 // reso = resolutionFormat(resolution, symbolInfo.name, periodParams.to)
var history = true // }
/*
!detafeed_historyTime 如果没请请求过这个产品或者这个周期的历史数据 // 是历史数据
resolution !== detafeed_lastResolution 是否更换了产品周期 var history = true
detafeed_lastSymbol !== symbolInfo.name 是否切换了产品 /*
*/ !detafeed_historyTime 如果没请请求过这个产品或者这个周期的历史数据
if (!detafeed_historyTime || (resolution !== detafeed_lastResolution) || detafeed_lastSymbol !== symbolInfo resolution !== detafeed_lastResolution 是否更换了产品周期
.name) { detafeed_lastSymbol !== symbolInfo.name 是否切换了产品
// 那就不是历史数据 */
history = false if (!detafeed_historyTime || (resolution !== detafeed_lastResolution) || detafeed_lastSymbol !== symbolInfo
// 储存请求过的产品 .name) {
detafeed_lastSymbol = symbolInfo.name // 那就不是历史数据
// 记录目前时间戳,就用目前时间戳往前请求历史数据 history = false
detafeed_historyTime = window.parseInt((Date.now() / 1000)) // 储存请求过的产品
} detafeed_lastSymbol = symbolInfo.name
/* // 记录目前时间戳,就用目前时间戳往前请求历史数据
@socket.sendData detafeed_historyTime = window.parseInt((Date.now() / 1000))
第一个参数订阅历史数据 }
第二个参数订阅实时数据 /*
第三个参数 是否是历史数据 @socket.sendData
*/ 第一个参数订阅历史数据
socket.sendData({ 第二个参数订阅实时数据
req: reso.req, 第三个参数 是否是历史数据
id: "id10", */
from: reso.from, socket.sendData({
to: reso.to, event: "req",
}, reso.req, history) type: "kline",
channel: [reso.req],
Event.off('data') fromDate:reso.from,
toDate:reso.to
Event.on('data', data => { }, reso.req, history)
if (data && Array.isArray(data)) {
// 记录这次请求的时间周期
detafeed_lastResolution = resolution Event.off('data')
var meta = {
noData: false Event.on('data', data => {
}
const datas = [] if (data && Array.isArray(data)) {
if (data.length) { // 记录这次请求的时间周期
detafeed_historyTime = data[0].id detafeed_lastResolution = resolution
for (let i of data) { var meta = {
i.time = i.id * 1000 noData: false
i.volume = i.vol }
datas.push(i) const datas = []
} if (data.length) {
} else { detafeed_historyTime = data[0].id
meta = { for (let i of data) {
noData: true, i.time = i.id * 1000
nextTime: detafeed_historyTime i.volume = i.vol
} datas.push(i)
} }
onHistoryCallback(datas, meta) } else {
} console.log('进来')
}) meta = {
} noData: 'no_data',
nextTime: detafeed_historyTime
FeedBase.prototype.subscribeBars = function(symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback) { }
Event.off('realTime') }
// 拿到实时数据 在这里画 onHistoryCallback(datas, {noData:data.length==0})
Event.on('realTime', data => { }
if (Object.prototype.toString.call(data) === '[object Object]' && data.hasOwnProperty('open')) { })
//因为有的数值为科学计数法,故增加了转换函数,因为修改了源码中处理小数点的代码,所以需要二次元运算 }
//如果大于1则根据float形式进行toFixed(2),如果小于1则按照string形式进行截取处理显示
let realtimeData = { FeedBase.prototype.subscribeBars = function(symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback) {
time: data.id * 1000, Event.off('realTime')
volume: data.vol <= 0.00001 ? transferToNumber(data.vol) : data.vol, // 拿到实时数据 在这里画
close: data.close <= 0.00001 ? transferToNumber(data.close) : data.close, Event.on('realTime', data => {
open: data.open <= 0.00001 ? transferToNumber(data.open) : data.open, if (Object.prototype.toString.call(data) === '[object Object]' && data.hasOwnProperty('open')) {
high: data.high <= 0.00001 ? transferToNumber(data.high) : data.high, //因为有的数值为科学计数法,故增加了转换函数,因为修改了源码中处理小数点的代码,所以需要二次元运算
low: data.low <= 0.00001 ? transferToNumber(data.low) : data.low //如果大于1则根据float形式进行toFixed(2),如果小于1则按照string形式进行截取处理显示
} let realtimeData = {
onRealtimeCallback(realtimeData) time: data.id * 1000,
} volume: data.vol <= 0.00001 ? transferToNumber(data.vol) : data.vol,
}) close: data.close <= 0.00001 ? transferToNumber(data.close) : data.close,
} open: data.open <= 0.00001 ? transferToNumber(data.open) : data.open,
high: data.high <= 0.00001 ? transferToNumber(data.high) : data.high,
FeedBase.prototype.unsubscribeBars = function(listenerGuid) { low: data.low <= 0.00001 ? transferToNumber(data.low) : data.low
// 取消订阅产品的callback }
} onRealtimeCallback(realtimeData)
}
})
}
//处理科学计数法 FeedBase.prototype.unsubscribeBars = function(listenerGuid) {
function transferToNumber(inputNumber) { // 取消订阅产品的callback
if (isNaN(inputNumber)) { }
return inputNumber
}
inputNumber = '' + inputNumber
inputNumber = parseFloat(inputNumber)
let eformat = inputNumber.toExponential() // 转换为标准的科学计数法形式(字符串) //处理科学计数法
let tmpArray = eformat.match(/\d(?:\.(\d*))?e([+-]\d+)/) // 分离出小数值和指数值 function transferToNumber(inputNumber) {
let number = inputNumber.toFixed(Math.max(0, (tmpArray[1] || '').length - tmpArray[2])) if (isNaN(inputNumber)) {
return number return inputNumber
} }
inputNumber = '' + inputNumber
inputNumber = parseFloat(inputNumber)
let eformat = inputNumber.toExponential() // 转换为标准的科学计数法形式(字符串)
let tmpArray = eformat.match(/\d(?:\.(\d*))?e([+-]\d+)/) // 分离出小数值和指数值
let number = inputNumber.toFixed(Math.max(0, (tmpArray[1] || '').length - tmpArray[2]))
return number
}
exports.FeedBase = FeedBase exports.FeedBase = FeedBase

130
components/kline/tradingView/websocket.js

@ -1,47 +1,45 @@
import
constant
from '@/utils/constant.js'
import { import {
Event Event
} from './event.js' } from './event.js'
import pakoJs from './pako.js' import pakoJs from './pako.js'
var pako = pakoJs var pako = pakoJs
var socket = { var socket = {
socket: null, // socket name socket: null, // socket name
id:null,
realTimeData: null, // 请求实时数据的参数 realTimeData: null, // 请求实时数据的参数
intervalObj: null, // 定时器的名字 intervalObj: null, // 定时器的名字
lastRealTimeData: null, // 上一次请求的产品 lastRealTimeData: null, // 上一次请求的产品
sendData(historyData, realTimeDatas, history) { sendData(historyData, realTimeDatas, history) {
// 储存历史数据 // 储存历史数据
this.historyData = historyData this.historyData = historyData
this.realTimeData = realTimeDatas this.realTimeData = realTimeDatas
// 如果上一次订阅过产品 // 如果上一次订阅过产品
if (this.lastRealTimeData) { if (this.lastRealTimeData) {
// 如果不是订阅历史产品 那么肯定就是切换周期咯 或者 切换产品
// 那么就取消订阅上一次的产品实时数据
if (!history) {
console.log('取消订阅' + this.lastRealTimeData)
this.sendWsRequest({
"unsub": this.lastRealTimeData,
"id": "id1"
})
}
// 请求这一次的历史 // 请求这一次的历史
this.historyData.id=this.id
this.sendWsRequest(this.historyData) this.sendWsRequest(this.historyData)
console.log(111111,realTimeDatas)
// 如果不是订阅历史产品 那么肯定就是切换周期咯 或者切换产品咯 // 如果不是订阅历史产品 那么肯定就是切换周期咯 或者切换产品咯
// 那么就订阅一下 这次产品的或者周期的 实时数据 // 那么就订阅一下 这次产品的或者周期的 实时数据
if (!history) { if (!history) {
//console.log('订阅新的' + realTimeDatas) console.log('订阅新的' + realTimeDatas)
//console.log(111111,realTimeDatas) this.sendWsRequest({
this.sendWsRequest({ "sub": realTimeDatas,
event: 'un_sub', "id": "id1"
type: 'kline', })
id: this.id,
channel:[this.lastRealTimeData],
})
this.lastRealTimeData = this.realTimeData
} }
} else { } else {
// 如果是第一次订阅,就是说刚进入交易所, // 如果是第一次订阅,就是说刚进入交易所,
// 先存起来这一次请求的产品 作为历史产品 // 先存起来这一次请求的产品 作为历史产品
this.lastRealTimeData = this.realTimeData this.lastRealTimeData = this.realTimeData
@ -50,9 +48,13 @@ var socket = {
} }
}, },
initWs() { initWs() {
this.socket = new WebSocket(constant.WSSURL) this.socket = new WebSocket('wss://api.huobi.pro/ws')
this.socket.onopen = () => { this.socket.onopen = () => {
this.sendWsRequest(this.historyData)
this.sendWsRequest({
"sub": this.historyData.req,
"id": "id1"
})
} }
this.socket.onmessage = resp => { this.socket.onmessage = resp => {
this.message(resp) this.message(resp)
@ -65,52 +67,46 @@ var socket = {
} }
}, },
error(err) { error(err) {
//console.log(err, 'depth-socket::error') console.log(err, 'depth-socket::error')
}, },
close() { close() {
// 如果websocket关闭的话,就从新打开一下。 // 如果websocket关闭的话,就从新打开一下。
this.initWs() this.initWs()
//console.log('depth-socket::close') console.log('depth-socket::close')
}, },
message(resp) { message(resp) {
resp=JSON.parse(resp.data) //console.log(resp)
if (resp.channel === 'conn') { let this_ = this
this.id = resp.data let reader = new FileReader()
reader.onload = function(e) {
this.historyData.id=this.id // 对数据进行解压
this.sendWsRequest(this.historyData) let msg = JSON.parse(pako.ungzip(reader.result, {
to: 'string'
}))
}else { // console.log(msg)
if(resp.event === 'req'){ // 如果是实时数据触发Event('realTime') 喂数据
if (msg.tick) {
//Event.emit('data', resp.data) Event.emit('realTime', msg.tick)
if (resp.data && Array.isArray(resp.data)) { }
Event.emit('data', resp.data)
} //响应服务器,避免断开连接
this.sendWsRequest({ if (msg.ping) {
event: 'un_sub', this_.socket.send(JSON.stringify({
type: 'kline', pong: msg.ping
id: this.id, }));
channel:[this.lastRealTimeData], this_.hasCheck = true
}) }
this.sendWsRequest({
event: 'sub', this_.lastRealTimeData = this_.realTimeData
type: 'kline', // 如果是历史数据触发Event('data') 绘制数据
id: this.id, if (msg.data && Array.isArray(msg.data)) {
channel:[this.lastRealTimeData], console.log(msg.data)
}) Event.emit('data', msg.data)
}else{ }
}
Event.emit('realTime', resp.data) // //将返回的数据解析为字符串格式
reader.readAsArrayBuffer(resp.data);
}
}
}, },
checkSendMessage(options) { checkSendMessage(options) {
// 这里处理websocket 连接不上的问题 // 这里处理websocket 连接不上的问题
@ -126,7 +122,7 @@ var socket = {
} }
if (i >= checkTimes) { if (i >= checkTimes) {
clearInterval(this.intervalObj) clearInterval(this.intervalObj)
//console.log('send post_data_str timeout.') console.log('send post_data_str timeout.')
} }
}, 500) }, 500)
}, },
@ -139,13 +135,13 @@ var socket = {
this.socket.send(JSON.stringify(options)) this.socket.send(JSON.stringify(options))
break break
case 2: case 2:
//console.log('ws关闭状态') console.log('ws关闭状态')
break break
case 3: case 3:
this.initWs() this.initWs()
break break
default: default:
//console.log('ws未知错误') console.log('ws未知错误')
} }
} }
} }

296
components/kline/tradingView/websocket1.js → components/kline/tradingView/websocket2.js

@ -1,149 +1,153 @@
import { import
Event constant
} from './event.js' from '@/utils/constant.js'
import {
import pakoJs from './pako.js' Event
} from './event.js'
var pako = pakoJs import pakoJs from './pako.js'
var socket = {
socket: null, // socket name var pako = pakoJs
realTimeData: null, // 请求实时数据的参数 var socket = {
intervalObj: null, // 定时器的名字 socket: null, // socket name
lastRealTimeData: null, // 上一次请求的产品 id:null,
sendData(historyData, realTimeDatas, history) { realTimeData: null, // 请求实时数据的参数
// 储存历史数据 intervalObj: null, // 定时器的名字
this.historyData = historyData lastRealTimeData: null, // 上一次请求的产品
this.realTimeData = realTimeDatas sendData(historyData, realTimeDatas, history) {
// 如果上一次订阅过产品 // 储存历史数据
if (this.lastRealTimeData) { this.historyData = historyData
// 如果不是订阅历史产品 那么肯定就是切换周期咯 或者 切换产品
// 那么就取消订阅上一次的产品实时数据 this.realTimeData = realTimeDatas
if (!history) { // 如果上一次订阅过产品
console.log('取消订阅' + this.lastRealTimeData) if (this.lastRealTimeData) {
this.sendWsRequest({
"unsub": this.lastRealTimeData,
"id": "id1" // 请求这一次的历史
}) this.historyData.id=this.id
}
// 请求这一次的历史
this.sendWsRequest(this.historyData) this.sendWsRequest(this.historyData)
console.log(111111,realTimeDatas)
// 如果不是订阅历史产品 那么肯定就是切换周期咯 或者切换产品咯 // 如果不是订阅历史产品 那么肯定就是切换周期咯 或者切换产品咯
// 那么就订阅一下 这次产品的或者周期的 实时数据 // 那么就订阅一下 这次产品的或者周期的 实时数据
if (!history) { if (!history) {
console.log('订阅新的' + realTimeDatas) //console.log('订阅新的' + realTimeDatas)
this.sendWsRequest({ //console.log(111111,realTimeDatas)
"sub": realTimeDatas, this.sendWsRequest({
"id": "id1" event: 'un_sub',
}) type: 'kline',
} id: this.id,
} else { channel:[this.lastRealTimeData],
// 如果是第一次订阅,就是说刚进入交易所, })
// 先存起来这一次请求的产品 作为历史产品 this.lastRealTimeData = this.realTimeData
this.lastRealTimeData = this.realTimeData }
// 然后 初始化一下websocket } else {
this.initWs()
} // 如果是第一次订阅,就是说刚进入交易所,
}, // 先存起来这一次请求的产品 作为历史产品
initWs() { this.lastRealTimeData = this.realTimeData
this.socket = new WebSocket('wss://api.huobi.pro/ws') // 然后 初始化一下websocket
this.socket.onopen = () => { this.initWs()
this.sendWsRequest(this.historyData) }
this.sendWsRequest({ },
"sub": this.historyData.req, initWs() {
"id": "id1" this.socket = new WebSocket(constant.WSSURL)
}) this.socket.onopen = () => {
}
this.socket.onmessage = resp => { }
this.message(resp) this.socket.onmessage = resp => {
} this.message(resp)
this.socket.onclose = () => { }
this.close() this.socket.onclose = () => {
} this.close()
this.socket.onerror = err => { }
this.error(err) this.socket.onerror = err => {
} this.error(err)
}, }
error(err) { },
console.log(err, 'depth-socket::error') error(err) {
}, //console.log(err, 'depth-socket::error')
close() { },
// 如果websocket关闭的话,就从新打开一下。 close() {
this.initWs() // 如果websocket关闭的话,就从新打开一下。
console.log('depth-socket::close') this.initWs()
}, //console.log('depth-socket::close')
},
message(resp) { message(resp) {
//console.log(resp) resp=JSON.parse(resp.data)
let this_ = this if (resp.channel === 'conn') {
let reader = new FileReader() this.id = resp.data
reader.onload = function(e) {
// 对数据进行解压 this.historyData.id=this.id
let msg = JSON.parse(pako.ungzip(reader.result, { this.sendWsRequest(this.historyData)
to: 'string'
}))
// console.log(msg) }else {
// 如果是实时数据触发Event('realTime') 喂数据 if(resp.event === 'req'){
if (msg.tick) {
Event.emit('realTime', msg.tick) //Event.emit('data', resp.data)
} if (resp.data && Array.isArray(resp.data)) {
Event.emit('data', resp.data)
//响应服务器,避免断开连接 }
if (msg.ping) { this.sendWsRequest({
this_.socket.send(JSON.stringify({ event: 'un_sub',
pong: msg.ping type: 'kline',
})); id: this.id,
this_.hasCheck = true channel:[this.lastRealTimeData],
} })
this.sendWsRequest({
this_.lastRealTimeData = this_.realTimeData event: 'sub',
// 如果是历史数据触发Event('data') 绘制数据 type: 'kline',
if (msg.data && Array.isArray(msg.data)) { id: this.id,
console.log(msg.data) channel:[this.lastRealTimeData],
Event.emit('data', msg.data) })
} }else{
}
// //将返回的数据解析为字符串格式 Event.emit('realTime', resp.data)
reader.readAsArrayBuffer(resp.data);
}, }
checkSendMessage(options) {
// 这里处理websocket 连接不上的问题
var checkTimes = 10 }
var i = 0
this.intervalObj = setInterval(() => {
i += 1 },
if (this.socket.readyState === 1) { checkSendMessage(options) {
// ... // 这里处理websocket 连接不上的问题
this.socket.send(options) var checkTimes = 10
clearInterval(this.intervalObj) var i = 0
return this.intervalObj = setInterval(() => {
} i += 1
if (i >= checkTimes) { if (this.socket.readyState === 1) {
clearInterval(this.intervalObj) // ...
console.log('send post_data_str timeout.') this.socket.send(options)
} clearInterval(this.intervalObj)
}, 500) return
}, }
sendWsRequest(options) { if (i >= checkTimes) {
switch (this.socket.readyState) { clearInterval(this.intervalObj)
case 0: //console.log('send post_data_str timeout.')
this.checkSendMessage(JSON.stringify(options)) }
break }, 500)
case 1: },
this.socket.send(JSON.stringify(options)) sendWsRequest(options) {
break switch (this.socket.readyState) {
case 2: case 0:
console.log('ws关闭状态') this.checkSendMessage(JSON.stringify(options))
break break
case 3: case 1:
this.initWs() this.socket.send(JSON.stringify(options))
break break
default: case 2:
console.log('ws未知错误') //console.log('ws关闭状态')
} break
} case 3:
} this.initWs()
break
default:
//console.log('ws未知错误')
}
}
}
exports.socket = socket exports.socket = socket
Loading…
Cancel
Save