Python を使って定量的な取引ロボットのタイムストップ・スタート・ガジェットを実装

作者: リン・ハーンリディア, 作成日:2022-12-20 14:35:09, 更新日:2023-09-20 10:21:21

img

Python を使って定量的な取引ロボットのタイムストップ・スタート・ガジェットを実装

ネットワーク全体のための強力で柔軟で使いやすい量的な取引プラットフォームとして,FMZ Quant Trading Platformは使用に非常に低い障壁があり,ロボットプログラムはほとんどリソースを使いません.しかし,ロボットが実行する必要のあるときに起動し,実行する必要がないときに停止できると希望しています. 例えば,非開業時間は,商品先物取引のプログラムおよび定量取引を行うとき,全日の圧倒的多数を占めています.この方法により,ロボットは開業時にのみ動作し,お金を節約するために毎日開業時にのみ動作することを希望しています.ワクワクしませんか?この要件を満たすために,私たちはPython言語を使用して,FMZ Quant Trading Platformで実行される戦略ロボットを書き,FMZ Quant Trading Platformの拡張APIインターフェースを通じて,ロボットの開始と停止を定期的に制御することができます.

必要なものなら やってみよう!

実際,コード全体が非常にシンプルです. FMZ Quant Trading Platformの拡張 API インターフェースを直接呼び出す例は使用できます.

アドレス:https://www.fmz.com/api#simple

直接例の関数を使う:def api (method, *args)呼び出す必要があるインターフェースも非常にシンプルです.以下の2つのインターフェースが使用されています (FMZ文書で見つけることができます)

  • ロボットを再起動 ロボットインターフェースを再起動して ロボットIDにパラメータを入力します 特定の使用id呼び出すために:api ('RestartRobot', id)

  • ストップロボット ロボットのインターフェースを停止するには,パラメータもロボットですIDわかった ロボットID:

img

FMZ Quant Trading Platformの拡張 API を呼び出すには,API KEYFMZ量子取引プラットフォームの アカウント管理で独自の API キーを生成できます 通り過ぎるAPI KEY戦略パラメータとして FMZ量子取引プラットフォームのアカウントを取得するスクリーンショットAPI KEY:

img

タイムリングパラメータを設定します.

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

設定がより多くなったことを示しています"175708,14:55:33-15:10:33"設定できます タイミングパラメータはJSON文字列で,戦略コードのリストに解析されます.リスト内の各要素はロボット開始/停止設定のセットです. 具体的には

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

コマの前の部分は175708ロボットのIDで,コンマの後ろの部分はスタート/ストップ時間です. 上記の例では,ID 175708のロボットが14:55:33でスタートし,15:10:33で停止します

ロボットが回転するたびに,まず現在の時間を取得し,現在の時間とタイムリング時間の比較に基づいて,ロボットが起動するか停止するか判断します. ロボットを起動し停止するには,API ('RestartRobot', id) またはAPI (StopRobot, id) を呼び出します.

完全な戦略コード:

# -*- 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: delimiter,")
        param["id"] = arr[0]
        param["isProcessOpenThisDay"] = False
        param["isProcessCloseThisDay"] = False

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

        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 parameters", 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 a start today", "Did you perform a 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"], "Execution started, please log in to the platform to check if it started successfully", "Extended 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"], "Execution stopped, please log in to the platform to check if it stopped successfully", "Extended API return value:", ret, strPush)
        
        if nowDay != nowTime.tm_mday:
            nowDay = nowTime.tm_mday

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

ロボットのパラメータ設定:

img

戦略実行:

スクリーンショット:

img img

戦略アドレス:https://www.fmz.com/strategy/184600

終了

例えば,FMZ Quant Trading Platformの拡張APIは依然として非常に強力です.これらの拡張APIを使用してFMZプラットフォームに基づいて独自の定量取引プラットフォームを構築することは問題ありません. タイムリングロボットの設計はシンプルで,そのタイミングで起動し,そのタイミングで停止する.起動が成功するか,検査,例外再試行などなどのメカニズムを含まない.興味がある場合は,機能を追加して拡張することができます. 戦略は参考にのみ


関連性

もっと