Oak's hands teach you how to use JS to connect FMZ extension API

Posted by CookieD89 on Sat, 27 Jun 2020 07:19:18 +0200

brief introduction

Hello, I'm "oak quantification". Due to the previous period of time, I developed the market trend reminder[ Monitoring market ]It is widely loved by everyone, and has the synchronous reminder of the service number of the same name of [oak quantification], which gives new and old leeks a new reference in judging the market trend. With this enthusiasm, we started to connect FMZ's extended API to realize message communication between robots, and directly push market reminders to designated robots. This article exemplifies two application scenarios, in order to attract more and more people to develop interesting things

This article mainly introduces:
1, How to connect the FMZ extension API through JS language. (this article takes GetNodeList method as an example)
2, Case 1: using the command robot method of the extended API to realize the message communication between the large scale robot and other robots.
3, Case 2: use getrobot detail method of extended API to realize unified monitoring and display of multiple robot data.


1, Using JS to interface with FMZ's extended API

1) . apply for AccessKey and SecretKey (hereinafter referred to as AK and SK).
We apply in the menu of Account Settings > API interface > create new ApiKey on the FMZ official website, and then obtain a set of AK and SK and record them. (unlike an exchange, the AK and sk of FMZ are visible for the first time. In FMZ, we can view the full data of our AK and SK in the [API interface] menu at any time.)


2) . develop according to the document of extended API
Let's first look at the key steps of the request API
1. FMZ API interface:

https://www.fmz.com/api/v1

2. Request basic parameters

{
    'version'   : '1.0',                                //Custom version number
    'access_key': '8a148320e0bxxxxxxxxxxxxxx19js99f',   //AK
    'method'    : 'GetNodeList',                        //Specific method called
    'args'      : [],                                   //Parameter list of specific method algorithm
    'nonce'     : 1516292399361,                        //Time stamp in milliseconds
    'sign'      : '085b63456c93hfb243a757366600f9c2'    //Signature (it needs to be obtained by encryption according to the above five parameters, which will be described below)
}

3. The complete request URL is spliced in the form of question mark parameter

with GetNodeList Method as an example
https://www.fmz.com/api/v1?
access_key=8a148320e0bxxxxxxxxxxxxxx19js99f&
nonce=1516292399361&
args=%5B%5D&
sign=085b63456c93hfb243a757366600f9c2&
version=1.0&
method=GetNodeList

4. Signature method

After the parameters are spliced in the following order, the MD5 encryption algorithm is used to encrypt the string and convert it to the hexadecimal data string value, which is the value of the parameter sign.
version + "|" + method + "|" + args + "|" + nonce + "|" + secretKey

5. To sum up, there are the following codes
Source address: [oak quantification] - JS docking FMZ extension API Demo

var URL = "https://www.fmz.com/api/v1?";
var AK = "b3a53d3XXXXXXXXXXXXXXXXXXX866fe5";//Replace your own AccessKey here
var SK = "1d9ddd7XXXXXXXXXXXXXXXXXXX85be17";//Replace it with your own secret key

function main() {
    //Get 5 basic parameter objects
    var param = getParam("1.0.0",AK,getArgs());
    Log("param:",param);
    //Get the result of md5 encryption
    var md5Result = md5(param);
    //Assign encryption result to basic parameter object
    param.sign = md5Result;
    //Get the URL of the request api
    var finalUrl = getFinalUrl(param);
    Log("finalUrl:",finalUrl);
    //Execute request and print results
    var info = HttpQuery(finalUrl);
    Log("info:",info);
}

//Get the object of the basic 5 parameters
function getParam(version,ak,args){
    return {
        'version': version,
        'access_key': ak,
        'method': 'GetNodeList',
        'args': JSON.stringify(args),
        'nonce': new Date().getTime()
    }
}

//Perform md5 encryption
function md5(param){
    var paramUrl = param.version+"|"+param.method+"|"+param.args+"|"+param.nonce+"|"+SK
    Log("paramUrl:",paramUrl);
    return Hash("md5", "hex", paramUrl)
}

