Dial
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.
javascriptfunction 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() } }pythondef 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()rustfn 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.
javascriptfunction 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() }pythonimport 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()rustfn 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
sqlite3database and execute SQL statements with theexec()method of the connection object (seeDial-return).javascriptvar 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() }pythonclient = 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()rustfn 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
| Type | Description |
object | A connection object with |
Arguments
| Name | Type | Required | Description |
address | string | Yes | The request address. |
timeout | number | No | The connection timeout. For |
options | object | No | Configuration options, such as |
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 function | Parameter description |
|---|---|
| Parameters related to WebSocket protocol data compression: compress=value | compress 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=value | mode 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=true | This 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=value | reconnect 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=value | interval 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=value | payload is the subscription message to be sent when the WebSocket reconnects, for example: payload=okok. |
| Parameters related to the socks5 proxy: proxy=value | proxy 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=value | qsize is the maximum number of messages kept in the receive buffer. Defaults to 4096 when not set. |
| WebSocket receive buffer limit: qbytes=value | qbytes 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 databases | Connection String |
|---|---|
| sqlite3 | sqlite3://test1.db |
| mysql | mysql://username:yourpassword@tcp(localhost:3306)/yourdatabase?charset=utf8mb4&parseTime=true |
| postgres | postgres://user=username password=yourpassword host=localhost port=5432 dbname=yourdatabase sslmode=disable |
| clickhouse | clickhouse://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 assqlite3://file:test.db?cache=shared&mode=memoryare 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 ascharset,collation,timeout,readTimeout,writeTimeoutandtls(true,false,skip-verify,preferred) take effect, andssl-modecan also be used to configure TLS;parseTimeandlocare only validated and have no effect; custom TLS config names are not supported; any other unrecognized parameter is treated as a session variable andSET name = valueis 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.
sslmodefollows libpq semantics:disabledoes not use TLS,requireand similar modes use TLS without verifying the certificate, and onlyverify-caandverify-fullverify the certificate; parameters that read files, such assslrootcert,sslcert,sslkey,passfileandservice, 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 parametersecure=true, and the certificate is not verified withskip_verify=true), andhttp://orhttps://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; theclickhouse+http://andclickhouse+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.