Python

Data Interface Basic Function Application (Apply to Trial Version and Official Version)

Brief Introduction

This script is an example of a common function of a data interface in a common scenario.

Sample Code

python
# -*- coding: utf-8 -*-

from iFinDPy import *
from datetime import datetime
import pandas as pd
import time as _time
import json
from threading import Thread,Lock,Semaphore
import requests

sem = Semaphore(5)  # This variable is used to control the maximum number of concurrency
dllock = Lock()  #This variable is used to control the lock of falling data to the local in the real-time market push

# Login function
def thslogindemo():
    # Enter the user's account and password
    thsLogin = THS_iFinDLogin("Data Interface _ Account", "Data Interface _ Password")
    print(thsLogin)
    if thsLogin != 0:
        print('Login failed')
    else:
        print('Login successfully')

def datepool_basicdata_demo():
    # Through the sector component function and basic data function of the data pool, extract the daily non-weighted closing price of all CSI 300 stocks on 2020-11-16
    data_hs300 = THS_DP('block', '2020-11-16;001005290', 'date:Y,thscode:Y,security_name:Y')
    if data_hs300.errorcode != 0:
        print('error:{}'.format(data_hs300.errmsg))
    else:
        seccode_hs300_list = data_hs300.data['THSCODE'].tolist()
        data_result = THS_BD(seccode_hs300_list, 'ths_close_price_stock', '2020-11-16,100')
        if data_result.errorcode != 0:
            print('error:{}'.format(data_result.errmsg))
        else:
            data_df = data_result.data
            print(data_df)

def datapool_realtime_demo():
    # Through the plate component function and real-time market function of the data pool, extract the latest price data of all the stocks of the SSE 50 and export it as a csv file
    today_str = datetime.today().strftime('%Y-%m-%d')
    print('today:{}'.format(today_str))
    data_sz50 = THS_DP('block', '{};001005260'.format(today_str), 'date:Y,thscode:Y,security_name:Y')
    if data_sz50.errorcode != 0:
        print('error:{}'.format(data_sz50.errmsg))
    else:
        seccode_sz50_list = data_sz50.data['THSCODE'].tolist()
        data_result = THS_RQ(seccode_sz50_list,'latest')
        if data_result.errorcode != 0:
            print('error:{}'.format(data_result.errmsg))
        else:
            data_df = data_result.data
            print(data_df)
            data_df.to_csv('realtimedata_{}.csv'.format(today_str))

def iwencai_demo():
    # Demonstrates how to call common data through natural language statements that do not consume traffic
    print('Output capital flow data')
    data_wencai_zjlx = THS_WC('Main capital flow', 'stock')
    if data_wencai_zjlx.errorcode != 0:
        print('error:{}'.format(data_wencai_zjlx.errmsg))
    else:
        print(data_wencai_zjlx.data)

    print('Output stock score data')
    data_wencai_xny = THS_WC('Equity Score', 'stock')
    if data_wencai_xny.errorcode != 0:
        print('error:{}'.format(data_wencai_xny.errmsg))
    else:
        print(data_wencai_xny.data)

def dlwork(tick_data):
    # This function is the task function of real-time market quotation subscription for new starting threads
    dllock.acquire()
    with open('dlwork.txt', 'a') as f:
        for stock_data in tick_data['tables']:
            if 'time' in stock_data:
                timestr = _time.strftime('%Y-%m-%d %H:%M:%S', _time.localtime(stock_data['time'][0]))
                print(timestr)
                f.write(timestr + str(stock_data) + '\n')
            else:
                pass
    dllock.release()

def work(codestr,lock,indilist):
    sem.acquire()
    stockdata = THS_HF(codestr, ';'.join(indilist),'','2020-08-11 09:15:00', '2020-08-11 15:30:00','format:json')
    if stockdata.errorcode != 0:
        print('error:{}'.format(stockdata.errmsg))
        sem.release()
    else:
        print(stockdata.data)
        lock.acquire()
        with open('test1.txt', 'a') as f:
            f.write(str(stockdata.data) + '\n')
        lock.release()
        sem.release()

def multiThread_demo():
    # This function is an example of how to use multi-threading to accelerate data extraction through a high-frequency sequence function. In this example, all A shares are divided into 100 groups and the maximum number of threads is extracted
    # Users can modify according to their own scenarios
    today_str = datetime.today().strftime('%Y-%m-%d')
    print('today:{}'.format(today_str))
    data_alla = THS_DP('block', '{};001005010'.format(today_str), 'date:Y,thscode:Y,security_name:Y')
    if data_alla.errorcode != 0:
        print('error:{}'.format(data_alla.errmsg))
    else:
        stock_list = data_alla.data['THSCODE'].tolist()

    indi_list = ['close', 'high', 'low', 'volume']
    lock = Lock()

    btime = datetime.now()
    l = []
    for eachlist in [stock_list[i:i + int(len(stock_list) / 10)] for i in
                     range(0, len(stock_list), int(len(stock_list) / 10))]:
        nowstr = ','.join(eachlist)
        p = Thread(target=work, args=(nowstr, lock, indi_list))
        l.append(p)

    for p in l:
        p.start()
    for p in l:
        p.join()
    etime = datetime.now()
    print(etime-btime)

pd.options.display.width = 320
pd.options.display.max_columns = None


def reportDownload():
    df = THS_ReportQuery('300033.SZ','beginrDate:2021-08-01;endrDate:2021-08-31;reportType:901','reportDate:Y,thscode:Y,secName:Y,ctime:Y,reportTitle:Y,pdfURL:Y,seq:Y').data
    print(df)
    for i in range(len(df)):
        pdfName = df.iloc[i,4]+str(df.iloc[i,6])+'.pdf'
        pdfURL = df.iloc[i,5]
        r = requests.get(pdfURL)
        with open(pdfName,'wb+') as f:
            f.write(r.content)


def main():
    # This script is an example of a common scenario for data interfaces. You can observe the effect by uncommenting the following example functions

    # Login function
    thslogindemo()
    # Through the sector component function and basic data function of the data pool, extract the daily non-weighted closing price of all CSI 300 stocks on 2020-11-16
    # datepool_basicdata_demo()
    # Through the plate component function and real-time market function of the data pool, extract the latest price data of all the stocks of the SSE 50 and export it as a csv file
    # datapool_realtime_demo()
    # Demonstrates how to call common data through natural language statements that do not consume traffic
    # iwencai_demo()
    # This function is an example of how to use multi-threading to accelerate data extraction through a high-frequency sequence function. In this example, all A shares are divided into 100 groups and the maximum number of threads is extracted
    # multiThread_demo()
    # This function demonstrates how to use the announcement function to extract announcements that meet the conditions, and download its pdf
    # reportDownload()

if __name__ == '__main__':
    main()

Application Example of Time-point Data (Apply to Trial Version and Official Version)

Brief Introduction

Demonstrate how to extract the time point data of financial indicators, how to use auxiliary functions to better process the application scenarios of time point data, and how to extract data according to custom date series in date series.

Sample Code

python
from iFinDPy import *
import pandas as pd

pd.options.display.max_columns = None
pd.set_option('display.float_format', lambda x: '%.4f' % x)


loginResult = THS_iFinDLogin('zhanghao','mima')
print(loginResult)

def historyReportDateTest():
    # Extract the financial report data of the stock on different dates to avoid backtesting the financial model from being interfered by future data
    dateList = THS_DateQuery('SSE','dateType:0,period:D,dateFormat:0','2019-10-20','2019-10-30')['tables']['time']
    for date in dateList:
        result = THS_BD('300029.SZ', 'ths_np_atoopc_pit_stock', '{},20190930,1'.format(date))
        print(date,result.data)

    # Use date sequence functions to achieve the same effect
    result = THS_DS('300029.SZ', 'ths_np_atoopc_pit_stock', '20190930,1', 'Fill:Blank', '2019-10-20', '2019-10-30')
    print(result.data)

def reportChange():
    # Use the financial report change date indicator and the custom date sequence function to extract the financial report change record of the stock
    result = THS_BD('000892.SZ', 'ths_report_changedate_pit_stock', '2018-12-31,2020-11-25,604,1,20171231')
    changeDateList = result.data.iloc[0]['ths_report_changedate_pit_stock']
    print(changeDateList)

    changeRecord = THS_DS('000892.SZ', 'ths_total_assets_pit_stock', '20181231,1', 'date_sequence:{}'.format(changeDateList), '', '').data
    print(changeRecord)

def calepsttm(x):
    curDate = x['time']
    reportDateNow = x['ths_history_reportdate_pit_stock']
    year = int(reportDateNow[:4])
    datestr = reportDateNow[-4:]
    reportDateLast12 = str(year-1)+'1231'
    reportDateLastEnd = str(year-1)+datestr
    if datestr == '1231':
        np_ttm = THS_BD('300029.SZ','ths_np_atoopc_pit_stock','{},{},1'.format(curDate,reportDateNow)).data.iloc[0]['ths_np_atoopc_pit_stock']
    else:
        npThisYear = THS_BD('300029.SZ','ths_np_atoopc_pit_stock','{},{},1'.format(curDate,reportDateNow)).data.iloc[0]['ths_np_atoopc_pit_stock']
        npLastYear1 = THS_BD('300029.SZ', 'ths_np_atoopc_pit_stock', '{},{},1'.format(curDate, reportDateLast12)).data.iloc[0]['ths_np_atoopc_pit_stock']
        npLastYear2 = THS_BD('300029.SZ', 'ths_np_atoopc_pit_stock', '{},{},1'.format(curDate, reportDateLastEnd)).data.iloc[0]['ths_np_atoopc_pit_stock']
        np_ttm = npThisYear + npLastYear1 - npLastYear2
    shareNum = THS_BD('300029.SZ','ths_total_shares_stock',curDate).data.iloc[0]['ths_total_shares_stock']
    epsttm = np_ttm/shareNum
    return epsttm