//Get the final request URL
function getFinalUrl(param){
    return URL+"access_key="+AK+"&nonce="+param.nonce+"&args="+param.args+"&sign="+param.sign+"&version="+param.version+"&method="+param.method;
}

//The naming method of... args is not supported in js, so use the arguments keyword to get the parameter array
function getArgs(){
    return [].slice.call(arguments);
}

Case 2: using command robot method of extended API to realize message communication between robots

Based on the above code, we use the CommandRobot method to realize the message communication between robots.

First, let's look at the two parameters required for the commandrobot (robot ID, CMD) method

Parameter name type meaning
RobotId int Robot ID, you can use getrobot list ( )Get it or get it on the robot details page
Cmd String Messages to robots

Knowing the meaning of the parameter, let's implement the calling method next.

1. Get the robot ID on the robot details page:

2. How to get Cmd message

//Get header information
function getMessageBody(toUserName,msgType,content){
    return ({
        "toUserName":toUserName,//To whom
        "fromUserName":AOKE_INFO,//Source
        "createTime": new Date().getTime(),//Current timestamp
        "msgType":msgType,//Message type
        "content":content,//Message content
        "msgId":Math.random().toString(36).slice(-8)//Message ID
    })
}

//Get the trend information of message body (data in the content field of message header)
function getCtaDate(symbol,timeCycle,direction,nowCycleTime){
    return {
        "symbol":symbol,//Transaction currency
        "timeCycle":timeCycle,//Trend cycle
        "direction":direction,//Current entry direction, 0: short, 1: long
        "createTime":new Date().getTime(),//Current timestamp
        "nowCycleTime":nowCycleTime//Current cycle start time
    }
}

3. Modify send message code

//Get messages before sending them
var sendMessage = getMessageBody("Test object",'CTARemind',getCtaDate('BTC_USDT','120','0','2020-05-1620:00:00'));

//Get the robot ID and message body through the getArgs() method, and pass in the basic parameters.
var param = getParam("1.0.0",AK,getArgs(17777,sendMessage));

4. Execute the main method, after sending the message, use the GetCommand() method to get the message

function main(){
    while(true) { 
        var cmd = GetCommand()
        if (cmd) { 
            Log(cmd)
        }
        Sleep(1000) 
    }
}

Message sent successfully:

Message received successfully:

Case 3: using GetRobotList and GetRobotDetail methods of extended API to realize robot data monitoring and display.

Similarly, let's first look at the parameter descriptions of the following two methods
GetRobotList(offset, length, robotStatus, label):

Parameter name type meaning
offset int Page number of query
length int Data length of query page
robotStatus int Pass - 1 for all
label String Custom tag, all robots with this tag can be filtered out

GetRobotDetail(RobotId):

Parameter name type meaning
RobotId int Robot ID

1. Get the Robot list through GetRobotList method

//Get robot list information
var robotListJson = getAPIInfo('GetRobotList',getArgs(OFF_SET,PAGE_LENGTH,-1));
var robotList = robotListJson.data.result.robots;

2. Get robot details

//Get robot details
var robotDetailJson = getAPIInfo('GetRobotDetail',getArgs(robotId));
var robotDetail = robotDetailJson.data.result.robot;

3. Console output table data

function getLogPrient(infoArr){
    return table = {
            type: 'table',
            title: 'Robot display of oak quantification',
            cols: ['robot ID','Robot name','Policy name','Next deduction time','Time consumed ms','Amount consumed CNY','Last active time','Open or not'],
            rows: infoArr
        };
}

4. To sum up, there are the following codes
Source address: [oak quantification] - use the extended API to obtain robot information and display

var URL = "https://www.fmz.com/api/v1?";
var AK = "b3a53d3XXXXXXXXXXXXXXXXXXX866fe5";//Replace your own AccessKey here
var SK = "1d9ddd7XXXXXXXXXXXXXXXXXXX85be17";//Replace it with your own secret key
var OFF_SET = 0;//Page subscript of query
var PAGE_LENGTH = 5;//Data length of query page

