Using Python to realize the start or stop gadget of Quantitative Trading Robot

Using Python to realize the start or stop gadget of Quantitative Trading Robot

As a powerful, flexible and easy-to-use quantitative trading platform for the whole network, the inventor's quantitative trading platform has a very low threshold of use, and the robot program occupies little resources. But we still hope to make the robot start when it needs to run and stop when it doesn't need to run.
For example, in the process of commodity futures trading, non opening time accounts for the vast majority of the day. In this way, we very much hope that we can only let the robot run at the opening time, and that we can save more money by running only at the opening time every day, which is exciting to think about. For this requirement, we can use Python language to write a strategy robot running on the FMZ quantitative trading platform, and let the robot pass the
The inventor quantifies the extended API interface of the trading platform and controls the start and stop of the robot at a fixed time.

If you have a need, just do it!

In fact, the whole code is very simple. The example calling the inventor's quantitative trading platform to extend API interface can be used directly. Address: https://www.fmz.com/apią·% E7% AE% 80% E5% 8D% 95% E7% 9A% 84% E4% be% 8b% E5% ad% 90
Use the function in the example directly: def api(method, *args)
The interface we need to call is also very simple, using the following two interfaces (which can be found in the FMZ document)

  • RestartRobot
    Restart the robot interface and input the parameters into the robot ID.
    Use the specific id to call: api('RestartRobot', id)

  • StopRobot
    Stop robot interface, parameter is also robot ID.

    View and obtain robot ID, screenshot:

To call the inventor quantitative trading platform extension API, you need to use the API KEY of the inventor quantitative trading platform.
You can generate your own API KEY in account management.
We passed in the API KEY as a parameter of the policy.
Obtain the screenshot of API KEY of the inventor's quantitative trading platform account:

The rest is to write timing logic, which is also very simple. Set timing parameters:

["175708,14:55:33-15:10:33", ...]

The ellipsis indicates that more settings like "175708,14:55:33-15:10:33" can be set.
The timing parameter is a JSON string, which will be parsed into a list in the policy code. Each element in the list is a set of robot start / stop settings.
Namely:

"175708,14:55:33-15:10:33"

It is separated by commas. The part 175708 before the comma is the robot ID, and the part after the comma is the start time / stop time.
As an example, the robot with ID 175708 starts at 14:55:33 and stops at 15:10:33.

In the strategy, the current time is obtained first, and then the robot needs to be triggered to start or stop according to the comparison between the current time and the timing time.
If triggered, call the api('RestartRobot ', id) or api('StopRobot', id) to start and stop the robot.

Complete policy code:

# -*- coding: utf-8 -*-
import time
import json

try:
    import md5
    import urllib2
    from urllib import urlencode
except:
    import hashlib as md5
    import urllib.request as urllib2
    from urllib.parse import urlencode

def api(method, *args):
    d = {
        'version': '1.0',
        'access_key': accessKey,
        'method': method,
        'args': json.dumps(list(args)),
        'nonce': int(time.time() * 1000),
        }

    d['sign'] = md5.md5(('%s|%s|%s|%d|%s' % (d['version'], d['method'], d['args'], d['nonce'], secretKey)).encode('utf-8')).hexdigest()
    return json.loads(urllib2.urlopen('https://www.fmz.com/api/v1', urlencode(d).encode('utf-8')).read().decode('utf-8'))

RobotParams = json.loads(strRobotParams)

def main():
    global RobotParams 
    arrParams = []
    nowDay = 0
    strPush = ""
    if isPushMsg:
        strPush = "@"

    for i in range(len(RobotParams)):
        param = {}
        arr = RobotParams[i].split(",")
        if len(arr) != 2:
            raise Exception("String configuration error: separator,")
        param["id"] = arr[0]
        param["isProcessOpenThisDay"] = False
        param["isProcessCloseThisDay"] = False

        arr = arr[1].split("-")
        if len(arr) != 2:
            raise Exception("String configuration error: separator-")

        begin = arr[0]
        arrBegin = begin.split(":")
        if len(arrBegin) != 3:
            raise Exception("String configuration error: start time separator:")
        
        param["begin"] = {}
        param["begin"]["hour"] = float(arrBegin[0])
        param["begin"]["min"] = float(arrBegin[1])
        param["begin"]["sec"] = float(arrBegin[2])

        end = arr[1]
        arrEnd = end.split(":")
        if len(arrEnd) != 3:
            raise Exception("String configuration error: end time separator:")            
        
        param["end"] = {}
        param["end"]["hour"] = float(arrEnd[0])
        param["end"]["min"] = float(arrEnd[1])
        param["end"]["sec"] = float(arrEnd[2])
        arrParams.append(param)

    # test
    Log("Output parameter", arrParams, "#FF0000")  

    while True:
        nowTime = time.localtime(time.time())
        nowHour = nowTime.tm_hour 
        nowMin = nowTime.tm_min
        nowSec = nowTime.tm_sec
        
        tbl = {
            "type" : "table", 
            "title" : "msg", 
            "cols" : ["id", "begin", "end", "Did you perform startup today", "Did you stop today"],
            "rows" : []
        }

        for i in range(len(arrParams)):
            tbl["rows"].append([arrParams[i]["id"], json.dumps(arrParams[i]["begin"]), json.dumps(arrParams[i]["end"]), arrParams[i]["isProcessOpenThisDay"], arrParams[i]["isProcessCloseThisDay"]])
            if nowDay != nowTime.tm_mday:
                arrParams[i]["isProcessOpenThisDay"] = False
                arrParams[i]["isProcessCloseThisDay"] = False

            if arrParams[i]["isProcessOpenThisDay"] == False:
                if nowTime.tm_hour == arrParams[i]["begin"]["hour"] and nowTime.tm_min >= arrParams[i]["begin"]["min"] and nowTime.tm_sec >= arrParams[i]["begin"]["sec"]:
                    ret = api('RestartRobot', int(arrParams[i]["id"]))                    
                    arrParams[i]["isProcessOpenThisDay"] = True
                    Log("Robot ID:", arrParams[i]["id"], "Please log in to the platform to check whether the startup is successful", "extend API Return value:", ret, strPush)

            if arrParams[i]["isProcessCloseThisDay"] == False:
                if nowTime.tm_hour == arrParams[i]["end"]["hour"] and nowTime.tm_min >= arrParams[i]["end"]["min"] and nowTime.tm_sec >= arrParams[i]["end"]["sec"]:
                    ret = api('StopRobot', int(arrParams[i]["id"]))
                    arrParams[i]["isProcessCloseThisDay"] = True
                    Log("Robot ID:", arrParams[i]["id"], "Execute stop. Please log in to the platform to check whether the stop is successful", "extend API Return value:", ret, strPush)
        
        if nowDay != nowTime.tm_mday:
            nowDay = nowTime.tm_mday

        LogStatus(_D(), nowTime, "\n`" + json.dumps(tbl) + "`")
        Sleep(500)

Robot parameter setting:

Policy run:

screenshot

Robots operated by this strategy:

Policy address: https://www.fmz.com/strategy/184600

Ending

As an introduction, the extended API of the inventor's quantitative trading platform is also powerful. It is no problem to build a quantitative trading platform based on FMZ platform with these extended APIs.
The timing robot is simple in design, but it has no brain to start at time, to stop at time, and no mechanism to check whether the start is successful or not, to retry abnormally, and so on. If you are interested, you can add functions and expand.
Strategies for learning only

Published 75 original articles, won praise 1, visited 4903
Private letter follow

Tags: JSON Python network REST

Posted on Wed, 11 Mar 2020 01:15:04 -0400 by Mr.Fab