The resource loading... loading...

Timing start or stop widgets for quantified trading robots using Python

Author: Inventors quantify - small dreams, Created: 2020-02-14 21:56:58, Updated: 2023-10-10 21:13:38

img

Timing start or stop widgets for quantified trading robots using Python

As a powerful, flexible and easy-to-use quantitative trading platform, the inventors of the quantitative trading platform, although the use threshold is very low and the robotic program takes up very few resources. But we still hope that the robot will start when it needs to run, not stop when it needs to run. For example, in the case of commodity futures programming and quantitative trading, the non-market time takes up the vast majority of the day. So we really want to have the robot run only at the opening hours, and it is exciting to think about saving money every day. For this need, we can use Python to write a strategy robot that runs on the FMZ quantitative trading platform, and let the robot pass through. Inventors quantify the extended API interface of the trading platform, timing the start and stop of the robot.

If there is a demand, say it and do it!

In fact, the entire code is very simple, and the inventor's example of calling the quantitative trading platform extension API interface can be used directly.

The address:https://www.fmz.com/api#简单的例子

Use the function directly in the example: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 documentation)

  • I'm not sure. Restart the robot interface, and the parameters can be passed to the robot ID. Specific useidIt's called "Show Me Your Love".api('RestartRobot', id)

  • StopRobot Stop the robot interface, the parameters are also robotsID

    The robotIDSee, get, and screenshot:img

Inventors call for an extended API to use inventors' quantitative trading platformsAPI KEYI'm not sure. You can generate your own account managementAPI KEYI'm not sure. We're going toAPI KEYThis is the first time I have seen this feature. How to get inventors' accounts on a quantitative trading platformAPI KEYThe screenshot:img

All that is left is to write a timing logic, which is very simple, and set the timing parameters:

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

The omitted representative can set more similar"175708,14:55:33-15:10:33"The setting of the page is: A timing parameter is a JSON string that is parsed in the policy code as a list. Each element in the list is a set of bot start/stop settings. It means:

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

The comma intervals are used to indicate the part before the comma.175708For the robot ID, the part after the comma is the start/stop time. In the example above, the ID of the robot is: 175708, 14:55:33 starts, 15:10:33 stops.

The strategy then rotates around, taking the current time at each turn, and then deciding whether to trigger the bot to start or stop based on the comparison of the current time and the timing time. If triggered, call the API (RestartRobot button, id) or the API (StopRobot button, id) to start or stop the robot.

The full code of the strategy:

# -*- 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("字符串配置错误:分隔符号,")
        param["id"] = arr[0]
        param["isProcessOpenThisDay"] = False
        param["isProcessCloseThisDay"] = False

        arr = arr[1].split("-")
        if len(arr) != 2:
            raise Exception("字符串配置错误:分隔符号-")

        begin = arr[0]
        arrBegin = begin.split(":")
        if len(arrBegin) != 3:
            raise Exception("字符串配置错误:起始时间分隔符号:")
        
        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("字符串配置错误:结束时间分隔符号:")            
        
        param["end"] = {}
        param["end"]["hour"] = float(arrEnd[0])
        param["end"]["min"] = float(arrEnd[1])
        param["end"]["sec"] = float(arrEnd[2])
        arrParams.append(param)

    # 测试
    Log("输出参数", 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", "今天是否执行过启动", "今天是否执行过停止"],
            "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("机器人ID:", arrParams[i]["id"], "执行启动,请登录平台检查是否启动成功", "扩展API返回值:", 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("机器人ID:", arrParams[i]["id"], "执行停止,请登录平台检查是否停止成功", "扩展API返回值:", ret, strPush)
        
        if nowDay != nowTime.tm_mday:
            nowDay = nowTime.tm_mday

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

The robot's parameters are:

img

The strategy works:

Screenshot from the videoimg

The robot that was manipulated by this strategy:img

The policy address:https://www.fmz.com/strategy/184600

The End

As a starting point, the inventors' extensions to the quantitative trading platform are also very powerful, and it is perfectly fine to use these extensions to make their own quantitative trading platform based on the FMZ platform. This timing robot design is relatively simple, just brainless to start at the time, to stop at the time, and does not include the mechanism of whether the start is successful, check, abnormal retry, etc., which is interested in adding functionality, expansion. The strategy is for learning purposes only


Related

More