function main() {
    LogReset();
    while(true){
        //Get robot list information
        var robotListJson = getAPIInfo('GetRobotList',getArgs(OFF_SET,PAGE_LENGTH,-1));
        //Take out robot list information
        var robotList = robotListJson.data.result.robots;
        //Create an array of robot information
        var infoArr = new Array();
        var infoArr_index = 0;
        for (index = 0; index < robotList.length; index++) {
            var robot = robotList[index];
            //Take out the robot ID of the current cycle
            var robotId = robot.id;
            //Get robot details
            var robotDetailJson = getAPIInfo('GetRobotDetail',getArgs(robotId));
            var robotDetail = robotDetailJson.data.result.robot;
            //Convert details to array objects
            var arr = getLogPrientItem(robotDetail);
            infoArr[infoArr_index] = arr;
            infoArr_index++;
        }
        Log("infoArr:",infoArr);
        LogStatus('`' + JSON.stringify(getLogPrient(infoArr)) + '`');
        Sleep(30000);
    }
}

function getLogPrient(infoArr){
    return table = {
            type: 'table',
            title: 'Robot display of oak quantification',
            cols: ['robot ID','Robot name','Policy name','Next deduction time','Time consumed ms','Amount consumed CNY','Last active time','Open or not'],
            rows: infoArr
        };
}

//Get API information through parameters
function getAPIInfo(method,dateInfo){
    //Get 5 basic parameter objects
    var param = getParam("1.0.0",AK,method,dateInfo);
    //Log("param:",param);
    //Get the result of md5 encryption
    var md5Result = md5(param);
    //Assign encryption result to basic parameter object
    param.sign = md5Result;
    //Get the URL of the request api
    var finalUrl = getFinalUrl(param);
    //Log("finalUrl:",finalUrl);
    //Execute request and print results
    var info = HttpQuery(finalUrl);
    //Log("info:",info);
    return JSON.parse(info);
}

//Get the object of the basic 5 parameters
function getParam(version,ak,method,args){
    return {
        'version': version,
        'access_key': ak,
        'method': method,
        'args': JSON.stringify(args),
        'nonce': new Date().getTime()
    }
}

//Perform md5 encryption
function md5(param){
    var paramUrl = param.version+"|"+param.method+"|"+param.args+"|"+param.nonce+"|"+SK
    //Log("paramUrl:",paramUrl);
    return Hash("md5", "hex", paramUrl)
}

//Get the final request URL
function getFinalUrl(param){
    return URL+"access_key="+AK+"&nonce="+param.nonce+"&args="+param.args+"&sign="+param.sign+"&version="+param.version+"&method="+param.method;
}

//The naming method of... args is not supported in js, so use the arguments keyword to get the parameter array
function getArgs(){
    return [].slice.call(arguments);
}

//Get display details object 'robot ID', 'robot name', 'policy name', 'next deduction time', 'elapsed time ms',' consumed amount CNY ',' latest active time ',' open '],
function getLogPrientItem(robotDetail){
    var itemArr = new Array();
    var iteArr_index = 0;
    itemArr[iteArr_index++] = robotDetail.id;
    itemArr[iteArr_index++] = robotDetail.name;
    itemArr[iteArr_index++] = robotDetail.strategy_name;
    itemArr[iteArr_index++] = robotDetail.charge_time;
    itemArr[iteArr_index++] = robotDetail.charged;
    itemArr[iteArr_index++] = robotDetail.consumed/1e8;
    itemArr[iteArr_index++] = robotDetail.refresh;
    itemArr[iteArr_index++] = robotDetail.public == 0?"Published":"Unpublished";
    return itemArr;
}

Effect display:

epilogue

In the actual expansion, more and more interesting functions can be realized. For example, use the CommandRobot method to let each robot send heartbeat detection to robot A. if robot a finds that a machine has no heartbeat, but the robot is still running, it can alarm through the FMZ service number. In this way, for example_ C() dead cycle and so on causes the program to feign the dead scene alarm.
I hope that through my introduction, FMZ platform can have more and more interesting functions to be developed and open-source.
Finally, I would like to thank FMZ platform, President Meng, President Chao, President Z and other gods for their support and help. Thank you ~

Topics: JSON