def epsttm():
    # Extraction of the current ttm
    result_before = THS_DS('300029.SZ', 'ths_eps_ttm_stock', '101', 'Fill:Blank', '2019-10-20', '2019-10-30')
    if result_before.errorcode != 0:
        print('error {} happen'.format(result_before.errmsg))
    else:
        print(result_before.data)
    # Calculate ttm by yourself using the new time-point data
    result_after = THS_DS('300029.SZ','ths_history_reportdate_pit_stock','608,1,0@104,2','Fill:Blank','2019-10-20','2019-10-30')
    if result_after.errorcode != 0:
        print('error {} happen'.format(result_after.errmsg))
    else:
        result_df = result_after.data
        result_df['epsttm'] = result_df.apply(calepsttm,axis=1)
        print(result_df)

def exceed100test():
    dateList = THS_DateQuery('SSE', 'dateType:0,period:D,dateFormat:0', '2018-10-20', '2019-10-30')['tables']['time']
    changeRecord = THS_DS('000892.SZ', 'ths_np_atoopc_pit_stock', '20171231,1',
                          'date_sequence:{}'.format(','.join(dateList)), '', '')
    print(changeRecord)

def duplicatedatetest():
    # Custom sequence functions support different date formats
    changeRecord = THS_DS('000892.SZ', 'ths_np_atoopc_pit_stock', '20171231,1',
                          'date_sequence:2018-05-01,20200601,2020-08-01', '', '')
    print(changeRecord)

def main():
    historyReportDateTest()
    # reportChange()
    # epsttm()
    # exceed100test()
    # duplicatedatetest()

if __name__ == '__main__':
    main()

Case Study of Index Performance after Sharp Drop

Brief Introduction

Analyze the performance of the stock market one month, one quarter and one year after the 5% plunge.

Sample Code

python
import pandas as pd
from datetime import datetime
from iFinDPy import *


thsLogin = THS_iFinDLogin("IFind account","IFind account password")

index_list = ['000001.SH','399001.SZ','399006.SZ']
result = pd.DataFrame()
today =datetime.today().strftime('%Y-%m-%d')

for index in index_list: 
    data_js = THS_DateSerial(index,'ths_pre_close_index;ths_open_price_index;ths_close_price_index;ths_high_price_index',';;;',\
                             'Days:Tradedays,Fill:Previous,Interval:D,block:history','2000-01-01',today,True)
    data_df = THS_Trans2DataFrame(data_js)
    data_df['close_chg'] = data_df['ths_close_price_index'] / data_df['ths_pre_close_index'] * 100 - 100
    result_pd = data_df[(data_df['close_chg'] < -5)]
    date_list = result_pd['time'].tolist()
    print('{}Closed at -5% of the trading day with{}'.format(index,str(date_list)))
    for date in date_list:
        date_after_1month = THS_DateOffset('SSE','dateType:1,period:D,offset:30,dateFormat:0,output:singledate',date)['tables']['time'][0]
        date_after_3month = THS_DateOffset('SSE','dateType:1,period:D,offset:90,dateFormat:0,output:singledate',date)['tables']['time'][0]
        date_after_1year = THS_DateOffset('SSE','dateType:1,period:D,offset:365,dateFormat:0,output:singledate',date)['tables']['time'][0]
        if date > (datetime.today() + timedelta(days=-365)).strftime('%Y-%m-%d'):
            continue
        index_close_date = THS_BasicData(index,'ths_close_price_index',date)['tables'][0]['table']['ths_close_price_index'][0]
        index_close_date_after_1month = THS_BasicData(index,'ths_close_price_index',date_after_1month)['tables'][0]['table']['ths_close_price_index'][0]
        index_close_date_after_3month = THS_BasicData(index,'ths_close_price_index',date_after_3month)['tables'][0]['table']['ths_close_price_index'][0]
        index_close_date_after_1year = THS_BasicData(index,'ths_close_price_index',date_after_1year)['tables'][0]['table']['ths_close_price_index'][0]
        result = result.append(pd.DataFrame([index,date,index_close_date,index_close_date_after_1month,index_close_date_after_3month,index_close_date_after_1year]).T)
result.columns = ['Index Code',' Crash Day ',' Crash Day Points', 'One Month Later Points', 'Three Months Later Points', 'One Year Later Points']
result = result.set_index('Index Code')
result['Changes after a month of tumbling'] = result['Points after a month']/result['Crash day points'] *100 -100
result['Changes after three months of tumbling'] = result['Points after three months']/result[Crash day points'] *100 -100
result['Changes after a year of tumbling'] = result['Points after one year']/result['大跌日点数'] *100 -100
result

HTTP Interface Application Case (python environment)

Brief Introduction

Demonstrate extracting function data using HTTP interfaces in Python environments.

Sample Code

python
import requests
import json
import time
import pandas as pd

# Cancel the panda scientific notation and keep 4 valid decimal places.
pd.set_option('float_format', lambda x: '%.2f' % x)
# Set Chinese alignment, value isometric alignment.
pd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)
pd.set_option('display.max_columns', 20)
pd.set_option('display.width', 500)

# Token accessToken And permission verification mechanism
getAccessTokenUrl = 'https://quantapi.51ifind.com/api/v1/get_access_token'
# To obtain refresh _ token, you need to download the Windows version interface package to decompress, and open the super command-tools-refresh _ token query
refreshtoken = 'Fill in refresh _ token here'
getAccessTokenHeader = {"Content- Type": "application/json", "refresh_token": refreshtoken}
getAccessTokenResponse = requests.post(url=getAccessTokenUrl, headers=getAccessTokenHeader)
accessToken = json.loads(getAccessTokenResponse.content)['data']['access_token']
print(accessToken)

thsHeaders = {"Content-Type": "application/json", "access_token": accessToken}


# High frequency sequence: get minute data
def high_frequency():
    thsUrl = 'https://quantapi.51ifind.com/api/v1/high_frequency'
    thsPara = {"codes":
                   "000001.SZ",
               "indicators":
                   "open,high,low,close,volume,amount,changeRatio",
               "starttime":
                   "2022-07-05 09:15:00",
               "endtime":
                   "2022-07-05 15:15:00"}
    thsResponse = requests.post(url=thsUrl, json=thsPara, headers=thsHeaders)
    print(thsResponse.content)


# Real-time market data: loop to get the latest market data
def real_time():
    thsUrl = 'https://quantapi.51ifind.com/api/v1/real_time_quotation'
    thsPara = {"codes": "300033.SZ", "indicators": "latest"}
    while True:
        thsResponse = requests.post(url=thsUrl, json=thsPara, headers=thsHeaders)
        data = json.loads(thsResponse.content)
        result = pd.json_normalize(data['tables'])
        result = result.drop(columns=['pricetype'])
        result = result.apply(lambda x: x.explode().astype(str).groupby(level=0).agg(", ".join))
        print(result)
        # do your thing here
        time.sleep(3)
        pass


# Historical Quotes: Obtain historical daily frequency market data
def history_quotes():
    thsUrl = 'https://quantapi.51ifind.com/api/v1/cmd_history_quotation'
    thsPara = {"codes":
                   "000001.SZ,600000.SH",
               "indicators":
                   "open,high,low,close",
               "startdate":
                   "2021-07-05",
               "enddate":
                   "2022-07-05",
               "functionpara":
                   {"Fill": "Blank"}
               }
    thsResponse = requests.post(url=thsUrl, json=thsPara, headers=thsHeaders)
    print(thsResponse.content)


# Basic data: obtain basic securities information, financial indicators, profit forecasts, daily market data and other data
def basic_data():
    thsUrl = 'https://quantapi.51ifind.com/api/v1/basic_data_service'
    thsPara = {"codes":
                   "300033.SZ,600000.SH",
               "indipara":
                   [
                       {
                           "indicator":
                               "ths_regular_report_actual_dd_stock",
                           "indiparams":
                               ["104"]
                       },
                       {
                           "indicator":
                               "ths_total_shares_stock",
                           "indiparams":
                               ["20220705"]
                       }
                   ]
               }
    thsResponse = requests.post(url=thsUrl, json=thsPara, headers=thsHeaders)
    print(thsResponse.content)


# Date series: the same as the basic data indicator, multi-day data can be obtained at the same time
def date_serial():
    thsUrl = 'https://quantapi.51ifind.com/api/v1/date_sequence'
    thsPara = {"codes":
                   "000001.SZ,600000.SH",
               "startdate":
                   "20220605",
               "enddate":
                   "20220705",
               "functionpara":
                   {"Fill": "Blank"},
               "indipara":
                   [
                       {
                           "indicator":
                               "ths_close_price_stock",
                           "indiparams":
                               ["", "100", ""]
                       },
                       {"indicator":
                            "ths_total_shares_stock",
                        "indiparams":
                            [""]
                        }
                   ]
               }
    thsResponse = requests.post(url=thsUrl, json=thsPara, headers=thsHeaders)
    data = json.loads(thsResponse.content)
    result = Trans2df(data)
    print(result)


# Json structure to dataframe
def Trans2df(data):
    df = pd.json_normalize(data['tables'])
    df2 = df.set_index(['thscode'])

    unnested_lst = []
    for col in df2.columns:
        unnested_lst.append(df2[col].apply(pd.Series).stack())

    result = pd.concat(unnested_lst, axis=1, keys=df2.columns)
    # result = result.reset_index(drop=True)
    # Set up a secondary index
    result = result.reset_index()
    result = result.set_index(['thscode', 'time'])
    # Formatting, row-to-column
    result = result.drop(columns=['level_1'])
    result = result.reset_index()
    return (result)


# Special reports, examples extract all A-share codes, and use the super command tool to view more report data
def data_pool():
    thsUrl = 'https://quantapi.51ifind.com/api/v1/data_pool'
    thsPara = {
        "reportname": "p03425",
        "functionpara": {
            "date": "20220706",
            "blockname": "001005010",
            "iv_type": "allcontract"
        },
        "outputpara": "p03291_f001,p03291_f002,p03291_f003,p03291_f004"
    }
    thsResponse = requests.post(url=thsUrl, json=thsPara, headers=thsHeaders)
    print(thsResponse.content)


# EDB
def edb():
    thsUrl = 'https://quantapi.51ifind.com/api/v1/edb_service'
    thsPara = {"indicators":
                   "G009035746",
               "startdate":
                   "2022-04-01",
               "enddate":
                   "2022-05-01"}
    thsResponse = requests.post(url=thsUrl, json=thsPara, headers=thsHeaders)
    print(thsResponse.content)


