Type/to search
Built-in Functions
Global
Version
IsVirtual
GetOS
GetPid
GetMeta
Sleep
Unix
UnixNano
_D
GetCommand
GetLastError
SetErrorFilter
_N
_C
_Cross
JSON.parse
JSON.stringify
Encode
MD5
UUID
Log
Market
Trade
Account
Futures
Exchange
IO
Network
Storage
Threads
Web3
Uniswap
TA
Talib
OverlapStudies
MomentumIndicators
VolumeIndicators
VolatilityIndicators
CycleIndicators
PriceTransform
StatisticFunctions
MathTransform
MathOperators
PatternRecognition
OS
Structures
Built-in Variables

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

TypeDescription

string

The current system version number, for example: 3.6.

Remarks

The system version number is the version number of the hosting program (docker/agent).

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

TypeDescription

bool

When the strategy runs in the backtesting system environment, it returns a truthy value, for example: true; when the strategy runs in the live trading environment, it returns a falsy value, for example: false.

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.

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

TypeDescription

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.

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

TypeDescription

string

Returns the ID of the live trading process.

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

TypeDescription

string

Meta data.

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.

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

NameTypeRequiredDescription

millisecond

number

Yes

The millisecond parameter is used to set the sleep duration, in milliseconds.

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.

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

TypeDescription

number

Returns the second-level timestamp.

See Also

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

TypeDescription

number

The UnixNano() function returns a nanosecond-level timestamp.

See Also

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:

    javascript
    function main(){ var time = _D() Log(time) }
    python
    def main(): strTime = _D() Log(strTime)
    rust
    fn main() { let time = _D(None); Log!(time); }
  • The timestamp is 1574993606000; convert it with code:

    javascript
    function main() { Log(_D(1574993606000)) }
    python
    def 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))
    rust
    fn main() { Log!(_D(1574993606000)); }
  • Format using the fmt argument. The format strings for JavaScript and Python differ; please refer to the following examples for details:

    javascript
    function main() { Log(_D(1574993606000, "yyyy--MM--dd hh--mm--ss")) // 2019--11--29 10--13--26 }
    python
    def main(): # 1574993606 is a second-level timestamp Log(_D(1574993606, "%Y--%m--%d %H--%M--%S")) # 2019--11--29 10--13--26
    rust
    fn 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

TypeDescription

string

The time string.

Arguments

NameTypeRequiredDescription

timestamp

number / object

No

A millisecond-level timestamp or a Date object.

fmt

string

No

The format string. Default format for JavaScript: yyyy-MM-dd hh:mm:ss; default format for Python: %Y-%m-%d %H:%M:%S.

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.

Get the strategy's interactive command.

GetCommand()

Examples

  • Detect interactive commands, and when an interactive command is detected, use the Log function to output it.

    javascript
    function main(){ while(true) { var cmd = GetCommand() if (cmd) { Log(cmd) } Sleep(1000) } }
    python
    def main(): while True: cmd = GetCommand() if cmd: Log(cmd) Sleep(1000)
    rust
    fn 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 description Buy; this is a button control. Then add a control with an input box, name it sell, with the control description Sell; 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:

    javascript
    function 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) } }
    python
    def 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)
    rust
    fn 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

TypeDescription

string

The returned command format is ControlName:Data, where ControlName is the name of the control and Data is the data entered in the control. If the interactive control does not contain input components such as an input box or dropdown box (for example, a button control without an input box), then the returned command format is ControlName, i.e. only the control name is returned.

Remarks

This function is invalid in the backtesting system.

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

TypeDescription

string

The most recent error message.

Remarks

This function does not work in the backtesting system.

Filters error logs.

SetErrorFilter(filters)

Examples

  • Filter common errors.

    javascript
    function main() { SetErrorFilter("502:|503:|tcp|character|unexpected|network|timeout|WSARecv|Connect|GetAddr|no such|reset|http|received|EOF|reused") }
    python
    def main(): SetErrorFilter("502:|503:|tcp|character|unexpected|network|timeout|WSARecv|Connect|GetAddr|no such|reset|http|received|EOF|reused")
    rust
    fn 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.

    javascript
    function 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) }
    python
    def main(): order = exchange.GetOrder("123") Log(order) SetErrorFilter("502:|GetOrder") order = exchange.GetOrder("123") Log(order)
    rust
    fn 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

NameTypeRequiredDescription

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.

Format a floating-point number.

_N()
_N(num)
_N(num, precision)

