Quantitative technology of data Jun - Part 1 coming children's shoes

Children's shoes interested in quantitative techniques, especially the application of big data and artificial intelligence in quantification, can pay attention to my official account.

datahomex:

 

Recently, the circle of friends is full of counting money. Before, it was all about money color change. Now it shows that you are non-human without talking about money.

Datajun studied the coin circle transaction and found that the quantification of the coin circle has great potential (a strange smile). The coin circle is really pure numbers, and there are rows of numbers floating in the sky.

Starting today, dataking will take you to open the door of quantitative technology. This series of articles will introduce the acquisition of currency circle transaction data, the development and evaluation of quantitative strategies, and how to apply artificial intelligence technology in quantitative transactions.

This chapter mainly introduces:

1. How to obtain the APP KEY of the trading platform required by your own development program

2. Real time acquisition of K-line data of trading platform

3. How to realize programmed ordering operation through platform interface

 

1, APP KEY acquisition

Data Jun takes Huo coin platform as an example, and the operations of other platforms are similar.

Step 1: register a platform account (it's too simple and straightforward to omit directly)

Registered address: https://www.huobi.li/zh-cn/register/ , support mobile phone or email registration, and you can register directly with your mobile phone

Step 2: create API KEY

After logging in successfully with the account registered above, click the personal avatar in the upper right corner and select the API management menu (as shown in the figure) to enter the API creation page

 

On the create API page, you need to pay attention to permission setting and binding IP side operations (as shown below):

  • For the sake of security, only read and transaction are allowed, and the function of automatic withdrawal of currency by the program is limited

  • Quanjun is only for testing. The IP segment only sets the local address. The officially launched programs are generally deployed on the cloud (such as Alibaba cloud). Here you can fill in the external address of Alibaba cloud

 

After clicking the Create button, a message box will pop up. The Access key and Secret Key above must remember that the subsequent programmed transaction is the voucher of your account. Of course, the data gentleman also reminds you here:

Never reveal these two key s!

Never reveal these two key s!

Never reveal these two key s!

Here, the first step of the long march has been completed

2, K-line data acquisition

After obtaining the registered account and APP key, you can obtain the real-time historical transaction data through the API interface provided by the platform, and can also realize the order transaction and other operations through the interface. Personally, you think the interface provided by the platform is still very detailed and standardized, and the address is as follows:

        https://huobiapi.github.io/docs/spot/v1/cn/#185368440e

Today, dataking will first introduce the acquisition and storage of historical K-line data. Dataking has always been used to using python, so this time we also use Python to call the API interface of the platform. We should have a little Python Foundation (of course, the operation of other languages is basically the same)

First look at the description in the interface document provided by the platform:

The API interfaces provided by Huo coin are Restful interfaces, which are very friendly for children's shoes with some development experience. This is a general interface calling function encapsulated in python. If children's shoes are in python, they can be used directly. Of course, the key needs to be changed to its own. The code is as follows:

 

# -*- coding: utf-8 -*-
import base64import datetimeimport hashlibimport hmacimport jsonimport urllibimport urllib.parseimport urllib.requestimport requests# Fill in here APIKEYACCESS_KEY = "***********" //Fill in the secret by yourself_ Key = "************" / / fill in your own key# API request address TRADE_URL = "https://api.huobipro.com "# in the first run, you can obtain acct_id through get_accounts(), and then assign value directly to reduce repeated acquisition. Account_id = none #'timestamp ':'2017-06-02t06:13:49'def http_get_request (URL, params, add_to_headers = none): headers = {" content type ":" application / x-www-form-urlencoded "," user agent':'mozilla / 5.0 (Windows NT 6.1; wow64)  AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',    }    if add_ to_ headers:        headers. update(add_to_headers)    postdata = urllib. parse. urlencode(params)    response = requests. get(url, postdata, headers=headers, timeout=5)     try:                if response. status_ code == 200:            return response. json()        else:            return    except BaseException as e:        print("httpGet failed, detail is:%s,%s" %(response.text,e))        returndef http_ post_ request(url, params, add_to_headers=None):    headers = {        "Accept": "application/json",        'Content-Type': 'application/json'    }    if add_ to_ headers:        headers. update(add_to_headers)    postdata = json. dumps(params)    response = requests. post(url, postdata, headers=headers, timeout=10)    try:                if response. status_ code == 200:            return response. json()        else:            return    except BaseException as e:        print("httpPost failed, detail is:%s,%s" %(response.text,e))        returndef api_ key_ get(params, request_path):    method = 'GET'    timestamp = datetime. datetime. utcnow(). strftime('%Y-%m-%dT%H:%M:%S')    params. update({'AccessKeyId': ACCESS_KEY,                   'SignatureMethod': 'HmacSHA256',                   'SignatureVersion': '2',                   'Timestamp': timestamp})    host_ url = TRADE_ URL    host_ name = urllib. parse. urlparse(host_url). hostname    host_ name = host_ name. lower()    params['Signature'] = createSign(params, method, host_name, request_path, SECRET_KEY)    url = host_ url + request_ path    return http_ get_ request(url, params)def api_ key_ post(params, request_path):    method = 'POST'    timestamp = datetime. datetime. utcnow(). strftime('%Y-%m-%dT%H:%M:%S')    params_ to_ sign = {'AccessKeyId': ACCESS_KEY,                      'SignatureMethod': 'HmacSHA256',                      'SignatureVersion': '2',                      'Timestamp': timestamp}    host_ url = TRADE_ URL    host_ name = urllib. parse. urlparse(host_url). hostname    host_ name = host_ name. lower()    params_ to_ sign['Signature'] = createSign(params_to_sign, method, host_name, request_path, SECRET_KEY)    url = host_ url + request_ path + '?' +  urllib. parse. urlencode(params_to_sign)    return http_ post_ request(url, params)    def createSign(pParams, method, host_url, request_path, secret_key):    sorted_ params = sorted(pParams.items(), key=lambda d: d[0], reverse=False)    encode_ params = urllib. parse. urlencode(sorted_params)    payload = [method, host_url, request_path, encode_params]    payload = '\n'. join(payload)    payload = payload. encode(encoding='UTF8')    secret_ key = secret_ key. encode(encoding='UTF8')    digest = hmac. new(secret_key, payload, digestmod=hashlib.sha256). digest()    signature = base64. b64encode(digest)    signature = signature. decode()    return signature        
call/market/history/kline Interface to obtain historical data. The code is as follows:
# Get klinedef get_ Kline (symbol, period, size = 150): "" ": param symbol: param period: optional values: {1min, 5min, 15min, 30min, 60min, 1day, 1mon, 1week, 1year}: param size: optional values: [12000]: Return:" "" params = {symbol ': symbol,' period ': period,' size ': size} url = Market_ URL + '/market/history/kline'    return http_ get_ request(url, params)

Data Jun take the acquisition of dogeusdt transaction pairs and 5-minute K-line data as an example, up to 2000 records can be obtained at a time:

jsonData = get_kline(symbol='dogeusdt',period='5min',size=2000)df=parse_json(jsonData.get('data'))

The Huo coin restful interface cannot be obtained according to the specified time period. If it needs to be obtained according to the specified time period, it needs to use the websocket API interface. The data should consider the later test and evaluation quantification strategy, so the obtained data will be persisted and retained in the local database. The detailed retained data is shown in the figure below:

Seeing the children's shoes here is not far from the success of the long march~~~

3, Realize programmed ordering

The exciting moment is coming. Dataking will realize a programmed ordering. The ordering interface of the platform is shown in the figure below,

The order interface can be used to buy and sell. There are many parameters. The description is as follows:

Parameter nameRequiredDefault valuedescribe
account-idTRUENAAccount ID, refer to GET /v1/account/accounts for value. The account ID of the 'spot' account is used for spot transactions; For position by position leverage trading, please use the account ID of the 'margin' account; For full position leverage trading, please use the account ID of the 'super margin' account
symbolTRUENATransaction pair, btcusdt, ethbtc (refer to GET /v1/common/symbols for values)
typeTRUENAOrder type, including buy market, sell market, buy limit, sell limit, buy IOC, sell IOC, buy limit maker, sell limit maker (see below for description), buy stop limit, sell stop limit, buy limit FOK, sell limit FOK, buy stop limit FOK, sell stop limit FOK, sell stop limit Fok
amountTRUENAOrder transaction volume (the market price is the order transaction volume)
priceFALSENAOrder price (invalid for market price order)
sourceFALSEspot-apiFill in "spot API" for spot transactions, "margin API" for position by position leveraged transactions, "super margin API" for full position leveraged transactions, and "C2C margin API" for C2C leveraged transactions
client-order-idFALSENAUser made order number (maximum length 64 characters, must be unique within 24 hours)
stop-priceFALSENATrigger price of stop profit and stop loss order
operatorFALSENATrigger price of stop profit and stop loss order: gte – greater than and equal (> =), LTE – less than and equal (< =)

The calling code of the order interface is as follows:

 

//Interface for obtaining account information / / it is usually initialized once when the program is started. Def get_ accounts():    """    :return:     """    path = "/v1/account/accounts"    params = {}    return api_ key_ get(params, path)def send_ Order (amount, source, symbol, _type, price = 0): "" ": param amount:: param source: if loan asset transaction is used, please fill in 'margin API' in the order interface, request parameter source, fill in" spot API "for spot transaction, fill in" margin API "for position by position leverage transaction, fill in" super margin API "for full position leverage transaction and" C2C margin API "for C2C leverage transaction ": param symbol:: param _type: optional values {buy market: buy at market price, sell market: sell at market price, buy limit: buy at limited price, sell limit: sell at limited price}: param price:: Return:" "" try: accounts = get_ accounts()        acct_ id = accounts['data'][0]['id']    except BaseException as e:        print ('get acct_id error.%s' % e)        acct_ id = ACCOUNT_ ID    params = {"account-id": acct_id,              "amount": amount,              "symbol": symbol,              "type": _type,              "source": source}    if price:        params["price"] = price    url = '/v1/order/orders/place'    return api_ key_ post(params, url)

Now you can buy a doge test at the market price through the program:

print(send_order(amount='10',source='spot-api',symbol='dogeusdt',_type='buy-market'))

Bad start. The IP address is illegal according to the error information. We need to add the IP address to the bound IP column in the create API Key page!

After adding the IP address, buy it again. If you find that the purchase is successful, sprinkle it (as shown in the figure below)

Log in to the platform and you can see the successful purchase on the order page, as shown in the following figure:

Then, you can sell the doge you just bought directly at the market price through the program. The results are as follows:

Log in to the platform order page and confirm again:

Why are there three transactions? I just forgot to change the buying into selling in the data Jun program, so I bought another one. Look at the handling fee, which makes me worried. Therefore, the procedural transaction should be cautious, cautious and cautious. Oolong refers to all this!!!

 

summary

Today, datajun finally took a solid step on the road of quantification, and successfully realized the programmed purchase and sale once!

Of course, this is far from the real quantification. To be exact, it is not quantification at all, but everything is difficult at the beginning. This is also a good beginning. The links are all through, and the second time we sprinkle flowers to celebrate!!

Later, the data gentleman will bring real quantitative technology to the children's shoes, as if he saw a pile of gold coins waving to the data gentleman in the near future (strange smile)!!!

Keywords: Machine Learning Programmer Digital Currency

Added by Sj0wKOoMel on Fri, 11 Feb 2022 08:50:52 +0200