# Intraday Snapshot: tick data
def snap_shot():
    thsUrl = 'https://quantapi.51ifind.com/api/v1/snap_shot'
    thsPara = {
        "codes": "000001.SZ",
        "indicators": "open,high,low,latest,bid1,ask1,bidSize1,askSize1",
        "starttime": "2022-07-06 09:15:00",
        "endtime": "2022-07-06 15:15:00"
    }
    thsResponse = requests.post(url=thsUrl, json=thsPara, headers=thsHeaders)
    print(thsResponse.content)


# Announcement function
def report_query():
    thsUrl = 'https://quantapi.51ifind.com/api/v1/report_query'
    thsPara = {
        "codes": "000001.SZ,600000.SH",
        "functionpara": {
            "reportType": "901"
        },
        "beginrDate": "2021-01-01",
        "endrDate": "2022-07-06",
        "outputpara": "reportDate:Y,thscode:Y,secName:Y,ctime:Y,reportTitle:Y,pdfURL:Y,seq:Y"
    }
    thsResponse = requests.post(url=thsUrl, json=thsPara, headers=thsHeaders)
    print(thsResponse.content)


# Intelligent stock selection
def WCQuery():
    thsUrl = 'https://quantapi.51ifind.com/api/v1/smart_stock_picking'
    thsPara = {
        "searchstring": "Quote change",
        "searchtype": "stock"
    }
    thsResponse = requests.post(url=thsUrl, json=thsPara, headers=thsHeaders)
    print(thsResponse.content)


# Date query function, date offset function: query trading days according to the exchange
def date_offset():
    thsUrl = 'https://quantapi.51ifind.com/api/v1/get_trade_dates'
    thsPara = {"marketcode": "212001",
               "functionpara":
                   {"dateType": "0",
                    "period": "D",
                    "offset": "-10",
                    "dateFormat": "0",
                    "output": "sequencedate"},
               "startdate":
                   "2022-07-05"}
    thsResponse = requests.post(url=thsUrl, json=thsPara, headers=thsHeaders)
    print(thsResponse.content)


def main():
    # Real-time Quotes
    real_time()
    # fundamental data
    # basic_data()
    # date sequence
    # date_serial()
    # thematic report
    # data_pool()
    # historical Quotes
    # history_quotes()
    # high frequency sequence
    # high_frequency()
    # EDB
    # edb()
    # intraday snapshot
    # snap_shot()
    # announcement function
    # report_query()
    # intelligent stock selection
    # WCQuery()
    # date query function
    # date_query()
    # date offset function
    # date_offset()


if __name__ == '__main__':
    main()

Matlab

Matlab Interface Function Use Cases

Brief Introduction

Demonstrate the use of Matlab interface functions, as well as the conversion of JSON format to table format.

Sample Code

matlab
%%
%Create on Fri Jan 13
%Authorized by @THS
%This is a sample which shows how to operate the commonds.
%%,
%Users please change to their own account and password when using
thsLogin = THS_iFinDLogin('account','password');
if(thsLogin == 0 || thsLogin == -201)
    %The high-frequency sequence function format is 		THS_HighFrequenceSequence('thsCodes','indicators','params','startTime','endTime')
    % thsCodes cannot be null and supports multiple inputs. When there are multiple thsCodes, they are separated by English 	half-width commas, such as thsCode 1, thsCode 2, thsCode 3
    % indicators cannot be null and support multiple inputs. When there are multiple indicators, they are separated by English 	semi-semicolons, such as indicator 1; indicator 2; indicator 3
    % params cannot be empty and supports multiple inputs. When using default parameters, you can use 'default'. When the user 	only sets one of the indicators and the other parameters remain default, only the set parameters need to be entered, such as' 	Interval: 5'
    %The date input format for startDate is YYYY-MM-DD HH: MM: SS
    %The date input format of endDate is YYYY-MM-DD HH: MM: SS
    %THS_HighFrequenceSequence('thsCode1,thsCode2,thsCode3','indicator1;indicator2;indicator3','param1,param2,param3','startTime','endTime')
    thsDataHighFrequenceSequence = THS_HighFrequenceSequence('300033.SZ','open;high;low;close;volume;amt','CPS:0,MaxPoints:50000,Fill:Previous,Interval:1','2016-12-12 09:30:00','2016-12-12 15:00:00');
    highFrequenceSequence = THS_Trans2Table(thsDataHighFrequenceSequence)
	
    %The format of the real-time market function is THS _ RealtimeQuotes (' thsCodes', 'indicators', 'params ')
    %ThsCodes cannot be null and supports multiple inputs. When there are multiple thsCodes, they are separated by English half-width commas, such as thsCode 1, thsCode 2, thsCode 3
    %Indicators cannot be null and support multiple inputs. When there are multiple indicators, they are separated by English semi-semicolons, such as indicator 1; indicator 2; indicator 3
    %Params cannot be empty
    %THS_RealtimeQuotes('thsCode1,thsCode2,thsCode3','indicator1;indicator2;indicator3','param1,param2,param3')
    thsDataRealtimeQuotes = THS_RealtimeQuotes('600000.SH,300033.SZ','open;high;low;new','pricetype:1');
    realtimeQuotes = THS_Trans2Table(thsDataRealtimeQuotes)
	
    %The historical market function format is THS _ HistoryQuotes (' thsCodes', 'indicators', 'params', 'startDate', 'endDate ')
    %ThsCodes cannot be null and supports multiple inputs. When there are multiple thsCodes, they are separated by English half-	width commas, such as thsCode 1, thsCode 2, thsCode 3
    %Indicators cannot be null and support multiple inputs. When there are multiple indicators, they are separated by English 		semi-semicolons, such as indicator 1; indicator 2; indicator 3
    %Params cannot be null and supports multiple inputs. When using default parameters, you can use 'default' to indicate that 		when the user only sets one of the indicators and the other parameters remain default, only the set parameters need to be   	entered, such as' period: W'
    %The date input format for startDate is YYYY-MM-DD
    %The date input format of endDate is YYYY-MM-DD
    %THS_HistoryQuotes('thsCode1,thsCode2,thsCode3','indicator1;indicator2;indicator3','param1,param2,param3','startDate','endDate')
    thsDataHistoryQuotes  = THS_HistoryQuotes('300033.SZ','open;high;low;close','period:D,pricetype:1,rptcategory:0,fqdate:1900-01-01,hb:YSHB','2016-03-01','2016-04-01');
    historyQuotes = THS_Trans2Table(thsDataHistoryQuotes)
	
    % Basic Data THS _ BasicData (' thsCodes', 'function', 'params '); supports multi-security single indicator input
	% thsCodes cannot be empty and supports multiple inputs. When there are multiple thsCodes, they are separated by English 		half-width commas, such as thsCode 1, thsCode 2, thsCode 3
	% function cannot be empty, and currently only supports a single function, the current function name can be viewed in [iFinD 	Terminal-Tools-Data Interface-Indicator Function Query Tool]
	% params can be empty or there can be multiple. When there are multiple params, they are separated by English half-width 		commas, such as param1, param2, param3
	%THS_BasicData('thsCode1,thsCode2,thsCode3','function','param1,param2,param3')
	thsDataBasicData = THS_BasicData('300033.SZ', 'ths_sfssrq_stock', '')
	basicData = THS_Trans2Table(thsDataBasicData)
    
    % Date series function format is THS _ DateSerial (' thsCodes', 'indicators', 'params', 'startDate', 'endDate ')
	% thsCodes cannot be empty and supports multiple inputs. When there are multiple thsCodes, they are separated by English 		half-width commas, such as thsCode 1, thsCode 2, thsCode 3
	% indicators cannot be null and support multiple inputs. When there are multiple indicators, they are separated by English 		semi-semicolons, such as indicator 1; indicator 2; indicator 3
	% params cannot be empty and supports multiple inputs. When using default parameters, you can use 'default'. When the user 		only sets one of the indicators and the other parameters remain default, only the set parameters need to be entered, such 		as' Interval: M'
	The date input format for% startDate is YYYY-MM-DD
	The date input format of% endDate is YYYY-MM-DD
	The format of the% date sequence function is THS _ DateSerial (' thsCode1, thsCode2, thsCode3 ',' indicator1; indicator2; 		indicator3 ',' param1, param2, param3 ',' startDate ',' endDate ')
	thsDataDateSerial = 							THS_DateSerial('300033.SZ','gz_pe','CPS:0,Days:Tradedays,Fill:Previous,Interval:D,Currency:ORIGINAL','2016-12-13','2017-01-13');
	dateSerial = THS_Trans2Table(thsDataDateSerial)
	
	%日内快照函数格式为THS_Snapshot('thsCodes','indicators','params','startTime','endTime')
    %thsCodes不可以为空,且支持多个输入,当有多个thsCodes则用英文半角逗号分隔,如thsCode1,thsCode2,thsCode3
    %indicators不可以为空,且支持多个输入,当有多个indicators则用英文半角分号分隔,如indicator1;indicator2;indicator3
    %params不可以为空,且当前只有一个参数,即dataType:Original
    %startDate的日期输入格式为YYYY-MM-DD HH:MM:SS
    %endDate的日期输入格式为YYYY-MM-DD HH:MM:SS
    %THS_HighFrequenceSequence('thsCode1,thsCode2,thsCode3','indicator1;indicator2;indicator3','param1,param2,param3','startTime','endTime')
	thsDataSnapShot = 											THS_Snapshot('300033.SZ,600000.SH','tradeDate;tradeTime;preClose;open;high;low;latest','dataType:Original','2018-06-13 09:30:00','2018-06-13 09:45:00')
	snapShot = THS_Trans2Table(thsDataSnapShot)
	
    % Data pool function format is THS _ DataPool (' modelName ',' inputParams', 'outputParams ')
	% modelName cannot be null and can only be entered one at a time
	% inputParams are separated by English semicolons, such as inputParam 1; inputParam 2; inputParam 3
	% outputParams is assigned with an English half-width colon, separated by an English half-width comma, Y means the field is 	output, N means the field is not output, if not written, the default is Y, such as outputParam 1: Y, outputParam 2: Y, 			outputParam 3: N
	%THS_DataPool('modelName','inputParam1;inputParam2;inputParam3','outputParam1,outputParam2,outputParams3')
	% [001005260] is the sector ID, the current sector ID can be viewed in [iFinD terminal-tools-data interface-sector ID query 	tool]
	thsDataDataPool = THS_DataPool('block','2016-12-19;001005260','date:Y,security_name:Y,thscode:Y');
	dataPool = THS_Trans2Table(thsDataDataPool)
	
    % EDB data request function format is THS _ EDBQuery (' indicatorIDs', 'startDate', 'endDate ')
	% indicatorIDs cannot be empty and supports multiple ID inputs. The indicator ID can be viewed in the indicator ID query 		tool in [iFinD Terminal-Tools-Data Interface]
	The date input format for% startDate is YYYY-MM-DD
	The date input format of% endDate is YYYY-MM-DD
	%thsEDBDataQuery = THS_EDBDataQuery("M001620326", "2000-01-01", "2016-01-01");
    
    % data usage query function, which is used for users to query the data usage of their own account. The market data is 150 		million pieces/week, the basic data is 5 million pieces/week, and the EDB data is 500 pieces/week. Data obtained through high-		frequency sequence functions, historical market functions and real-time market functions
	% is collectively referred to as market data; data obtained through basic data functions, date sequence functions and data 		pool functions are collectively referred to as basic data; data obtained through EDB data request functions are collectively 	referred to as EDB data.
	thsDataStatistics = THS_DataStatistics();
    
    % error information query function, query the errorcode after the function is executed to understand the error information
	The value of% value cannot be null, and the value of value must be an enumerated error value
	thsGetErrorInfo = THS_GetErrorInfo(0);
    
    % Transaction Date/Calendar Date Query Function
	The format of the% date query function is THS _ DateQuery (' exchange ',' dateType: value, period: value, dateFormat: value 	',' startDate ',' endDate ')
	% exchange cannot be empty
	The value of% dateType, period, dateFormat cannot be empty
	The date input format for% startDate is YYYY-MM-DD
	The date input format of% endDate is YYYY-MM-DD
	thsDateQuery = THS_DateQuery('SSE', 'dateType:trade,period:D,dateFormat:0', '2016-07-21', '2016-08-21');
    
    % Find the corresponding date based on the specified date and offset
	The format of the% date offset function is THS _ DateQuery (' exchange ',' dateType: value, period: value, dateFormat: value 	',' date ')
	% exchange cannot be empty
	The value of% dateType, period, dateFormat cannot be empty
	The date input format of% date is YYYY-MM-DD
	thsDateOffset = THS_DateOffset('SSE', 'dateType:trade,period:W,offset:-10,dateFormat:0', '2016-08-21');
    
    % Count the number of dates in the specified time interval and date type
	The format of the% date query function is THS _ DateCount (' exchange ',' dateType: value, period: value, dateFormat: value 	',' startDate ',' endDate ')
	% exchange cannot be empty
	The value of% dateType, period, dateFormat cannot be empty
	The date input format for% startDate is YYYY-MM-DD
	The date input format of% endDate is YYYY-MM-DD
	thsDateCount = THS_DateCount('SSE', 'dateType:trade,period:D,dateFormat:0', '2016-07-21', '2016-08-21');