Examples

  • For example, _N(3.1415, 2) keeps 3.1415 to two decimal places, removes the remaining digits, and the function returns 3.14.

    javascript
    function main(){ var i = 3.1415 Log(i) var ii = _N(i, 2) Log(ii) }
    python
    def main(): i = 3.1415 Log(i) ii = _N(i, 2) Log(ii)
    rust
    fn 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:

    javascript
    function main(){ var i = 1300 Log(i) var ii = _N(i, -3) // Check the log and you will see it is 1000 Log(ii) }
    python
    def main(): i = 1300 Log(i) ii = _N(i, -3) Log(ii)
    rust
    fn main() { let i = 1300; Log!(i); let ii = _N(i, -3); // Check the log and you will see it is 1000 Log!(ii); }

Returns

TypeDescription

number

The floating-point number formatted according to the precision setting.

Arguments

NameTypeRequiredDescription

num

number

Yes

The floating-point number to be formatted.

precision

number

No

Used to set the formatting precision. The parameter precision is an integer, with a default value of 4.

See Also

Remarks

The parameter precision can be a positive integer or a negative integer.

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:

    javascript
    function 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) }
    python
    def main(): ticker = _C(exchange.GetTicker) _CDelay(2000) depth = _C(exchange.GetDepth) Log(ticker) Log(depth)
    rust
    fn 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:

    javascript
    function main(){ var records = _C(exchange.GetRecords, PERIOD_D1) Log(records) }
    python
    def main(): records = _C(exchange.GetRecords, PERIOD_D1) Log(records)
    rust
    fn 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:

    javascript
    var 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) }
    python
    import 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)
    rust
    fn 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

TypeDescription

All types supported by the platform except false values and null values (any).

The return value after the callback function is executed.

Arguments

NameTypeRequiredDescription

pfn

function

Yes

The parameter pfn is a function reference, i.e. a callback function.

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 arg parameters. The type and number of the arg parameters are determined by the parameters of the callback function.

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()).

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

TypeDescription

number

The number of crossover periods between array arr1 and array arr2.

Arguments

NameTypeRequiredDescription

arr1

array

Yes

An array whose elements are of type number.

arr2

array

Yes

An array whose elements are of type number.

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.

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

TypeDescription

object

The return value is a JSON object.

Arguments

NameTypeRequiredDescription

s

string

Yes

This parameter is the JSON string that needs to be decoded (parsed).

safeStr

bool

No

When this parameter is set to true, if a value that may exceed the precision range is encountered during parsing, it will be returned as a string to avoid precision loss or numeric overflow issues.

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.

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
// Omitted

Returns

TypeDescription

string

Returns the serialized JSON string.

Arguments

NameTypeRequiredDescription

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.

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.

    javascript
    function 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 }
    python
    def 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")) # 698d54f0494528a759f19c8e87a9f99e75a5881b9267ee3926bcf62c992d84ba
    rust
    fn 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 algo also supports the following values: "text.encoder.utf8", "text.decoder.utf8", "text.encoder.gbk", "text.decoder.gbk", which are used to encode and decode strings.

    javascript
    function 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) }
    python
    def 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)
    rust
    fn 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

TypeDescription

string

The Encode function returns the encoded and encrypted data.

Arguments

NameTypeRequiredDescription

algo

string

Yes

The algo parameter is used to specify the algorithm used in the encoding computation. It supports being set to one of the following values: "raw" (no algorithm used), "sign", "signTx", "md4", "md5", "sha256", "sha512", "sha1", "keccak256", "sha3.224", "sha3.256", "sha3.384", "sha3.512", "sha3.keccak256", "sha3.keccak512", "sha512.384", "sha512.256", "sha512.224", "ripemd160", "blake2b.256", "blake2b.512", "blake2s.128", "blake2s.256".

The algo parameter also supports "text.encoder.utf8", "text.decoder.utf8", "text.encoder.gbk", "text.decoder.gbk", which are used to encode or decode strings.

The algo parameter also supports the "ed25519" algorithm, which can be used in combination with different hash algorithms. For example, the algo parameter can be written as "ed25519.md5", "ed25519.sha512", etc., and ed25519.seed computation is also supported.

inputFormat

string

Yes

Used to specify the data format of the data parameter. The inputFormat parameter supports being set to one of "raw", "hex", "base64", "string". "raw" indicates raw data, "hex" indicates hex-encoded data, "base64" indicates base64-encoded data, and "string" indicates string data.

outputFormat

string

Yes

Used to specify the output data format. The outputFormat parameter supports being set to one of "raw", "hex", "base64", "string". "raw" indicates raw data, "hex" indicates hex-encoded data, "base64" indicates base64-encoded data, and "string" indicates string data.

data

string

Yes

The data parameter is the data to be processed.

keyFormat

string

No

Used to specify the data format of the key parameter. The keyFormat parameter supports being set to one of "raw", "hex", "base64", "string". "raw" indicates raw data, "hex" indicates hex-encoded data, "base64" indicates base64-encoded data, and "string" indicates string data.

key

string

No

The key parameter is the key used for HMAC encryption.

When the algo parameter is set to "sign" or "signTx", the key parameter must be passed in.

When the algo parameter is set to "raw", the key parameter is not used for HMAC encryption (because HMAC encryption must specify an algorithm).

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.

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

TypeDescription

string

The MD5 hash value.

Arguments

NameTypeRequiredDescription

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.

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

TypeDescription

string

A 32-bit UUID.

Remarks

The UUID() function is only supported in live trading.