TradingView usage tips
create by db on 2020-9-2 13:30:46
Recently revised in 2020-12-28 09:52:10Idle time to have a tight mind, busy time to have leisure fun
directory
-
preface
-
The body of the
- Tradingview introduction
- Two, before use
- 3. Use Tradingview
-
conclusion
-
Reference documentation
preface
Returns the directory
Because the company is working on an exchange project, k-chart is needed in the page. After referring to several other similar websites, we decided to use TradingView, a professional stock exchange chart library. Based on some similar projects, plus the Tradingview documentation, the K line is finally made. Now arrange your notes to record what you have learned. Share with you for your reference.
The body of the
Tradingview introduction
Returns the directory
Tradingview is a price charting and analysis software offering free and paid options that was launched in September 2011 by a group of traders and software developers. Tradingview allows investors to view price charts for a variety of financial markets and asset classes, including stocks, currency pairs, bonds, futures, and cryptocurrencies. In addition, investors can check out a variety of trades, such as stock index futures, European and U.S. currency pairs, gold, crude oil, bitcoin and more.
TradingView can be said to be the world’s most professional website on the page K chart, those who provide K chart on the page, most of the use of TradingView technology, such as Huobi, Binance…
In short, this is a charting plug-in that strips away the UI Settings and does just that: Get data — data visualization — respond to user actions — Get data — data visualization –…
You can check out the online demo if you are interested
Two, before use
Returns the directory
1. Apply for the core chart library
The Tradingview chart library is open source and free. You can download the demo on GitHub.
The demo library supports multiple languages and frameworks (such as Vue/React/Angular, etc.). In fact, the demo can not be run directly because it lacks the key core library (Charting-library), which needs to be applied to the official website. You need to download a copy of the agreement, sign and stamp it, scan and upload it, and then fill in a bunch of forms (email address, company address, etc.). If there is no problem, it will reply to your email within a day or two, which is the Github link (authorized, otherwise 404 will be reported).
The application page is as follows:
After obtaining github license, you can download the core charting-library locally. NPM install http-server/ http-server -p 8080). I’m using VScode Live After running, you can see the demo effect as follows.
2. Description of chart library content
The downloaded icon library contents are as follows:
+/charting_library
+ /static
- charting_library.min.js
- charting_library.min.d.ts
- datafeed-api.d.ts
+ /datafeeds
+ /udf
- index.html
- mobile_black.html
- mobile_white.html
- test.html
Copy the code
Introduction to the document:
/charting\_library
Contains all chart library files./charting\_library/charting\_library.min.js
Contains the external chart library Widget interface. This file should not be modified./charting_library/charting_library.min.d.ts
Widget interfaces that contain TypeScript definitions/charting_library/datafeed-api.d.ts
Datafeed interface that contains TypeScript definitions./charting_library/datafeeds/udf/
Includes udF-Compatible Datafeed wrapper classes that implement the JS API for transferring data to the chart library via UDF. The Datafeed wrapper class in this example implements real-time simulation data for pulses. You are free to edit this file./charting\_library/static
Folders that store internal chart library resources are not used for other purposes./index.html for using the Charting Library widget
HTML examples of./test.html
Examples of use of custom functions for different chart libraries./mobile\*.html
Also an example of Widget customization.
3. Reference documents
Because the development documentation may not be very friendly, here is a list of their own reference documentation and some implementation of the demo
The document
- TradingView development documentation in Chinese = = > zlq4863947. Gitbook. IO/TradingView…
This is a very good document, the author is very careful, the document is also very detailed, but small white may look a little round.
The open source project
Since we use the Vue framework, most of the recommended open source projects are based on Vue, which can be downloaded directly from Github.
- Vue – tradingview | xushanpei = = > github.com/xushanpei/V…
A very basic project, Vue + TradingView to achieve exchange trading K line, K line is randomly created false data, there is online demo
- Vue – tradingview | webdatavisualdev = = > github.com/webdatavisu…
Vue 2 + Vuex + TypeScript + TradingView Component (Vue 2 + Vuex + TypeScript + TradingView Component
- Hangzhou su xiaoxiao tradingview – vue | = = > gitee.com/SuHangWeb/t…
It includes both mobile and PC
The same site
-
Fire money = = > futures. Huobi. FM/useful – cn/contr…
-
Currency Ann = = > www.binancezh.pro/cn/trade/BN…
3. Use Tradingview
Now that we have an overview of TradingView, we have run the demo. However, to use Tradingview in our project, we need to learn more than just demo. Now let’s start at the beginning.
1. Introduce charts
- First official warehouse (address) download code to the local, new
tradingview-test
Project and then will
Charting_library /_ folder/datafeeds /_ folder /Copy the code
Place the above two in the static folder under the root of the TradingView-test project
- An entry file in its root directory
index.html
To introduce the following two files,
<script type="text/javascript" src="./static/datafeeds/udf/dist/polyfills.js"></script>
<script type="text/javascript" src="./static/datafeeds/udf/dist/bundle.js"></script>
Copy the code
- In the corresponding component, for example
Exchange.vue
Import tradingView – the constructor widget here
import { widget } from '.. /.. /.. /static/charting_library/charting_library.min.js'
Copy the code
Now that the chart library we need to apply is ready to use, the next step is to configure the K-line graph.
2. Configure parameters
The parameter configuration of K-chart, including language, style, product information, data display mode, disabled functions on the panel, enabled functions, etc., can be configured by oneself. The documentation is also detailed. Its general configuration is as follows:
new TradingView.widget({
symbol: 'A'./ / product
interval: 'D'.// Time interval
timezone: 'America/New_York'.// The default time zone
container_id: 'tv_chart_container'.// Specify the DOM element ID to contain the widget.
locale: 'ru'./ / language
datafeed: new Datafeeds.UDFCompatibleDatafeed(
'https://demo_feed.tradingview.com'
), // Chart Settings can be customized. When you create an object that implements the interface, you simply pass it to the constructor of the chart library Widget.
})
Copy the code
3. Bind data.
The code in the demo uses the tradingView official UDF interface to get data, which has great limitations. If we need our own data, we need to follow the Tradingviewd format (pass parameters are {start time, end time, product ID}, return value is [{high, open, low, close, quantity, timestamp}]), implement their own interface.
However, if you have enough people on the back end of your team, it is perfectly possible to develop an interface to use using the UDF, so that the front-end code is much less (I haven’t tried this).
4. Chart events
Chart events, that is, create a Datafeed function. This is the focus of our custom use of TradingView, including life cycle/event triggers and so on.
It is recommended to read the JS Api in the document carefully. The content is cumbersome, but necessary. It defines the format of the data, the response to user actions, and how each parameter is passed to the diagram.
There are several key methods to master
-
onReady
-
resolveSymbol
-
getBars
-
subscribeBars
-
unsubscribeBars
Specific use is as follows:
// Create a k-line configuration
createFeed () {
let that = this
let Datafeed = {}
Datafeed.Container = function (updateFrequency) {
this._configuration = {
supports_search: false.supports_group_request: false.supported_resolutions: [// Supported periodic arrays
'1'.'5'.'15'.'60'.'120'.'1D'.'1W'].supports_marks: true.// to indicate whether your datafeed supports displaying flags on the K line.
supports_timescale_marks: true.// Indicate whether your datafeed supports timescale markers.
exchanges: ['myExchange1']// Array of exchange objects}}// onReady is called immediately after the chart Widget is initialized. This method sets the chart configuration supported by the chart library
Datafeed.Container.prototype.onReady = function (callback) {
let that = this
if (this._configuration) {
setTimeout(function () {
callback(that._configuration)
}, 0)}else {
this.on('configuration_ready'.function () {
callback(that._configuration)
})
}
}
// Commodity information is resolved by commodity name (SymbolInfo), where individual commodities can be configured
Datafeed.Container.prototype.resolveSymbol = function (symbolName, onSymbolResolvedCallback, onResolveErrorCallback) {
Promise.resolve().then(() = > {
onSymbolResolvedCallback({
name: that.projectDetail.productName ,
ticker: symbolName, // The unique identifier of this commodity in the commodity system
description: ' '.// Product description
session: '24x7'.// Commodity trading time
timezone: 'Asia/Shanghai'.// The exchange time zone for this commodity
pricescale: 100.// Price precision
minmov: 1.// Minimum fluctuation
minmov2: 0.type: 'bitcoin'.// Optional type of meter.
// 'exchange-traded': 'myExchange2',
// 'exchange-listed': productName,
has_intraday: true.// Displays whether the item has historical data within days (minutes)
intraday_multipliers: ['1'.'5'.'15'.'15'.'60'.'120'].// An array of days in minutes
has_weekly_and_monthly: true.// Displays whether the item has historical data in W and M
has_daily: true.// Displays whether the item has historical data in days
// has_empty_bars: true,
force_session_rebuild: true.// Whether k-pillars are filtered with current transactions
has_no_volume: false.// Indicates whether the commodity has volume data.
regular_session: '24x7'})})}// Get the chart data from our API source and pass it to TradingView.
Datafeed.Container.prototype.getBars = async function (
symbolInfo, // Commodity information object
resolution, // (string (cycle)
rangeStartDate, // Unix timestamp, the leftmost requested K line time
rangeEndDate, // Unix timestamp, the rightmost requested K line time
onDataCallback, // Historical data callback function. Each request should only be invoked once.
onErrorCallback, // Error callback function.
firstDataRequest // A Boolean value to identify whether the history of this commodity/cycle was first called.
) {
that.localresolution = resolution
if (firstDataRequest) {
let bars = await that.getChartData(resolution, rangeStartDate, rangeEndDate, firstDataRequest)
if (bars.length) {
onDataCallback(bars)
} else {
onDataCallback([], { noData: true })
// onErrorCallback([], { noData: true })}}else {
onDataCallback([], { noData: true })
// onErrorCallback([], { noData: true })}}// Subscribe to line K data. The chart library calls the onRealtimeCallback method to update the live data.
Datafeed.Container.prototype.subscribeBars = function (
symbolInfo, / / ObjectsymbolInfo object
resolution, // StringK line cycle
onRealtimeCallback, // Function passes our updated K line to this callback to update the chart
listenerGUID, // String The unique ID of this transaction pair and the resolution representing the subscription, generated by ticker+'_'+ cycle
onResetCacheNeededCallback // Function calls a callback to make the chart request historical k-line data again
) {
that.callbacks = []
that.callbacks.push(onRealtimeCallback)
that.updateBar(resolution, onRealtimeCallback)
// Change the linestyle
that.chart.activeChart().setChartType(1);
}
// Unsubscribe from K line data
Datafeed.Container.prototype.unsubscribeBars = function (listenerGUID) {}return new Datafeed.Container()
}
Copy the code
5. Working principle
After we know something about the chart event, we can know that the way the chart works is that we feed the data and the chart makes a visual presentation.
As for how we feed the data to the diagram, the plug-in itself has defined the external interface, and we need to provide an object datafeed with these interfaces. For example, the getBars method, which gets the transaction records, and the datafeed object we use to instantiate the chart, needs to be implemented, and the value returned must be what the chart plug-in expects.
So we need to implement these interfaces in the Datafeed and return the expected data, which the chart will show.
6, websocket
Ajax data acquisition In the case of a large number of users, real-time data polling will cause great pressure on the server, so websocket push is generally used to obtain data.
For Websocket, there is no official demo, but fortunately, there are bloggers who have implemented websocket demo, students who need to take a look at the tradingView and WebSocket combination of available cases
conclusion
Returns the directory
This is a nice plug-in for users, but not very friendly for front-end engineers. A lot of people have taken over this plugin with a lot of confusion, including me. However, I have gained a lot of knowledge by studying this plug-in, and I hope this article will help you.
reference
-
TradingView Chinese development document
-
TradingView JS API integration tutorial | Ellite – Jane books
-
Tradingview usage insight | jacoby_fire – CSDN
-
Introductory tradingview | Chen Qiwen – no
-
TradingView notes | line in tomato you – CSDN
-
Garden TradingView custom indicators | x_smile – blog
Postscript: Hello friends, if you think this article is good, remember to give a thumbs-up or star, your thumbs-up and star is my motivation to write more and richer articles!Making the address
Document agreement
dbThe document library 由 dbusingCreative Commons Attribution – Non-commercial Use – Same way Share 4.0 International LicenseGrant permission.
Based on thegithub.com/danygitgitOn the creation of works.
Use rights other than those authorized by this License agreement may be obtained fromCreativecommons.org/licenses/by…Obtained.