end
%Logout function
thsLogout = THS_iFinDLogout();

Matlab Historical Quotation Function to Obtain Data and Simply Draw K chart

Brief Introduction

Demonstrate the use of Matlab basic data functions, drawing comparison active and passive buy and sell large single volume.

Sample Code

matlab
%% Simple implementation of K-line chart Demo using historical market data of RoyalFlush
% User, please change to your own account and password when using
ThsLogin = THS _ iFinDLogin (' account ',' password ');
if (thsLogin == 0 || thsLogin == -201)
% Obtain the opening, high and low closing data of a RoyalFlush (300033. SZ) from 2016-08-23 to 2016-11-23 through the historical market function
The format of the% historical market function is THS _ HistoryQuotes (' thsCodes', 'indicators', 'params', 'startDate', 'endDate ')
% thsCodes cannot be empty and supports multiple inputs. When there are multiple thsCodes, they are separated by English half-width commas, such as thsCode 1, thsCode 2, thsCode 3
% indicators cannot be null and support multiple inputs. When there are multiple indicators, they are separated by English semi-semicolons, such as indicator 1; indicator 2; indicator 3
% params cannot be null and supports multiple inputs. When using default parameters, it can be represented by 'default'. When the user only sets one of the indicators and the other parameters remain default, only the set parameters need to be entered, such as' period: W'
The date input format for% startDate is YYYY-MM-DD
The date input format of% endDate is YYYY-MM-DD
    %THS_HistoryQuotes('thsCode1,thsCode2,thsCode3','indicator1;indicator2;indicator3','param1,param2,param3','startDate','endDate')
    
    thsDataHistoryQuotes = THS_HistoryQuotes('300033.SZ','open;high;low;close','period:D,pricetype:1,rptcategory:0,fqdate:1900-01-01,hb:YSHB','2016-08-23','2016-11-23');
% Use the RoyalFlush JSON format parsing function to parse the data
thsData = THS_DataFromJSON(thsDataHistoryQuotes);
% Get open high and low data, N *1
OPEN = thsData.tables{1,1}.table.open;
HIGH = thsData.tables{1,1}.table.high;
LOW = thsData.tables{1,1}.table.low;
CLOSE = thsData.tables{1,1}.table.close;
% Get computer resolution
scrsz = get(0,'ScreenSize');
% Set window size
figure('Position',[scrsz(3)*1/4 scrsz(4)*1/6 scrsz(3)*4/5 scrsz(4)]*3/4);
% draw candlestick chart
candle(HIGH, LOW, CLOSE, OPEN, 'b');
% Simple implementation of K-line chart Demo using historical market data of RoyalFlush
Title (' Using the data obtained by the historical market function of RoyalFlush to simply realize K-line chart drawing ',' FontWeight ',' Bold ',' FontSize ', 15);
end
% Logout function
thsLogout = THS_iFinDLogout();

Matlab Data Pool Function to Obtain Data saved as a Data File

Brief Introduction

Demonstrate Matlab data pool function and THS_DataFromJSON format conversion function use and save as a data file.

Sample Code

matlab
%% Obtain SSE 50 constituent stocks through MATLAB and save them in TXT
% User, please change to your own account and password when using
ThsLogin = THS _ iFinDLogin (' account ',' password ');
if (thsLogin == 0 || thsLogin == -201)
% Use the data pool function to obtain the constituent stocks of the SSE 50 in 2016-12-19
% Data pool function format is THS _ DataPool (' modelName ',' inputParams', 'outputParams ')
% modelName cannot be null and can only be entered one at a time
% inputParams are separated by English semi-semicolons, such as inputParam 1; inputParam 2; inputParam 3
% outputParams is assigned with an English half-width colon, separated by an English half-width comma, Y means the field is output, N means the field is not output, if not written, the default is Y, such as outputParam 1: Y, outputParam 2: Y, outputParam 3: N
%THS_DataPool('modelName','inputParam1;inputParam2;inputParam3','outputParam1,outputParam2,outputParams3')
% [001005260] is the sector ID. At present, the sector ID can be viewed in [iFinD Terminal-Tools-Data Interface-Sector ID Query Tool]
thsDataDataPool = THS_DataPool('block','2016-12-19;001005260','date:Y,security_name:Y,thscode:Y');
% Use the RoyalFlush JSON format parsing function to parse the data
thsData = THS_DataFromJSON(thsDataDataPool);
% or security name
securityNames=thsData.tables{1,1}.table.SECURITY_NAME;
thsCodes=thsData.tables{1,1}.table.THSCODE;
[row, colume] = size(securityNames);
% Save data to txt file
fid = fopen('D:\test.txt', 'wt');
for i = 1 : 1:row
thsCode = thsCodes(i, :);
%fprintf(fid, '%s', thsCode);
securityName = securityNames(i, :);
%fprintf(fid, '%s\n', securityName);
fprintf(fid, '%s:%s\n', thsCode,securityName);
%securityNameStr = mat2cell(securityName);
%securityNameCell = cell2mat(nameArr(i,1));
end
fid = fclose(fid);
end
% Logout function
thsLogout = THS_iFinDLogout();

Matlab High Frequency Sequence Function and Data Smoothing Effect Display

Brief Introduction

Demonstrate the use of high-frequency sequence functions and observe the data smoothing effects of different data smoothing methods.

Sample Code

