Global
Version
Returns the current system version number.
Version()Examples
javascript
function main() {
Log("version:", Version())
}
python
def main():
Log("version:", Version())
rust
fn main() {
Log!("version:", Version());
}Returns
| Type | Description |
string | The current system version number, for example: |
Remarks
The system version number is the version number of the hosting program (docker/agent).
IsVirtual
Used to determine whether the strategy's runtime environment is the backtesting system.
IsVirtual()Examples
javascript
function main() {
if (IsVirtual()) {
Log("Currently in backtest environment.")
} else {
Log("Currently in live trading environment.")
}
}
python
def main():
if IsVirtual():
Log("Currently in backtest environment.")
else:
Log("Currently in live trading environment.")
rust
fn main() {
if IsVirtual() {
Log!("Currently in backtest environment.");
} else {
Log!("Currently in live trading environment.");
}
}Returns
| Type | Description |
bool | When the strategy runs in the backtesting system environment, it returns a truthy value, for example: |
Remarks
Used to determine whether the current runtime environment is the backtesting system, in order to accommodate the differences between the backtesting and live trading environments.
GetOS
Retrieves the operating system information of the device hosting the bot.
GetOS()Examples
javascript
function main() {
Log("GetOS:", GetOS())
}
python
def main():
Log("GetOS:", GetOS())
rust
fn main() {
Log!("GetOS:", GetOS());
}Returns
| Type | Description |
string | Operating system information. |
Remarks
For example, a bot running on the Mac OS operating system may return darwin/amd64 when calling the GetOS() function. Since Apple computers use various hardware architectures, the return value includes the specific architecture information. Here, darwin is the kernel name of the Mac OS system.
GetPid
Get the ID of the live trading process.
GetPid()Examples
javascript
function main(){
var id = GetPid()
Log(id)
}
python
def main():
id = GetPid()
Log(id)
rust
fn main() {
let id = GetPid();
Log!(id);
}Returns
| Type | Description |
string | Returns the ID of the live trading process. |
GetMeta
Get the Meta value written when generating the strategy registration code.
GetMeta()Examples
Application scenario example: Use Meta to limit the number of assets the strategy can operate.
javascript
function main() {
// The maximum asset value of the quote currency allowed by the strategy
var maxBaseCurrency = null
// Get the metadata when creating the registration code
var level = GetMeta()
// Check the condition corresponding to Meta
if (level == "level1") {
// -1 means no limit
maxBaseCurrency = -1
} else if (level == "level2") {
maxBaseCurrency = 10
} else if (level == "level3") {
maxBaseCurrency = 1
} else {
maxBaseCurrency = 0.5
}
while(1) {
Sleep(1000)
var ticker = exchange.GetTicker()
// Check the asset value
var acc = exchange.GetAccount()
if (maxBaseCurrency != -1 && maxBaseCurrency < acc.Stocks + acc.FrozenStocks) {
// Stop executing the strategy trading logic
LogStatus(_D(), "level:", level, "Position exceeds registration code limit, strategy trading logic will not execute!")
continue
}
// Other trading logic
// Normally output the status bar information
LogStatus(_D(), "level:", level, "Strategy running normally! ticker data:\n", ticker)
}
}
python
def main():
maxBaseCurrency = null
level = GetMeta()
if level == "level1":
maxBaseCurrency = -1
elif level == "level2":
maxBaseCurrency = 10
elif level == "level3":
maxBaseCurrency = 1
else:
maxBaseCurrency = 0.5
while True:
Sleep(1000)
ticker = exchange.GetTicker()
acc = exchange.GetAccount()
if maxBaseCurrency != -1 and maxBaseCurrency < acc["Stocks"] + acc["FrozenStocks"]:
LogStatus(_D(), "level:", level, "Position exceeds registration code limit, strategy trading logic will not execute!")
continue
# Other trading logic
# Normally output the status bar information
LogStatus(_D(), "level:", level, "Strategy running normally! ticker data:\n", ticker)
rust
fn main() {
// The maximum asset value of the quote currency allowed by the strategy
let maxBaseCurrency;
// Get the metadata when creating the registration code, Rust's GetMeta() returns a JsonValue type
let meta = GetMeta();
let level = meta.as_str().unwrap_or("");
// Check the condition corresponding to Meta
if level == "level1" {
// -1 means no limit
maxBaseCurrency = -1.0;
} else if level == "level2" {
maxBaseCurrency = 10.0;
} else if level == "level3" {
maxBaseCurrency = 1.0;
} else {
maxBaseCurrency = 0.5;
}
loop {
Sleep(1000);
let ticker = exchange.GetTicker(None).unwrap();
// Check the asset value
let acc = exchange.GetAccount().unwrap();
if maxBaseCurrency != -1.0 && maxBaseCurrency < acc.Stocks + acc.FrozenStocks {
// Stop executing the strategy trading logic
LogStatus!(_D(None), "level:", level, "Position exceeds registration code limit, strategy trading logic will not execute!");
continue;
}
// Other trading logic
// Normally output the status bar information
LogStatus!(_D(None), "level:", level, "Strategy running normally! ticker data:\n", ticker);
}
}Returns
| Type | Description |
string |
|
Remarks
Application scenario: You need to impose fund restrictions on different strategy lessees. The length of the Meta value set when generating the registration code cannot exceed 190 characters. The GetMeta() function is only supported in live trading and does not work in the backtesting system. If the metadata (Meta) is not set when generating the strategy registration code, the GetMeta() function will return an empty value.
Sleep
The sleep function pauses program execution for a specified period of time.
Sleep(millisecond)Examples
javascript
function main() {
Sleep(1000 * 10) // Wait for 10 seconds
Log("Waited for 10 seconds")
}
python
def main():
Sleep(1000 * 10)
Log("Waited for 10 seconds")
rust
fn main() {
Sleep(1000 * 10); // Wait for 10 seconds
Log!("Waited for 10 seconds");
}Arguments
| Name | Type | Required | Description |
millisecond | number | Yes | The |
Remarks
For example, when executing the Sleep(1000) function, the program will sleep for 1 second. This function supports sleep operations of less than 1 millisecond, such as Sleep(0.1). The minimum supported parameter is 0.000001, i.e. nanosecond-level sleep, where 1 nanosecond equals 1e-6 milliseconds.
When writing strategies in Python, for operations such as polling intervals and time waiting, you should use the Sleep(millisecond) function rather than the time.sleep(second) function from Python's time library. This is because if a strategy uses the time.sleep(second) function during backtesting, it will cause the strategy program to actually wait for a period of time (instead of skipping ahead on the backtesting system's time series), resulting in very slow backtesting speed.
Unix
Get the second-level timestamp of the current moment.
Unix()Examples
javascript
function main() {
var t = Unix()
Log(t)
}
python
def main():
t = Unix()
Log(t)
rust
fn main() {
let t = Unix();
Log!(t);
}Returns
| Type | Description |
number | Returns the second-level timestamp. |
See Also
UnixNano
Get the nanosecond-level timestamp of the current moment.
UnixNano()Examples
If you need to get a millisecond-level timestamp, you can use the following code:
javascript
function main() {
var time = UnixNano() / 1000000
Log(_N(time, 0))
}
python
def main():
time = UnixNano()
Log(time)
rust
fn main() {
let time = UnixNano() / 1000000;
Log!(_N(time, 0));
}Returns
| Type | Description |
number | The |
See Also
_D
Convert a millisecond-level timestamp or a Date object into a time string.
_D()
_D(timestamp)
_D(timestamp, fmt)Examples
-
Get and print the current time string:
javascriptfunction main(){ var time = _D() Log(time) }pythondef main(): strTime = _D() Log(strTime)rustfn main() { let time = _D(None); Log!(time); } -
The timestamp is 1574993606000; convert it with code:
javascriptfunction main() { Log(_D(1574993606000)) }pythondef main(): # Running on a server set to Beijing time, the result is: 2019-11-29 10:13:26; while running this code on a docker on a server in another region gives the result: 2019-11-29 02:13:26 Log(_D(1574993606))rustfn main() { Log!(_D(1574993606000)); } -
Format using the
fmtargument. The format strings forJavaScriptandPythondiffer; please refer to the following examples for details:javascriptfunction main() { Log(_D(1574993606000, "yyyy--MM--dd hh--mm--ss")) // 2019--11--29 10--13--26 }pythondef main(): # 1574993606 is a second-level timestamp Log(_D(1574993606, "%Y--%m--%d %H--%M--%S")) # 2019--11--29 10--13--26rustfn main() { // Rust's _D() function does not support the fmt argument; it only supports the default format: yyyy-MM-dd hh:mm:ss Log!(_D(1574993606000)); // 2019-11-29 10:13:26 }
Returns
| Type | Description |
string | The time string. |
Arguments
| Name | Type | Required | Description |
timestamp | number / object | No | A millisecond-level timestamp or a |
fmt | string | No | The format string. Default format for |
See Also
Remarks
If no argument is passed, the current time string is returned. When using the _D() function in a Python strategy, note that the argument passed in is a second-level timestamp (in JavaScript and Rust strategies it is a millisecond-level timestamp; 1 second equals 1000 milliseconds). When using the _D() function in live trading to parse a timestamp into a readable time string, note the time zone and time settings of the operating system on which the docker (hosting program) runs, because the parsing result of the _D() function depends on the docker system's time.
GetCommand
Get the strategy's interactive command.
GetCommand()Examples
-
Detect interactive commands, and when an interactive command is detected, use the
Logfunction to output it.javascriptfunction main(){ while(true) { var cmd = GetCommand() if (cmd) { Log(cmd) } Sleep(1000) } }pythondef main(): while True: cmd = GetCommand() if cmd: Log(cmd) Sleep(1000)rustfn main() { loop { // Rust's GetCommand() requires a timeout parameter (milliseconds) and returns Option<String>, which is None when there is no command if let Some(cmd) = GetCommand(0) { Log!(cmd); } Sleep(1000); } } -
For example, in the strategy's interactive controls, add a control without an input box, name it
buy, with the control descriptionBuy; this is a button control. Then add a control with an input box, name itsell, with the control descriptionSell; this is an interactive control composed of a button and an input box. Write interactive code in the strategy to respond to the different interactive controls:javascriptfunction main() { while (true) { LogStatus(_D()) var cmd = GetCommand() if (cmd) { Log("cmd:", cmd) var arr = cmd.split(":") if (arr[0] == "buy") { Log("Buy, this control has no quantity") } else if (arr[0] == "sell") { Log("Sell, this control has quantity:", arr[1]) } else { Log("Other control triggered:", arr) } } Sleep(1000) } }pythondef main(): while True: LogStatus(_D()) cmd = GetCommand() if cmd: Log("cmd:", cmd) arr = cmd.split(":") if arr[0] == "buy": Log("Buy, this control has no quantity") elif arr[0] == "sell": Log("Sell, this control has quantity:", arr[1]) else: Log("Other control triggered:", arr) Sleep(1000)rustfn main() { loop { LogStatus!(_D(None)); if let Some(cmd) = GetCommand(0) { Log!("cmd:", cmd); let arr: Vec<&str> = cmd.split(':').collect(); if arr[0] == "buy" { Log!("Buy, this control has no quantity"); } else if arr[0] == "sell" { Log!("Sell, this control has quantity:", arr[1]); } else { Log!("Other control triggered:", arr); } } Sleep(1000); } }
Returns
| Type | Description |
string | The returned command format is |
Remarks
This function is invalid in the backtesting system.
GetLastError
Retrieves the most recent error message.
GetLastError()Examples
javascript
function main(){
// Since order number 123 does not exist, this will trigger an error
exchange.GetOrder("123")
var error = GetLastError()
Log(error)
}
python
def main():
exchange.GetOrder("123")
error = GetLastError()
Log(error)
rust
fn main() {
// Since order number 123 does not exist, this will trigger an error
// Rust's GetOrder accepts a &OrderId parameter; the string id must be placed in the S field
let id = OrderId { S: "123".to_string(), ..Default::default() };
let _ = exchange.GetOrder(&id);
let error = GetLastError();
Log!(error);
}Returns
| Type | Description |
string | The most recent error message. |
Remarks
This function does not work in the backtesting system.
SetErrorFilter
Filters error logs.
SetErrorFilter(filters)Examples
-
Filter common errors.
javascriptfunction main() { SetErrorFilter("502:|503:|tcp|character|unexpected|network|timeout|WSARecv|Connect|GetAddr|no such|reset|http|received|EOF|reused") }pythondef main(): SetErrorFilter("502:|503:|tcp|character|unexpected|network|timeout|WSARecv|Connect|GetAddr|no such|reset|http|received|EOF|reused")rustfn main() { SetErrorFilter("502:|503:|tcp|character|unexpected|network|timeout|WSARecv|Connect|GetAddr|no such|reset|http|received|EOF|reused"); } -
Filter error messages from a specific interface.
javascriptfunction main() { // Query a non-existent order (id 123) to deliberately trigger an interface error var order = exchange.GetOrder("123") Log(order) // Filter http 502 errors and GetOrder interface errors; after setting the error filter, the second call to GetOrder will no longer report an error SetErrorFilter("502:|GetOrder") order = exchange.GetOrder("123") Log(order) }pythondef main(): order = exchange.GetOrder("123") Log(order) SetErrorFilter("502:|GetOrder") order = exchange.GetOrder("123") Log(order)rustfn main() { // Query a non-existent order (id 123) to deliberately trigger an interface error let orderId = OrderId { S: "123".to_string(), ..Default::default() }; let order = exchange.GetOrder(&orderId); Log!(order); // Filter http 502 errors and GetOrder interface errors; after setting the error filter, the second call to GetOrder will no longer report an error SetErrorFilter("502:|GetOrder"); let order = exchange.GetOrder(&orderId); Log!(order); }
Arguments
| Name | Type | Required | Description |
filters | string | Yes | A regular expression string. |
Remarks
Error logs that match this regular expression will no longer be uploaded to the logging system. This function can be called multiple times (with no limit on the number of calls) to set multiple filter conditions; regular expressions set across multiple calls accumulate and take effect simultaneously. You can pass an empty string to reset the regular expression used to filter error logs: SetErrorFilter(""). Filtered logs will no longer be written to the database file corresponding to the live trading Id under the docker directory, thereby preventing the database file from bloating due to frequent errors.
_N
Format a floating-point number.
_N()
_N(num)
_N(num, precision)Examples
-
For example,
_N(3.1415, 2)keeps3.1415to two decimal places, removes the remaining digits, and the function returns3.14.javascriptfunction main(){ var i = 3.1415 Log(i) var ii = _N(i, 2) Log(ii) }pythondef main(): i = 3.1415 Log(i) ii = _N(i, 2) Log(ii)rustfn main() { let i = 3.1415; Log!(i); let ii = _N(i, 2); Log!(ii); } -
If you need to set the N digits to the left of the decimal point all to 0, you can write it like this:
javascriptfunction main(){ var i = 1300 Log(i) var ii = _N(i, -3) // Check the log and you will see it is 1000 Log(ii) }pythondef main(): i = 1300 Log(i) ii = _N(i, -3) Log(ii)rustfn main() { let i = 1300; Log!(i); let ii = _N(i, -3); // Check the log and you will see it is 1000 Log!(ii); }
Returns
| Type | Description |
number | The floating-point number formatted according to the precision setting. |
Arguments
| Name | Type | Required | Description |
num | number | Yes | The floating-point number to be formatted. |
precision | number | No | Used to set the formatting precision. The parameter |
See Also
Remarks
The parameter precision can be a positive integer or a negative integer.
_C
A retry function used for fault-tolerant handling of interface calls.
_C(pfn)
_C(pfn, ...args)Examples
-
Apply fault-tolerant handling to a function without parameters:
javascriptfunction main(){ var ticker = _C(exchange.GetTicker) // Change the retry interval of the _C() function to 2 seconds _CDelay(2000) var depth = _C(exchange.GetDepth) Log(ticker) Log(depth) }pythondef main(): ticker = _C(exchange.GetTicker) _CDelay(2000) depth = _C(exchange.GetDepth) Log(ticker) Log(depth)rustfn main() { let ticker = _C!(exchange.GetTicker(None)); // Change the retry interval of the _C!() macro to 2 seconds _CDelay(2000); let depth = _C!(exchange.GetDepth(None)); Log!(ticker); Log!(depth); } -
Apply fault-tolerant handling to a function with parameters:
javascriptfunction main(){ var records = _C(exchange.GetRecords, PERIOD_D1) Log(records) }pythondef main(): records = _C(exchange.GetRecords, PERIOD_D1) Log(records)rustfn main() { let records = _C!(exchange.GetRecords(None, PERIOD_D1, None)); Log!(records); } -
It can also be used to apply fault-tolerant handling to custom functions:
javascriptvar test = function(a, b){ var time = new Date().getTime() / 1000 if(time % b == 3){ Log("Condition met!", "#FF0000") return true } Log("Retrying!", "#FF0000") return false } function main(){ var ret = _C(test, 1, 5) Log(ret) }pythonimport time def test(a, b): ts = time.time() if ts % b == 3: Log("Condition met!", "#FF0000") return True Log("Retrying!", "#FF0000") return False def main(): ret = _C(test, 1, 5) Log(ret)rustfn test(a: i64, b: i64) -> Result<bool> { let time = Unix(); if time % b == 3 { Log!("Condition met!", "#FF0000"); return Ok(true); } Log!("Retrying!", "#FF0000"); Err(Error::Api("retry".to_string())) } fn main() { // In Rust, a custom function can use the _C! macro for fault tolerance as long as it returns a Result type; it will retry when Err is returned let ret = _C!(test(1, 5)); Log!(ret); }
Returns
| Type | Description |
All types supported by the platform except false values and null values (any). | The return value after the callback function is executed. |
Arguments
| Name | Type | Required | Description |
pfn | function | Yes | The parameter |
arg | string / number / bool / object / array / function / any (any type supported by the platform) | No | The parameters of the callback function. There can be multiple |
Remarks
The _C() function repeatedly calls the specified function until it returns successfully (when the function referenced by the parameter pfn returns a null value or a false value upon being called, the call to pfn will be retried).
For example, _C(exchange.GetTicker). The default retry interval is 3 seconds, and you can call the _CDelay() function to set the retry interval.
For example, _CDelay(1000) means changing the retry interval of the _C() function to 1 second.
Fault-tolerant handling can be applied to the following functions (but is not limited to them):
exchange.GetTicker()exchange.GetDepth()exchange.GetTrades()exchange.GetRecords()exchange.GetAccount()exchange.GetOrders()exchange.GetOrder()exchange.GetPositions()
All of the above functions can be called through the _C() function to achieve fault tolerance. The fault tolerance of the _C() function is not limited to the functions listed above. Please note that the parameter pfn is a function reference rather than a function call, i.e. it should be written as _C(exchange.GetTicker), not _C(exchange.GetTicker()).
_Cross
Returns the number of crossover periods between array arr1 and array arr2.
_Cross(arr1, arr2)Examples
You can simulate a set of data to test the _Cross(Arr1, Arr2) function:
javascript
// Fast line indicator
var arr1 = [1,2,3,4,5,6,8,8,9]
// Slow line indicator
var arr2 = [2,3,4,5,6,7,7,7,7]
function main(){
Log("_Cross(arr1, arr2) : ", _Cross(arr1, arr2))
Log("_Cross(arr2, arr1) : ", _Cross(arr2, arr1))
}
python
arr1 = [1,2,3,4,5,6,8,8,9]
arr2 = [2,3,4,5,6,7,7,7,7]
def main():
Log("_Cross(arr1, arr2) : ", _Cross(arr1, arr2))
Log("_Cross(arr2, arr1) : ", _Cross(arr2, arr1))
rust
fn main() {
// Fast line indicator
let arr1 = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 8.0, 8.0, 9.0];
// Slow line indicator
let arr2 = [2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 7.0, 7.0, 7.0];
Log!("_Cross(arr1, arr2) : ", _Cross(&arr1, &arr2));
Log!("_Cross(arr2, arr1) : ", _Cross(&arr2, &arr1));
}Returns
| Type | Description |
number | The number of crossover periods between array |
Arguments
| Name | Type | Required | Description |
arr1 | array | Yes | An array whose elements are of type |
arr2 | array | Yes | An array whose elements are of type |
Remarks
When the return value of the _Cross() function is positive, it indicates the number of periods since the upward cross (golden cross); when negative, it indicates the number of periods since the downward cross (death cross); when 0, it indicates that the current prices are equal. For detailed usage instructions, please refer to: Analysis and Usage Instructions for the Built-in Function _Cross.
JSON.parse
The JSON.parse function is a method of the ECMAScript standard built-in object JSON, used to decode (parse) a JSON string. The FMZ Quant Trading Platform has extended it with an additional parameter safeStr on this basis.
JSON.parse(s)
JSON.parse(s, safeStr)Examples
Decode (parse) a JSON string containing a large numeric value.
javascript
function main() {
let s1 = '{"num": 8754613216564987646512354656874651651358}'
Log("JSON.parse:", JSON.parse(s1)) // JSON.parse: {"num":8.754613216564987e+39}
Log("JSON.parse:", JSON.parse(s1, true)) // JSON.parse: {"num":"8754613216564987646512354656874651651358"}
let s2 = '{"num": 123}'
Log("JSON.parse:", JSON.parse(s2)) // JSON.parse: {"num":123}
Log("JSON.parse:", JSON.parse(s2, true)) // JSON.parse: {"num":123}
}
python
# You can use Python's third-party libraries to handle large numeric data.
rust
fn main() {
// Rust uses the JSONParse() function to parse JSON strings, without the safeStr parameter
// Large numeric values that exceed the precision range will be parsed as f64, which may lose precision
let s1 = r#"{"num": 8754613216564987646512354656874651651358}"#;
Log!("JSONParse:", JSONParse(s1).unwrap()["num"].as_f64().unwrap_or(0.0)); // JSONParse: 8.754613216564987e39
let s2 = r#"{"num": 123}"#;
Log!("JSONParse:", JSONParse(s2).unwrap()["num"].as_f64().unwrap_or(0.0)); // JSONParse: 123
}Returns
| Type | Description |
object | The return value is a |
Arguments
| Name | Type | Required | Description |
s | string | Yes | This parameter is the |
safeStr | bool | No | When this parameter is set to |
Remarks
The JSON.parse() function can correctly parse JSON strings containing large numeric values; when the safeStr parameter is set to a truthy value, large numeric values will be parsed as the string type.
The safeStr parameter position also supports passing in a reviver parameter, i.e. a function used to transform the result, which is called once for each member of the object; for specific usage, please refer to the relevant materials, which will not be elaborated here.
Only the JavaScript language is supported.
The safeStr parameter feature of the JSON.parse() function is not supported in the backtesting system.
JSON.stringify
The JSON.stringify function is a method of the ECMAScript standard built-in object JSON, used to convert JavaScript values to JSON strings.
JSON.stringify(obj)Examples
Serialize an object to a JSON string and output it.
javascript
function main() {
let s1 = {"num": "8754613216564987646512354656874651651358"}
Log("JSON.stringify:", JSON.stringify(s1))
// JSON.stringify: {"num":"8754613216564987646512354656874651651358"}
// The variable returned by JSON.stringify(s1) is of string type
}
python
// OmittedReturns
| Type | Description |
string | Returns the serialized |
Arguments
| Name | Type | Required | Description |
obj | string / number / bool / object / array / function / any (any type supported by the platform) | Yes | The value to be serialized into a JSON string. |
Remarks
Only supported in JavaScript language.
Encode
This function encodes data according to the parameters passed in.
Encode(algo, inputFormat, outputFormat, data)
Encode(algo, inputFormat, outputFormat, data, keyFormat, key)Examples
-
Example of calling the Encode function.
javascriptfunction main() { Log(Encode("raw", "raw", "hex", "example", "raw", "123")) // 6578616d706c65 Log(Encode("raw", "raw", "hex", "example")) // 6578616d706c65 Log(Encode("sha256", "raw", "hex", "example", "raw", "123")) // 698d54f0494528a759f19c8e87a9f99e75a5881b9267ee3926bcf62c992d84ba Log(Encode("sha256", "raw", "hex", "example", "", "123")) // 50d858e0985ecc7f60418aaf0cc5ab587f42c2570a884095a9e8ccacd0f6545c Log(Encode("sha256", "raw", "hex", "example", null, "123")) // 50d858e0985ecc7f60418aaf0cc5ab587f42c2570a884095a9e8ccacd0f6545c Log(Encode("sha256", "raw", "hex", "example", "string", "123")) // 698d54f0494528a759f19c8e87a9f99e75a5881b9267ee3926bcf62c992d84ba Log(Encode("raw", "raw", "hex", "123")) // 313233 Log(Encode("raw", "raw", "base64", "123")) // MTIz Log(Encode("sha256", "raw", "hex", "example", "hex", "313233")) // 698d54f0494528a759f19c8e87a9f99e75a5881b9267ee3926bcf62c992d84ba Log(Encode("sha256", "raw", "hex", "example", "base64", "MTIz")) // 698d54f0494528a759f19c8e87a9f99e75a5881b9267ee3926bcf62c992d84ba }pythondef main(): Log(Encode("raw", "raw", "hex", "example", "raw", "123")) # 6578616d706c65 Log(Encode("raw", "raw", "hex", "example", "", "")) # 6578616d706c65 Log(Encode("sha256", "raw", "hex", "example", "raw", "123")) # 698d54f0494528a759f19c8e87a9f99e75a5881b9267ee3926bcf62c992d84ba Log(Encode("sha256", "raw", "hex", "example", "", "123")) # 50d858e0985ecc7f60418aaf0cc5ab587f42c2570a884095a9e8ccacd0f6545c Log(Encode("sha256", "raw", "hex", "example", "string", "123")) # 698d54f0494528a759f19c8e87a9f99e75a5881b9267ee3926bcf62c992d84ba Log(Encode("raw", "raw", "hex", "123", "", "")) # 313233 Log(Encode("raw", "raw", "base64", "123", "", "")) # MTIz Log(Encode("sha256", "raw", "hex", "example", "hex", "313233")) # 698d54f0494528a759f19c8e87a9f99e75a5881b9267ee3926bcf62c992d84ba Log(Encode("sha256", "raw", "hex", "example", "base64", "MTIz")) # 698d54f0494528a759f19c8e87a9f99e75a5881b9267ee3926bcf62c992d84barustfn main() { // In Rust, all 6 parameters of the Encode() function are required; when not encrypting, simply pass empty strings for keyFormat and key Log!(Encode("raw", "raw", "hex", "example", "raw", "123")); // 6578616d706c65 Log!(Encode("raw", "raw", "hex", "example", "", "")); // 6578616d706c65 Log!(Encode("sha256", "raw", "hex", "example", "raw", "123")); // 698d54f0494528a759f19c8e87a9f99e75a5881b9267ee3926bcf62c992d84ba Log!(Encode("sha256", "raw", "hex", "example", "", "123")); // 50d858e0985ecc7f60418aaf0cc5ab587f42c2570a884095a9e8ccacd0f6545c Log!(Encode("sha256", "raw", "hex", "example", "string", "123")); // 698d54f0494528a759f19c8e87a9f99e75a5881b9267ee3926bcf62c992d84ba Log!(Encode("raw", "raw", "hex", "123", "", "")); // 313233 Log!(Encode("raw", "raw", "base64", "123", "", "")); // MTIz Log!(Encode("sha256", "raw", "hex", "example", "hex", "313233")); // 698d54f0494528a759f19c8e87a9f99e75a5881b9267ee3926bcf62c992d84ba Log!(Encode("sha256", "raw", "hex", "example", "base64", "MTIz")); // 698d54f0494528a759f19c8e87a9f99e75a5881b9267ee3926bcf62c992d84ba } -
The parameter
algoalso supports the following values: "text.encoder.utf8", "text.decoder.utf8", "text.encoder.gbk", "text.decoder.gbk", which are used to encode and decode strings.javascriptfunction main(){ var ret1 = Encode("text.encoder.utf8", "raw", "hex", "你好") // e4bda0e5a5bd Log(ret1) var ret2 = Encode("text.decoder.utf8", "hex", "string", ret1) Log(ret2) var ret3 = Encode("text.encoder.gbk", "raw", "hex", "你好") // c4e3bac3 Log(ret3) var ret4 = Encode("text.decoder.gbk", "hex", "string", ret3) Log(ret4) }pythondef main(): ret1 = Encode("text.encoder.utf8", "raw", "hex", "你好", "", "") # e4bda0e5a5bd Log(ret1) ret2 = Encode("text.decoder.utf8", "hex", "string", ret1, "", "") Log(ret2) ret3 = Encode("text.encoder.gbk", "raw", "hex", "你好", "", "") # c4e3bac3 Log(ret3) ret4 = Encode("text.decoder.gbk", "hex", "string", ret3, "", "") Log(ret4)rustfn main() { // In Rust, all 6 parameters of the Encode() function are required; when not encrypting, pass empty strings for keyFormat and key let ret1 = Encode("text.encoder.utf8", "raw", "hex", "你好", "", ""); // e4bda0e5a5bd Log!(ret1); let ret2 = Encode("text.decoder.utf8", "hex", "string", &ret1, "", ""); Log!(ret2); let ret3 = Encode("text.encoder.gbk", "raw", "hex", "你好", "", ""); // c4e3bac3 Log!(ret3); let ret4 = Encode("text.decoder.gbk", "hex", "string", &ret3, "", ""); Log!(ret4); }
Returns
| Type | Description |
string | The |
Arguments
| Name | Type | Required | Description |
algo | string | Yes | The The The |
inputFormat | string | Yes | Used to specify the data format of the |
outputFormat | string | Yes | Used to specify the output data format. The |
data | string | Yes | The |
keyFormat | string | No | Used to specify the data format of the |
key | string | No | The When the When the |
Remarks
The Encode() function is only supported in live trading. If the key and keyFormat parameters are not passed in, no key encryption is performed.
MD5
Calculate the MD5 hash of the parameter data.
MD5(data)Examples
javascript
function main() {
Log("MD5", MD5("hello world"))
}
python
def main():
Log("MD5", MD5("hello world"))
rust
fn main() {
Log!("MD5", MD5("hello world"));
}Returns
| Type | Description |
string | The MD5 hash value. |
Arguments
| Name | Type | Required | Description |
data | string | Yes | The data on which to perform the MD5 calculation. |
See Also
Remarks
After calling the MD5("hello world") function, the return value is: 5eb63bbbe01eeed093cb22bb8f5acdc3.
UUID
Create a UUID.
UUID()Examples
javascript
function main() {
var uuid1 = UUID()
var uuid2 = UUID()
Log(uuid1, uuid2)
}
python
def main():
uuid1 = UUID()
uuid2 = UUID()
Log(uuid1, uuid2)
rust
fn main() {
let uuid1 = UUID();
let uuid2 = UUID();
Log!(uuid1, uuid2);
}Returns
| Type | Description |
string | A 32-bit UUID. |
Remarks
The UUID() function is only supported in live trading.