Type/to search
Built-in Functions
Global
Log
Market
Trade
Account
Futures
Exchange
IO
Network
HttpQuery
HttpQuery_Go
Dial
Mail
Mail_Go
Storage
Threads
TA
Talib
OS
Structures
Built-in Variables and Constants
Conventions
Exchanges

Used for raw Socket access, supporting the tcp and tls (also written as ssl) protocols as well as the WebSocket ws and wss protocols. Also supports connecting to databases, with supported databases including: sqlite3, mysql, postgres, and clickhouse.

Dial(address)
Dial(address, timeout)
Dial(address, options)

Examples

  • Dial function call example.

    javascript
    function main(){ // Dial supports the tcp:// and tls:// protocols as well as ws:// and wss://; for tcp:// and // tls:// an extra parameter specifies the timeout in seconds var client = Dial("tls://www.baidu.com:443") if (client) { // write can take an additional numeric parameter to specify a timeout, and returns the // number of bytes successfully sent client.write("GET / HTTP/1.1\nConnection: Closed\n\n") while (true) { // read can take an additional numeric parameter to specify a timeout, in milliseconds; // returning null indicates an error, timeout, or that the socket has been closed var buf = client.read() if (!buf) { break } Log(buf) } client.close() } }
    python
    def main(): client = Dial("tls://www.baidu.com:443") if client: client.write("GET / HTTP/1.1\nConnection: Closed\n\n") while True: buf = client.read() if not buf: break Log(buf) client.close()
    rust
    fn main() { // Dial supports the tcp:// and tls:// protocols as well as ws:// and wss://; for tcp:// and // tls:// you can use Dial::new(addr, timeout) to specify the timeout in seconds let mut client = Dial("tls://www.baidu.com:443"); if client.Valid() { // The second numeric parameter of write is used to specify a timeout, and it returns the // number of bytes successfully sent client.write("GET / HTTP/1.1\nConnection: Closed\n\n", 0); loop { // The numeric parameter of read is used to specify a timeout, in milliseconds; // returning an empty string indicates an error, timeout, or that the socket has been // closed let buf = client.read(0); if buf == "" { break; } Log!(buf); } client.close(); } }
  • Access Binance's WebSocket market data interface.

    javascript
    function main() { LogStatus("Connecting...") // Access Binance's WebSocket interface var client = Dial("wss://stream.binance.com:9443/ws/!ticker@arr") if (!client) { Log("Connection failed, exiting") return } while (true) { // read only returns data received after read is called var buf = client.read() if (!buf) { break } var table = { type: 'table', title: 'Market Chart', cols: ['Symbol', 'High', 'Low', 'Bid', 'Ask', 'Last Price', 'Volume', 'Update Time'], rows: [] } var obj = JSON.parse(buf) Object.values(obj).forEach(function(ticker) { table.rows.push([ticker.s, ticker.h, ticker.l, ticker.b, ticker.a, ticker.c, ticker.q, _D(ticker.E)]) }) LogStatus('`' + JSON.stringify(table) + '`') } client.close() }
    python
    import json def main(): LogStatus("Connecting...") client = Dial("wss://stream.binance.com:9443/ws/!ticker@arr") if not client: Log("Connection failed, exiting") return while True: buf = client.read() if not buf: break table = { "type" : "table", "title" : "Market Chart", "cols" : ["Symbol", "High", "Low", "Bid", "Ask", "Last Price", "Volume", "Update Time"], "rows" : [] } obj = json.loads(buf) for i in range(len(obj)): table["rows"].append([obj[i]["s"], obj[i]["h"], obj[i]["l"], obj[i]["b"], obj[i]["a"], obj[i]["c"], obj[i]["q"], _D(int(obj[i]["E"]) / 1000)]) LogStatus('`' + json.dumps(table) + '`') client.close()
    rust
    fn main() { LogStatus!("Connecting..."); // Access Binance's WebSocket interface let mut client = Dial("wss://stream.binance.com:9443/ws/!ticker@arr"); if !client.Valid() { Log!("Connection failed, exiting"); return; } loop { // read only returns data received after read is called let buf = client.read(0); if buf == "" { break; } let obj = JSONParse(&buf).unwrap(); // The Rust SDK has no JSON serialization; here we use string concatenation to build the // JSON text for the status bar table let mut rows = String::new(); if let Some(arr) = obj.as_array() { for ticker in arr { if !rows.is_empty() { rows += ","; } rows += &format!(r#"["{}","{}","{}","{}","{}","{}","{}","{}"]"#, ticker["s"].as_str().unwrap_or(""), ticker["h"].as_str().unwrap_or(""), ticker["l"].as_str().unwrap_or(""), ticker["b"].as_str().unwrap_or(""), ticker["a"].as_str().unwrap_or(""), ticker["c"].as_str().unwrap_or(""), ticker["q"].as_str().unwrap_or(""), _D(ticker["E"].as_i64().unwrap_or(0))); } } let table = format!(r#"{{"type":"table","title":"Market Chart","cols":["Symbol","High","Low","Bid","Ask","Last Price","Volume","Update Time"],"rows":[{}]}}"#, rows); LogStatus!(format!("`{}`", table)); } client.close(); }
  • Connect to an sqlite3 database and execute SQL statements with the exec() method of the connection object (see Dial-return).

    javascript
    var client = null function main() { // client = Dial("sqlite3://:memory:") // Use an in-memory database // Open/connect to the database file in the live trading directory client = Dial("sqlite3://test1.db") // Query the tables in the database var ret = client.exec("SELECT name FROM sqlite_master WHERE type='table'") Log(ret) } function onexit() { Log("Executing client.close()") client.close() }
    python
    client = None def main(): global client # client = Dial("sqlite3://:memory:") # Use an in-memory database # Open/connect to the database file in the live trading directory client = Dial("sqlite3://test1.db") # Query the tables in the database ret = client.exec("SELECT name FROM sqlite_master WHERE type='table'") Log(ret) def onexit(): Log("Executing client.close()") client.close()
    rust
    fn main() { // let mut client = Dial("sqlite3://:memory:"); // Use an in-memory database // Open/connect to the database file in the live trading directory let mut client = Dial("sqlite3://test1.db"); // Rust's connection object does not support the fd() method // Query the tables in the database let ret = client.exec("SELECT name FROM sqlite_master WHERE type='table'"); Log!(format!("{:?}", ret)); Log!("Executing client.close()"); client.close(); }

Returns

TypeDescription

object

A connection object with read(), write(), close() and other methods (database connections also have exec()), see Dial-return. When the connection fails (for example on timeout) a null value is returned and an error is logged (Rust returns a connection object whose Valid() is false).

Arguments

NameTypeRequiredDescription

address

string

Yes

The request address.

timeout

number

No

The connection timeout. For ws and wss it is in milliseconds (values less than 100 are treated as seconds); for tcp and tls it is in seconds. When set to 0, the default timeout is used. In JavaScript and Python, it is 30 (i.e. 30 seconds) when this parameter is omitted. In Rust, Dial(address) uses the default timeout; to specify a timeout use Dial::new(address, timeout), where timeout has the same units as above.

options

object

No

Configuration options, such as headers (WebSocket request headers) and timeout (same units as the timeout parameter; the default timeout is used when it is not set).

See Also

Remarks

address parameter details: after the standard address wss://ws.okx.com:8443/ws/v5/public, use the | symbol as a separator. If the parameter string contains the | character, use || as the separator instead. The portion after the separator specifies the functional parameter settings, with individual parameters joined by the & character.

For example, to set both an ss5 proxy and compression parameters at the same time, you can write:

Dial("wss://ws.okx.com:8443/ws/v5/public|proxy=socks5://xxx:9999&compress=gzip_raw&mode=recv")

Features supported by the address parameter of the Dial functionParameter description
Parameters related to WebSocket protocol data compression: compress=valuecompress specifies the compression method. Available values: gzip, gzip_raw (also written as flate), zlib (also written as deflate). gzip_raw is raw deflate data without a gzip header, which can be used when the received data is not in standard gzip format. An unsupported value causes an error.
Parameters related to WebSocket protocol data compression: mode=valuemode specifies the compression mode. Only recv (receive compressed data and decompress it locally) is supported, and it is the default when not set. When compress is set, setting mode to send or dual causes an error.
Enable the WebSocket protocol compression setting: enableCompression=trueThis parameter is accepted but has no effect; no WebSocket permessage-deflate compression negotiation is performed.
Parameters for configuring underlying auto-reconnection of the WebSocket protocol: reconnect=valuereconnect sets whether to auto-reconnect. reconnect=true enables reconnection. If this parameter is not set, reconnection is disabled by default.
Parameters for configuring underlying auto-reconnection of the WebSocket protocol: interval=valueinterval is the retry interval, in milliseconds. For example, interval=10000 means a retry interval of 10 seconds; when not set, it defaults to 1 second, i.e., interval=1000.
Parameters for configuring underlying auto-reconnection of the WebSocket protocol: payload=valuepayload is the subscription message to be sent when the WebSocket reconnects, for example: payload=okok.
Parameters related to the socks5 proxy: proxy=valueproxy configures the ss5 proxy. The value format is: socks5://name:[email protected]:1080. Here name is the username of the ss5 server, pwd is the login password of the ss5 server, and 1080 is the port of the ss5 service.
WebSocket receive buffer limit: qsize=valueqsize is the maximum number of messages kept in the receive buffer. Defaults to 4096 when not set.
WebSocket receive buffer limit: qbytes=valueqbytes is the maximum number of bytes kept in the receive buffer. Defaults to 16777216 (16 MB) when not set.

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

When using the Dial function to connect to a database, write the connection string as follows:

Supported databasesConnection String
sqlite3sqlite3://test1.db
mysqlmysql://username:yourpassword@tcp(localhost:3306)/yourdatabase?charset=utf8mb4&parseTime=true
postgrespostgres://user=username password=yourpassword host=localhost port=5432 dbname=yourdatabase sslmode=disable
clickhouseclickhouse://tcp://localhost:9000?username=username&password=yourpassword&database=yourdatabase

Notes on each connection string:

  • sqlite3: The sqlite3:// prefix indicates that the sqlite3 database is used. A database file with a relative path is located in the live trading directory (logs/storage/<live trading ID>/); sqlite3://:memory: is an in-memory database that creates no file, and its data is discarded when the connection is closed; URI forms such as sqlite3://file:test.db?cache=shared&mode=memory are also supported.
  • mysql: The part after mysql:// is written the same way as a DSN of the Go MySQL driver (go-sql-driver/mysql). Parameters such as charset, collation, timeout, readTimeout, writeTimeout and tls (true, false, skip-verify, preferred) take effect, and ssl-mode can also be used to configure TLS; parseTime and loc are only validated and have no effect; custom TLS config names are not supported; any other unrecognized parameter is treated as a session variable and SET name = value is executed after connecting. It can also be written in URL form: mysql://username:yourpassword@localhost:3306/yourdatabase.
  • postgres: libpq key-value form, with items separated by spaces. sslmode follows libpq semantics: disable does not use TLS, require and similar modes use TLS without verifying the certificate, and only verify-ca and verify-full verify the certificate; parameters that read files, such as sslrootcert, sslcert, sslkey, passfile and service, are not supported; any other unrecognized parameter is set as a runtime parameter. It can also be written in URL form: postgres://username:yourpassword@localhost:5432/yourdatabase?sslmode=disable.
  • clickhouse: The part after clickhouse:// is written the same way as a DSN of the Go ClickHouse driver (clickhouse-go): tcp:// uses the native TCP protocol (port 9000; TLS with port 9440 or the parameter secure=true, and the certificate is not verified with skip_verify=true), and http:// or https:// use the HTTP interface; any other unrecognized parameter is treated as a ClickHouse setting. It can also be written in URL form: clickhouse://username:yourpassword@localhost:9000/yourdatabase, which uses the native TCP protocol by default; the clickhouse+http:// and clickhouse+https:// prefixes, or ports 8123 and 8443, use the HTTP interface.

Parameters after | in address are joined with & and assigned with =, so a payload containing characters such as = or & (for example a base64 signature or JSON) breaks the parsing. In that case do not put it in payload; send the subscription message with write() after connecting.