matlab
%% Data smoothing effect observation of different data smoothing methods
% User, please change to your own account and password when using
ThsLogin = THS _ iFinDLogin (' account ',' password ');
if (thsLogin == 0 || thsLogin == -201)
% Use the high-frequency sequence function to obtain the high-frequency 1 minute line data of the data RoyalFlush 2016-12-12
The format of the% high frequency sequence function is THS _ HighFrequenceSequence (' thsCodes', 'indicators', 'params', 'startTime', 'endTime ')
% thsCodes cannot be null and supports multiple inputs. When there are multiple thsCodes, they are separated by English half-width commas, such as thsCode 1, thsCode 2, thsCode 3
% indicators cannot be null and support multiple inputs. When there are multiple indicators, they are separated by English semi-semicolons, such as indicator 1; indicator 2; indicator 3
% params cannot be empty and supports multiple inputs. When using default parameters, you can use 'default'. When the user only sets one of the indicators and the other parameters remain default, only the set parameters need to be entered, such as' Interval: 5'
The date input format for% startDate is YYYY-MM-DD HH: MM: SS
The date input format of% endDate is YYYY-MM-DD HH: MM: SS
   %THS_HighFrequenceSequence('thsCode1,thsCode2,thsCode3','indicator1;indicator2;indicator3','param1,param2,param3','startTime','endTime')
   
   thsDataHighFrequenceSequence = THS_HighFrequenceSequence('300033.SZ','open;high;low;close;volume;amt',...
'CPS:0,MaxPoints:50000,Fill:Previous,Interval:1','2016-12-12 09:30:00','2016-12-12 15:00:00');
% Use the RoyalFlush JSON format parsing function to parse the data
thsData = THS_DataFromJSON(thsDataHighFrequenceSequence);
% Get the closing price data N of the 1 minute line *1
close=thsData.tables{1,1}.table.close;
% Create a new image window with
figure;
% Draw a 1 minute line closing price curve with a solid black line with a line width of 2
plot(close','K','LineWidth',2)
% Add X-axis Y-axis label
Xlabel (' observation serial number '); ylabel (' 300033. SZ RoyalFlush 1 minute closing price ');
Title (' 2016-12-12 RoyalFlush (300033. SZ) original closing price curve ',' FontWeight ',' Bold ',' FontSize ', 15);
   
   %%
% Use the box method to smooth data
CLOSE 1 = smoothts (close ',' b ', 30);% window width is 30
CLOSE 2 = smoothts (close ',' b ', 100);% window width is 100
figure;
% Draw a scatter chart of closing prices
plot(close','. ');
hold on
Plot (CLOSE1', 'K', 'LineWidth', 2);% draw a smooth curve, black solid line, line width is 2
Plot (CLOSE 2 ',' K-. ',' LineWidth ', 2);% draw a smooth curve, black dotted line, line width is 2
Xlabel (' observation serial number '); ylab (' Box Method ');
% Annotate the image
Legend (' original scatter ',' smooth curve (window width 30) ',' smooth curve (window width 100) ',' loacation ',' northwest ');
Title (' Box smoothed closing price curve ',' FontWeight ',' Bold ',' FontSize ', 15);
%%
% Smooth data with Gaussian window method
CLOSE 3 = smoothts (close ',' g ', 30);% window width is 30, standard deviation is 0.65 by default
CLOSE 4 = smoothts (close ',' g ', 100, 100);% window width is 100, standard deviation is 100
figure;
% Draw a scatter plot of closing prices
plot(close','. ');
hold on
Plot (CLOSE 3, 'K', 'LineWidth', 2);% draw a smooth curve, black solid line, line width is 2
Plot (CLOSE 4, 'K-.', 'LineWidth', 2);% draw a smooth curve, black dotted line, line width is 2
Xlabel (' observation serial number '); ylab (' Gaussian window Method ');
Legend (' original scatter ',' smooth curve (window width 30, standard deviation 0.65) ',' smooth curve (window width 100, standard deviation 100) ',' loacation ',' northwest ');
Title (' Gaussian window method smoothed closing price curve ',' FontWeight ',' Bold ',' FontSize ', 15);
%%
% Use exponential method to smooth data
CLOSE 5 = smoothts (close ',' e ', 30);% window width is 30, standard deviation is 0.65 by default
CLOSE 6 = smoothts (close ',' g ', 100, 100);% window width is 100, standard deviation is 100
figure;
% Draw a scatter chart of closing prices
plot(close','. ');
hold on
Plot (CLOSE 5, 'K', 'LineWidth', 2);% draw a smooth curve, black solid line, line width is 2
Plot (CLOSE 6, 'K-.', 'LineWidth', 2);% draw a smooth curve, black dotted line, line width is 2
Xlabel (' observation serial number '); ylab (' Exponential Method ');
Legend (' original scatter ',' smooth curve (window width 30) ',' smooth curve (window width 100) ',' loacation ',' northwest ');
Title (' Exponential smoothed closing price curve ',' FontWeight ',' Bold ',' FontSize ', 15);
end
% Logout function
thsLogout = THS_iFinDLogout();

MatlabTable Format Conversion Function Demonstration

Brief Introduction

Demonstrate the use of historical quotation functions and convert them to Table format.

Sample Code

matlab
%%*****Table data format conversion *****
%% Matlab table is a new data structure introduced in R2013b. Although not as familiar as the commonly used basic data types, it is very useful in programming. It is used to store table-like data structures and supports common table-to-table operations.
%% login function, where [ifind _ e001] is the account name and [ifinde001] is the password
% [ifind _ e001] and [ifinde001] are RoyalFlush internal test accounts and internal test passwords,
% User, please change to your own account and password when using
ThsLogin = THS _ iFinDLogin (' account ',' password ');
if (thsLogin == 0 || thsLogin == -201)
% Obtain the opening, high and low closing data of a RoyalFlush (300033. SZ) from 2016-08-23 to 2016-11-23 through the historical market function
The format of the% historical market function is THS _ HistoryQuotes (' thsCodes', 'indicators', 'params', 'startDate', 'endDate ')
% thsCodes cannot be empty and supports multiple inputs. When there are multiple thsCodes, they are separated by English half-width commas, such as thsCode 1, thsCode 2, thsCode 3
% indicators cannot be null and support multiple inputs. When there are multiple indicators, they are separated by English semi-semicolons, such as indicator 1; indicator 2; indicator 3
% params cannot be null and supports multiple inputs. When using default parameters, it can be represented by 'default'. When the user only sets one of the indicators and the other parameters remain default, only the set parameters need to be entered, such as' period: W'
The date input format for% startDate is YYYY-MM-DD
The date input format of% endDate is YYYY-MM-DD
%THS_HistoryQuotes('thsCode1,thsCode2,thsCode3','indicator1;indicator2;indicator3','param1,param2,param3','startDate','endDate')
thsDataHistoryQuotes = THS_HistoryQuotes('300033.SZ','open;high;low;close',''Interval:D,CPS:1,baseDate:1900-01-01,Currency:YSHB,fill:Previous','2016-08-23','2016-11-23');
%% Use the RoyalFlush JSON format parsing function to parse the data--JSON string format conversion
thsData = THS_Trans2Table(thsDataHistoryQuotes);
% Get each indicator data
OPEN = thsData.open;
HIGH = thsData.high;
LOW = thsData.low;
CLOSE = thsData.close;
end
% Logout function
thsLogout = THS_iFinDLogout();

R

R Language Data Pool and Base Data Function Use Cases

Brief Introduction

Demonstrate the joint use of R interface data pool function and basic data function, directly obtain and save the returned JSON format data.

Sample Code

r
library(iFinDR)
library(RJSONIO)
ret = THS_iFinDLogin("account","password")
if(ret==0){
  ans  = THS_DataPool("index","2016-11-27;SSE50","date:Y,security_name:Y,thscode:Y,weight:Y");
  code = ans$tables[[1]]$table$THSCODE;
  companys=c()
  begintimes=c()
  chairmans=c()
  registersaccounts=c()
  thscodes =c()
  for (i in 1:length(code)){
    ans = THS_BasicData(code[i],"ths_corp_cn_name_stock","")
    company = ans$tables[[1]]$table$ths_corp_cn_name_stock;
    companys=c(companys,company)
    ans = THS_BasicData(code[i],"ths_established_date_stock","")
    begintime= ans$tables[[1]]$table$ths_established_date_stock
    begintimes=c(begintimes,begintime)
    ans = THS_BasicData(code[i],"ths_reg_capital_stock","")
    registersaccount = ans$tables[[1]]$table$ths_reg_capital_stock;
    registersaccounts=c(registersaccounts,registersaccount)
    thscode = ans$tables[[1]]$thscode
    thscodes =c(thscodes,thscode)}
    text<-data.frame(thscodes,companys,begintimes,chairmans,registersaccounts)
    write.table(text,file = "D:/foo2.txt",row.names = F,quote = F,sep="\t")
    }
	else{
    print("Login failed")
  }

R Language Data Pool and High Frequency Sequence Function Use Cases

Brief Introduction

Demonstrate the joint use of R interface data pool function and high-frequency sequence function, and directly obtain and save the returned JSON format data.

Sample Code

r
library(iFinDR)
library(RJSONIO)
ret = THS_iFinDLogin("account","password")
if(ret==0){
  ans  = THS_DataPool("index","2016-11-27;SSE50","date:Y,security_name:Y,thscode:Y,weight:Y");
  code = ans$tables[[1]]$table$THSCODE;
  opens=c()
  highs=c()
  lows=c()
  closes=c()
  thscodes =c()
  times    =c()
  for (i in 1:length(code)){
    ans = THS_HighFrequenceSequence(code[i],"open;high;low;close","CPS:0,MaxPoints:50000,Fill:Previous,Interval:1","2016-11-23 09:35:00","2016-11-23 09:35:00")
    open= ans$tables[[1]]$table$open[1]
    high= ans$tables[[1]]$table$high[1]
    low= ans$tables[[1]]$table$low[1]
    close= ans$tables[[1]]$table$close[1]
    thscode = ans$tables[[1]]$thscode
    time    = ans$tables[[1]]$time
    opens=c(opens,open)
    highs=c(highs,high)
    lows=c(lows,low)
    closes=c(closes,close)
    thscodes =c(thscodes,thscode)
    times    =c(times,time)}
    text<-data.frame(thscodes,times,opens,highs,lows,closes)
    write.table(text,file = "D:/foo1.txt",row.names = F,quote = F,sep="\t")
    }else{
  print("Login failed")}

R Language History Quotes Function Use Cases

Brief Introduction

Demonstrate R interface historical quotation function to obtain data, directly obtain and save the returned JSON format data.

Sample Code

r
library(iFinDR)
library(RJSONIO)
ret <- THS_iFinDLogin("account","password")
if(ret == 0 || ret == -201){
  ans  = THS_HistoryQuotes('600000.SH','open,high,low,close','Interval:D,CPS:1,baseDate:1900-01-01,Currency:YSHB,fill:Previous','2018-12-06','2019-12-06')
  data = THS_Trans2DataFrame(ans)
  print(data)}else{
  print("Login failed")
}

R language Real-time Quotation Function Use Case

Brief Introduction

Demonstrate R interface real-time quotation function to obtain data, directly obtain and save the returned JSON format data.

Sample Code

r
library(iFinDR)
library(RJSONIO)
ret = THS_iFinDLogin("account","password")
if(ret==0){
  ans  = THS_RealtimeQuotes("300033.SZ","open;high;low;new","pricetype:1")
  code = ans$tables[[1]]$thscode;
  open=ans$tables[[1]]$table$open
  new=ans$tables[[1]]$table$new
  low=ans$tables[[1]]$table$low
  high=ans$tables[[1]]$table$high
  time    =ans$tables[[1]]$time
  text<-data.frame(code ,time,open,new,low,high)
    write.table(text,file = "D:/foo3.txt",row.names = F,quote = F,sep="\t")
    }else{
  print("Login failed")}

Temporal Sequence is Relevant

Brief Introduction

R language time series, acf correlation analysis.

Sample Code

r
library(iFinDR)
library(RJSONIO)
library(zoo)
library(xts)
ret <- THS_iFinDLogin("account","password")
if(ret==0 || ret== -201){
  hq_data  = THS_DateSerial('300033.SZ','ths_open_price_stock;ths_high_price_stock;ths_low_stock;ths_close_price_stock','100;100;100;100','','2020-09-10','2020-10-10',TRUE)
  result =  THS_Trans2DataFrame(hq_data)
  names(result)[3] = 'Open'
  names(result)[4] = 'High'
  names(result)[5] = 'Low'
  names(result)[6] = 'Close'
  result = result[,-2]
  HQ <- xts(result[,-1],order.by = as.Date(result$time))
  print(HQ)
  acf(HQ)
}

C#

C# Interface Function Use Case

Brief Introduction

Demonstrate the use of C#interface functions, including the encapsulated call method of the underlying dynamic library, and directly obtain and save the returned JSON format data.

Sample Code

csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
//using Newtonsoft.Json;
using System.Text.RegularExpressions;
using System.Threading;

namespace SampleCSharp
{
public unsafe delegate int FT_RTCallBack(void*PUser ,//When the function is called, the parameter pointer passed in by the caller
Int iQueryID ,//When the function is called, it is returned to the caller to indicate the ID of this request
char*PResultsBuff ,//Results returned by data query, in JSON format
Int iBuffLength ,//the length of the result cache
Int ErrorCode ,//error code
Int Reserved//Reserved
);
    class Program
    {
        /*
*E:\\ THSDataInterface _ Windows\\ bin\\ x86\\: This directory is the user's local data interface installation directory and the repaired bits are 32 bits. If it is 64 bits, the directory is E:\\ THSDataInterface _ Windows\\ bin\\ x64\\
*FTDataInterface.dll is the interface file, which is 32 bits, if it is 64 bits, the file name is FTDataInterface _ x64.dll
         */

        public const int REG_OPER_UPDATE = 0x01;
        public const int REG_OPER_ADD = 0x02;
        public const int REG_OPER_DEL = 0x03;


        //Modify the following path to the local data interface installation package path; if it is 64 bits, the directory is E:\\THSDataInterface_Windows\\bin\\x64\\,file name is FTDataInterface_x64.dll
        const string strPath = @"E:\\THSDataInterface_Windows\\bin\\x86\\";
        const string strDllFileName = "FTDataInterface.dll";        
        const string strDllFile = strPath + strDllFileName;

        static void Main(string[] args)
        {
            /*Login function, fill in account number and password
             */
            string strUserName = "account";
            string strPassWord = "password";
            int nRet = THS_iFinDLogin(strUserName, strPassWord);
            string strOut = "Login result:" + nRet;
            Console.WriteLine(strOut);
            Thread.Sleep(3000);

            _event = new AutoResetEvent(false);
            ThreadStart threadStart = new ThreadStart(testSample);
            Thread thread = new Thread(threadStart);
            thread.Start();
            _event.WaitOne();

            //Logout function
            //nRet = THS_iFinDLogout();
            //strOut = "Logout result:" + nRet;
            //Console.WriteLine(strOut);

            Console.ReadLine();
        }

        private static AutoResetEvent _event;
        public static void testSample()
        {
            //High frequency sequence function
            //HighFrequenceSequenceSample();

            //Real-time market function
            //RealtimeQuotesSample();

            //Historical market function
            //HistoryQuotesSample();

            //Basic data functions
            //BasicDataSample();

            //Date sequence function
            //DateSequenceSample();

            //Data pool function
            //DataPoolSample();
			
			//Thematic report function
            //DataReport();

            //EDB data request function
            //EDBQuerySample();

            //Intraday snapshot
            //Snapshot();

            //Data usage statistics function
            //DataStatisticsSample();

            //Error message query function
            //GetErrorInfoSample();

            //New date query function
            //DateQuerySample();

            //New date offset function
            //DateOffsetSample();

            //Date Statistics Function
            //DateCountSample();

            //Thread.Sleep(6000);
            //_event.Set();

        }

        static void HighFrequenceSequenceSample()
        {
            string strOut;
            //Request high frequency data to pass 5 string parameters and return data
/*The high-frequency sequence function format is THS _ HighFrequenceSequence (' thsCodes', 'indicators', 'params', 'startTime', 'endTime ')
*ThsCodes cannot be null and supports multiple inputs. When there are multiple thsCodes, they are separated by English half-width commas, such as thsCode 1, thsCode 2, thsCode 3
*Indicators cannot be null and support multiple inputs. When there are multiple indicators, they are separated by English semi-semicolons, such as indicator 1; indicator 2; indicator 3
*Params cannot be null and supports multiple inputs. When using default parameters, it can be represented by 'default'. When the user only sets one of the indicators and the other parameters remain default, only the set parameters need to be entered, such as' Interval: 5'
*The date input format for startDate is YYYY-MM-DD HH: MM: SS
*The date input format of endDate is YYYY-MM-DD HH: MM: SS
*Old version:THS_HighFrequenceSequence('thsCode1,thsCode2,thsCode3','indicator1;indicator2;indicator3','param1,param2,param3','startTime','endTime')
             */
            strOut = THS_HighFrequenceSequence("301279.SZ,600000.SH", "open;high;low;close;avgPrice;volume;amount;change;changeRatio;turnoverRatio;sellVolume;buyVolume", "Fill:Original", "2021-12-31 09:15:00", "2021-12-31 15:15:00");
            Console.WriteLine(strOut);
        }

        static void Snapshot()
        {
            string strOut;
            //Intraday snapshot
            strOut = THS_Snapshot("300033.SZ", "open;high;low", "", "2022-06-13 09:15:00", "2022-06-13 15:15:00");
            Console.WriteLine(strOut);
        }

        static void RealtimeQuotesSample()
        {
            string strOut;
            //Request real-time data
/*The format of the real-time market function is THS _ RealtimeQuotes (' thsCodes', 'indicators', 'params ')
*ThsCodes cannot be null and supports multiple inputs. When there are multiple thsCodes, they are separated by English half-width commas, such as thsCode 1, thsCode 2, thsCode 3
*Indicators cannot be null and support multiple inputs. When there are multiple indicators, they are separated by English semi-semicolons, such as indicator 1; indicator 2; indicator 3
*Params cannot be empty
*Old version: THS _ RealtimeQuotes (' thsCode 1, thsCode 2, thsCode 3 ',' indicator 1; indicator 2; indicator 3 ',' param1, param2, param3 ')
*The third parameter, 'pricetype: 1', is a parameter of the bond quotation method. The super command generates other securities types without this parameter, but please do not fill in the blanks, and fill in 'pricetype: 1' according to the following command
             */
            strOut = THS_RealtimeQuotes("300033.SZ,600000.SH", "open;high;low;latest;latestAmount;latestVolume", "pricetype:1");
            Console.WriteLine(strOut);
        }

        static void HistoryQuotesSample()
        {
            string strout;
            //Request historical quotations
/*
*Obtain the opening, high and low closing data of a RoyalFlush (300033. SZ) from 2016-08-23 to 2016-11-23 through the historical market function
*The historical market function format is THS _ HistoryQuotes (' thsCodes', 'indicators', 'params', 'startDate', 'endDate ')
*ThsCodes cannot be null and supports multiple inputs. When there are multiple thsCodes, they are separated by English half-width commas, such as thsCode 1, thsCode 2, thsCode 3
*Indicators cannot be null and support multiple inputs. When there are multiple indicators, they are separated by English semi-semicolons, such as indicator 1; indicator 2; indicator 3
*Params cannot be null and supports multiple inputs. When using default parameters, you can use 'default' to indicate that when the user only sets one of the indicators and the other parameters remain default, only the set parameters need to be entered, such as' period: W'
*The date input format for startDate is YYYY-MM-DD
*The date input format of endDate is YYYY-MM-DD
*Old version:THS_HistoryQuotes('thsCode1,thsCode2,thsCode3','indicator1;indicator2;indicator3','param1,param2,param3','startDate','endDate')
             */
            strout = THS_HistoryQuotes("300033.SZ,600000.SH", "open,high,low,close", "fill:Blank", "2021-11-09", "2021-12-08");
            Console.WriteLine(strout);
        }

        static void BasicDataSample()
        {
            string strOut;
            //Request basic data
/*Basic Data THS _ BasicData (' thsCodes', 'function', 'params '); supports multi-security single indicator input
*ThsCodes cannot be null and supports multiple inputs. When there are multiple thsCodes, they are separated by English half-width commas, such as thsCode 1, thsCode 2, thsCode 3
*The function cannot be empty, and only a single function is currently supported. The current function name can be viewed in [iFinD Terminal-Tools-Data Interface-Indicator Function Query Tool]
*Params can be empty or there can be multiple. When there are multiple params, they are separated by English half-width commas, such as param1, param2, param3
             * THS_BasicData('thsCode1,thsCode2,thsCode3','function','param1,param2,param3')
             */
            strOut = THS_BasicData("300033.SZ,600000.SH", "ths_total_shares_stock;ths_float_ashare_stock", "2022-01-08;2022-01-08");
            Console.WriteLine(strOut);
        }

        static void DateSequenceSample()
        {
            string strOut;
            //Request date sequence
/*The date series function format is THS _ DateSequence (' thsCodes', 'indicators', 'params', 'startDate', 'endDate ')
*ThsCodes cannot be null and supports multiple inputs. When there are multiple thsCodes, they are separated by English half-width commas, such as thsCode 1, thsCode 2, thsCode 3
*Indicators cannot be null and support multiple inputs. When there are multiple indicators, they are separated by English semi-semicolons, such as indicator 1; indicator 2; indicator 3
*Params cannot be null and supports multiple inputs. When using default parameters, it can be represented by 'default'. When the user only sets one of the indicators and the other parameters remain default, only the set parameters need to be entered, such as' Interval: M'
*The date input format for startDate is YYYY-MM-DD
*The date input format of endDate is YYYY-MM-DD
*Old version:THS_DateSequence('thsCode1,thsCode2,thsCode3','indicator1;indicator2;indicator3','param1,param2,param3','startDate','endDate')
             */
            strOut = THS_DateSerial("000001.SH", "ths_pe_index;ths_pb_index;ths_ps_index", "100,100;100,100;100,100", "Fill:Blank,block:history", "2021-03-23", "2021-04-23");
            Console.WriteLine(strOut);
        }

        static void DataPoolSample()
        {
            string strOut;
            //Request data pool
/*
*The data pool function format is THS _ DataPool (' modelName ',' inputParams', 'outputParams ')
*ModelName cannot be empty and can only be entered one at a time
*InputParams are separated by English semi-semicolons, such as inputParam 1; inputParam 2; inputParam 3
*OutputParams are assigned with English half-width colons, separated by English half-width commas, Y means the field output, N means the field is not output, if not written, the default is Y, such as outputParam 1: Y, outputParam 2: Y, outputParam 3: N
*THS_DataPool('modelName','inputParam1;inputParam2;inputParam3','outputParam1,outputParam2,outputParams3')
*【001005010】is the sector ID. At present, the sector ID can be viewed in【iFinD Terminal-Tools-Data Interface-Sector ID Query Tool】
*/
StrOut = THS _ DataPool (" block "," latest; 001005010 "," date: Y, thscode: Y, security _ name: Y, security _ name _ in _ time: Y ");
Console.WriteLine(strOut);

        }
		
		 static void DataReport()
        {
            string strOut;
            strOut = THS_DR("p00001", "sclx=SSE&SZSE", "p00001_f001:Y,p00001_f002:Y,p00001_f005:Y,p00001_f007:Y");
            Console.WriteLine(strOut);

        }

        static void EDBQuerySample()
        {
            string strout;
            //Request EDB Macroeconomic Data
/*The EDB data request function format is THS _ EDBQuery (' indicatorIDs', 'startDate', 'endDate ')
*IndicatorIDs cannot be empty and support multiple ID inputs. The indicator ID can be viewed in the indicator ID query tool in [iFinD Terminal-Tools-Data Interface]
*The date input format for startDate is YYYY-MM-DD
*The date input format of endDate is YYYY-MM-DD
             */
            strout = THS_EDBQuery("M001620247", "2020-01-01", "2020-12-31");
            Console.WriteLine(strout);
        }

        static void DataStatisticsSample()
        {
            string strout;
            //User data usage query function
/*
*The data usage query function is used for users to query the data usage of their own accounts. The market data is 150 million pieces/week, the basic data is 5 million pieces/week, and the EDB data is 500 pieces/week;
*The data obtained through high-frequency sequence functions, historical market functions and real-time market functions are collectively referred to as market data;
*The data obtained through the basic data function, date sequence function and data pool function are collectively referred to as basic data;
*The data obtained through the EDB data request function is collectively referred to as EDB data.
             */
            strout = THS_DataStatistics();
            Console.WriteLine(strout);
        }

        static void GetErrorInfoSample()
        {
            string strout;
            //Error code information query
/*Error information query function, query the errorcode after the function is executed, and understand the error information
*The value of value cannot be null, and the value of value must be an enumerated error value
             */
            strout = THS_GetErrorInfo(-1);
            Console.WriteLine(strout);
        }

        static void DateQuerySample()
        {
            string strout;
            //It is convenient for users to query the exchange's trading calendar within their customized time interval
/*
*Transaction Date/Calendar Date Query Function
*The format of the date query function is THS _ DateQuery (' exchange ',' dateType: value, period: value, dateFormat: value ',' startDate ',' endDate ')
*Exchange cannot be empty
*The values of dateType, period, and dateFormat cannot be empty either
*The date input format for startDate is YYYY-MM-DD
*The date input format of endDate is YYYY-MM-DD
             */
            strout = THS_Date_Query("212001", "mode:1,dateType:0,period:D,dateFormat:0", "2022-05-19", "2022-05-19");
            Console.WriteLine(strout);
        }

        static void DateOffsetSample()
        {
            string strout;
            //Query the corresponding transaction date according to the user-specified date and offset
/*
*Find the corresponding date based on the specified date and offset
*The format of the date offset function is THS _ DateQuery (' exchange ',' dateType: value, period: value, dateFormat: value ',' date ')
*Exchange cannot be empty
*The values of dateType, period, and dateFormat cannot be empty either
*The date input format for date is YYYY-MM-DD
             */
            strout = THS_Date_Offset("212001", "dateType:0,period:D,offset:0,dateFormat:0,output:singledate", "2022-05-19");
            Console.WriteLine(strout);
        }

        static void DateCountSample()
        {
            string strout;
            //It is convenient for users to uniformly query the total number of transaction dates within their customized time interval
/*
*Count the number of dates in the specified time interval and date type
*The format of the date query function is THS _ DateCount (' exchange ',' dateType: value, period: value, dateFormat: value ',' startDate ',' endDate ')
*Exchange cannot be empty
*The values of dateType, period, and dateFormat cannot be empty either
*The date input format for startDate is YYYY-MM-DD
*The date input format of endDate is YYYY-MM-DD
             */
            strout = THS_DateCount("SSE", "dateType:trade,period:D,dateFormat:0", "2016-07-21", "2017-08-21");
            Console.WriteLine(strout);
        }


/********************************************************************************************************************************************************************/

        [DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        public static extern int FT_ifinDLogin(string strUserName, string strPassWord, int nType);

        [DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        public static extern int FT_ifinDLogout();

        [DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] 
        unsafe public static extern IntPtr FTQueryTHS_SynDateCountC(string ExchangeCode, //exchange
                                                     string Param, //parameter
                                                     string startDate, //Parameters required by the function
                                                     string endDate,
                                                     out  char* pret
                                                     );


        [DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] 
        unsafe public static extern IntPtr FTQueryTHS_SynDateOffsetC(string ExchangeCode, //exchange
                                                     string Param, //parameter
                                                     string endDate,
                                                     out  char* pret
                                                     );


        [DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        unsafe public static extern IntPtr FTQueryTHS_SynDate_OffsetC(string ExchangeCode, //exchange
                                                     string Param, //parameter
                                                     string endDate,
                                                     out  char* pret
                                                     );


        [DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] 
        unsafe public static extern IntPtr FTQueryTHS_SynDateQueryC(string ExchangeCode, //exchange
                                                     string Param, //parameter
                                                     string startDate, //Parameters required by the function
                                                     string endDate,
                                                     out  char* pret
                                                     );



        [DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        unsafe public static extern IntPtr FTQueryTHS_SynDate_QueryC(string ExchangeCode, //exchange
                                                     string Param, //parameter
                                                     string startDate, //Parameters required by the function
                                                     string endDate,
                                                     out  char* pret
                                                     );



        [DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        unsafe public static extern int FTQueryTHS_SynDataPoolC(string DataPoolName, //data pool
                                                     string jsonIndicator, //
                                                     string jsonParam, //Parameters required by the function
                                                     out  char* pret
                                                     );



        [DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
		unsafe public static extern int FTQueryTHS_SynDRC(string DataReportID, //Thematic report ID
                                                    string jsonIndicator, //Report parameters
                                                    string jsonParam, //Report column name
                                                    out  char* pret
                                                    );



        [DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        unsafe public static extern int FTQueryTHS_SynDateSeriesC(string THSCodes, //RoyalFlush code
                                                     string jsonIndicator, //Indicators and parameters required by the indicators
                                                     string jsonParam, //Parameters required by the function
                                                     string begintime,
                                                     string endtime,
                                                     out  char* pret
                                                     );

		[DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] 
        unsafe public static extern int FTQueryTHS_SynDateSerialC(string THSCodes, //RoyalFlush code
                                                     string jsonIndicator, //Indicator
                                                     string jsonParam, //Parameters required by the function
													 string globalParam,
                                                     string begintime,
                                                     string endtime,
                                                     out  char* pret
                                                     );


        [DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] 
        unsafe public static extern int FTQueryTHS_SynBasicDataC(string THSCodes, //RoyalFlush code
                                                     string jsonIndicator, //Indicator
                                                     string jsonParam, //Parameters required by the function
                                                     out  char* pret
                                                     );



        [DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] 
        unsafe public static extern int FTQueryTHS_SynHisQuoteC(string THSCodes, //RoyalFlush code
                                                     string jsonIndicator, //Indicators and parameters required by the indicators
                                                     string jsonParam, //Parameters required by the function
                                                     string begintime,
                                                     string endtime,
                                                     out  char* pret
                                                     );

        [DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] 
        unsafe public static extern int FTQueryTHS_SynRTByJsonC(string THSCodes, //RoyalFlush code
                                                     string jsonIndicator, //Indicators and parameters required by the indicators
                                                     string jsonParam, //Parameters required by the function
                                                     out  char* pret
                                                     );

        [DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        unsafe public static extern int FTQueryTHS_SynHFQByJsonC(string THSCodes,
                                                      string jsonIndicator,
                                                      string jsonParam,
                                                      string begintime,
                                                      string endtime,
                                                      out  char* pret);

        [DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        unsafe public static extern int FTQueryTHS_SynEDBQueryC(string jsonIndicator,                                                    
                                                      string begintime,
                                                      string endtime,
                                                      out  char* pret);

        [DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        unsafe public static extern int FTQueryTHS_SynSnapshotQueryC(string THSCodes,
                                                      string jsonIndicator,
                                                      string jsonParam,
                                                      string begintime,
                                                      string endtime,
                                                      out  char* pret);

        [DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        unsafe public static extern int FTQueryTHS_SynGetErrorInfoC(int errorcode,
                                                      out  char* pret);

        [DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        unsafe public static extern IntPtr FTQuery_SynDataStasticsC(out int errorcode, void* reserve1, void* reserve2, void* reserve3);



        [DllImport(strDllFile, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        unsafe public static extern void DeleteBuffer(char* pret);

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//The encapsulated function command can be called directly according to the following encapsulation interface

        static int THS_iFinDLogin(string UserAcount, string Password)
        {
            int nRet = FT_ifinDLogin(UserAcount, Password, 0);
            return nRet;
        }

        static int THS_iFinDLogout()
        {
            int nRet = FT_ifinDLogout();
            return nRet;
        }

        unsafe static string THS_HighFrequenceSequence(string THSCodes,
                                                      string jsonIndicator,
                                                      string jsonParam,
                                                      string begintime,
                                                      string endtime)//High frequency sequence new version interface
        {
            string strOut;
            char* Pret;
            FTQueryTHS_SynHFQByJsonC(THSCodes, jsonIndicator, jsonParam, begintime, endtime, out  Pret);
            IntPtr data = new IntPtr(Pret);
            strOut = Marshal.PtrToStringUni(data);
            DeleteBuffer(Pret);
            return strOut;
        }

        unsafe static string THS_Snapshot(string THSCodes,
                                                      string jsonIndicator,
                                                      string jsonParam,
                                                      string begintime,
                                                      string endtime)//Intraday snapshot
        {
            string strOut;
            char* Pret;
            FTQueryTHS_SynSnapshotQueryC(THSCodes, jsonIndicator, jsonParam, begintime, endtime, out  Pret);
            IntPtr data = new IntPtr(Pret);
            strOut = Marshal.PtrToStringUni(data);
            DeleteBuffer(Pret);
            return strOut;
        }

        unsafe static string THS_RealtimeQuotes(string THSCodes, //RoyalFlush code
                                                     string jsonIndicator, //Indicators and parameters required by the indicators
                                                     string jsonParam //Parameters required by the function
                                                       )//Real-time market new version interface
        {
            string strOut;
            char* Pret;
            FTQueryTHS_SynRTByJsonC(THSCodes, jsonIndicator, jsonParam, out  Pret);
            IntPtr data = new IntPtr(Pret);
            strOut = Marshal.PtrToStringUni(data);
            DeleteBuffer(Pret);
            return strOut;
        }

        unsafe static string THS_HistoryQuotes(string THSCodes, //RoyalFlush code
                                                     string jsonIndicator, //Indicators and parameters required by the indicators
                                                     string jsonParam, //Parameters required by the function
                                                     string begintime,
                                                     string endtime
                                                     )//The new version of the historical market interface
        {
            string strOut;
            char* Pret;
            FTQueryTHS_SynHisQuoteC(THSCodes, jsonIndicator, jsonParam, begintime, endtime, out  Pret);
            IntPtr data = new IntPtr(Pret);
            strOut = Marshal.PtrToStringUni(data);
            DeleteBuffer(Pret);
            return strOut;
        }

        unsafe static string THS_BasicData(string THSCodes, //RoyalFlush code
                                                     string jsonIndicator, //Indicator
                                                     string jsonParam //Parameters required by the function
                                                     )//Basic data new version interface
        {
            string strOut;
            char* Pret;
            FTQueryTHS_SynBasicDataC(THSCodes, jsonIndicator, jsonParam, out  Pret);
            IntPtr data = new IntPtr(Pret);
            strOut = Marshal.PtrToStringUni(data);
            DeleteBuffer(Pret);
            return strOut;
        }

        // unsafe static string THS_DS(string THSCodes, //RoyalFlush code
                                                     // string jsonIndicator, //Indicators and parameters required by the indicators
                                                     // string jsonParam, //Parameters required by the function
                                                     // string begintime,
                                                     // string endtime)//Date series new version interface
        // {
            // string strOut;
            // char* Pret;
            // FTQueryTHS_SynDateSeriesC(THSCodes, jsonIndicator, jsonParam, begintime, endtime, out  Pret);
            // IntPtr data = new IntPtr(Pret);
            // strOut = Marshal.PtrToStringUni(data);
            // DeleteBuffer(Pret);
            // return strOut;
        // }

        unsafe static string THS_DateSerial(string THSCodes, //RoyalFlush code
                                                     string jsonIndicator, //Indicator
                                                     string jsonParam, //Parameters required by the function
													 string globalParam,
                                                     string begintime,
                                                     string endtime)//Date series new version interface
        {
            string strOut;
            char* Pret;
            FTQueryTHS_SynDateSerialC(THSCodes, jsonIndicator, jsonParam, globalParam, begintime, endtime, out  Pret);
            IntPtr data = new IntPtr(Pret);
            strOut = Marshal.PtrToStringUni(data);
            DeleteBuffer(Pret);
            return strOut;
        }

        unsafe static string THS_DataPool(string DataPoolName, //Data pool
                                                     string jsonIndicator, //
                                                     string jsonParam //Parameters required by the function
                                                     )//The new version of the data pool interface
        {
            string strOut;
            char* Pret;
            FTQueryTHS_SynDataPoolC(DataPoolName, jsonIndicator, jsonParam, out  Pret);
            IntPtr data = new IntPtr(Pret);
            strOut = Marshal.PtrToStringUni(data);
            DeleteBuffer(Pret);
            return strOut;
        }
		
		unsafe static string THS_DR(string DataReportID, //Thematic report ID
                                             string jsonIndicator, //Report parameters
                                             string jsonParam //Report column
                                             )//Thematic report interface
        {
            string strOut;
            char* Pret;
            FTQueryTHS_SynDRC(DataReportID, jsonIndicator, jsonParam, out  Pret);
            IntPtr data = new IntPtr(Pret);
            strOut = Marshal.PtrToStringUni(data);
            DeleteBuffer(Pret);
            return strOut;
        }

        unsafe static string THS_Date_Query(string ExchangeCode, //Exchange
                                                     string Param, //parameter
                                                     string startDate, //Parameters required by the function
                                                     string endDate)//Date query new version interface
        {
            string strOut;
            char* Pret;
            FTQueryTHS_SynDate_QueryC(ExchangeCode, Param, startDate, endDate, out  Pret);
            IntPtr data = new IntPtr(Pret);
            strOut = Marshal.PtrToStringUni(data);
            DeleteBuffer(Pret);
            return strOut;
        }

        unsafe static string THS_Date_Offset(string ExchangeCode, //Exchange
                                                     string Param, //parameter
                                                     string endDate)//Date query new version interface
        {
            string strOut;
            char* Pret;
            FTQueryTHS_SynDate_OffsetC(ExchangeCode, Param, endDate, out  Pret);
            IntPtr data = new IntPtr(Pret);
            strOut = Marshal.PtrToStringUni(data);
            DeleteBuffer(Pret);
            return strOut;
        }

        unsafe static string THS_DateCount(string ExchangeCode, //Exchange
                                                     string Param, //parameter
                                                     string startDate, //Parameters required by the function
                                                     string endDate)//Date query new version interface
        {
            string strOut;
            char* Pret;
            FTQueryTHS_SynDateCountC(ExchangeCode, Param, startDate, endDate,  out  Pret);
            IntPtr data = new IntPtr(Pret);
            strOut = Marshal.PtrToStringUni(data);
            DeleteBuffer(Pret);
            return strOut;
        }

        unsafe static string THS_EDBQuery(string jsonIndicator,
                                                      string begintime,
                                                      string endtime
                                                      )
        {
            string strOut;
            char* Pret;
            FTQueryTHS_SynEDBQueryC(jsonIndicator, begintime, endtime, out  Pret);
            IntPtr data = new IntPtr(Pret);
            strOut = Marshal.PtrToStringUni(data);
            DeleteBuffer(Pret);
            return strOut;
        }

        unsafe static string THS_DataStatistics()
        {
            string strOut;
            int code;
            strOut = Marshal.PtrToStringUni(FTQuery_SynDataStasticsC(out code, null, null, null));
            return strOut;
        }

        unsafe static string THS_GetErrorInfo(int code)
        {
            string strOut;
            char* Pret;
            FTQueryTHS_SynGetErrorInfoC(code, out  Pret);
            IntPtr data = new IntPtr(Pret);
            strOut = Marshal.PtrToStringUni(data);
            DeleteBuffer(Pret);
            return strOut;
        }
/**********************************************************************************************************************************************/

    }
}

Java

Java Interface Function Use Case

Brief Introduction

Demonstrate the simple use of java interface functions.

Sample Code

java
import java.util.Scanner;

import java.lang.Thread;

import Ths.JDIBridge;

public class test  {

public static void main(String[] args) {

		System.out.println(System.getProperty("java.library.path"));
		System.load("E://bin//x64//iFinDJava_x64.dll");
		int ret = -1;
		if (args.length > 0) {
			System.out.println("login with cn account");
		}
		 else {
				System.out.println("login with en account");
			}
	
		int a = 0;
		if (ret != 1) {
			while(true)
			{
			System.out.print(++a);
			ret = JDIBridge.THS_iFinDLogin("account", "password");
			System.out.println("THS_iFinDLogin ==> ");	
			
			
				
			String strResultDataSerious = JDIBridge.THS_DateSerial("002233.SZ","ths_open_price_stock;ths_high_price_stock;ths_low_stock;ths_close_price_stock;ths_avg_price_stock;ths_vol_stock;ths_trans_num_stock;ths_amt_stock;ths_macd_stock;ths_kdj_stock;ths_vstd_stock;ths_boll_stock;ths_rsi_stock;ths_ma_stock;ths_sar_stock;ths_wr_stock;ths_cci_stock;ths_obv_stock;ths_vol_w_stock;ths_vol_m_stock","100;100;100;100;100;100;;;26,12,9,100,100,100;9,3,3,100,100,100;10,100;26,2,100,100,100;6,100,100;10,100,100;4,100,100;14,100,100;14,100,100;100,100,100;;","Days:Tradedays,Fill:Previous,Interval:D","2018-05-31","2018-06-15");
			System.out.println("THS_iFinDhis ==> " + strResultDataSerious );
			
		  
			JDIBridge.THS_iFinDLogout();
			System.out.println("THS_iFinDLogout ==> ");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}			
			}
		}
		else {
			System.out.println("Login failed == > " + ret);
		}
	}

}