How can I use ClearScript to call Node.js script with NPM and possibly pass some parameter? #440
Replies: 23 comments 1 reply
-
Hi @zydjohnHotmail, ClearScript only provides a standard JavaScript environment. It implements neither the Web APIs nor the Node.js API. The idea is that you start with the bare standard and use .NET to provide whatever APIs your script code requires. However, the CCXT code doesn't seem to have too many external dependencies, at least when it comes to executing its main script. In fact, loading the web version of CCXT is quite easy: using var engine = new V8ScriptEngine();
engine.Execute("self = this; setTimeout = () => {}");
engine.DocumentSettings.AccessFlags = DocumentAccessFlags.EnableWebLoading;
engine.ExecuteDocument("https://cdn.jsdelivr.net/npm/[email protected]/dist/ccxt.browser.js"); Once you've done that, the .NET host and the script engine can work together to access the data: engine.AddHostType(typeof(Console));
engine.Execute(@"
function dumpExchangeNames() {
for (let exchange of ccxt.exchanges) {
Console.WriteLine(exchange);
}
}
function dumpExchange(name) {
const exchange = new ccxt[name]();
Console.WriteLine(name + ': ' + JSON.stringify(exchange, undefined, 4));
}
");
engine.Script.dumpExchangeNames();
engine.Script.dumpExchange("bitflyer");
engine.Script.dumpExchange("coinbase");
// etc. It does look like some other CCXT capabilities require additional APIs – e.g., Good luck! |
Beta Was this translation helpful? Give feedback.
-
Hello: |
Beta Was this translation helpful? Give feedback.
-
HI @zydjohnHotmail,
No problem at all: engine.Execute(@"
function getExchangeJSON(name) {
const exchange = new ccxt[name]();
return JSON.stringify(exchange);
}
");
string json = engine.Script.getExchangeJSON("coinbase");
var exchange = JObject.Parse(json);
Console.WriteLine("{0} {1}", exchange["name"], exchange["version"]);
Console.WriteLine(exchange["requiredCredentials"]);
// etc. Cheers! |
Beta Was this translation helpful? Give feedback.
-
Hello: 'use strict'; (async function () { I have the following C# code in ClearScript: When I run this, I got the following error, which is logic: This exception was originally thrown at this call stack: Inner Exception 1: Inner Exception 2: I don’t know how to write async functions in ClearScript, and how to pass the API_key, Secre_Key, please advise! I also prefer a named function, like: GetBalance. |
Beta Was this translation helpful? Give feedback.
-
Hi @zydjohnHotmail,
It is the script engine – not ClearScript – that defines the supported language features. Luckily, V8 complies with the latest JavaScript standards, so it has full support for async functions.
Here's a quick sample that demonstrates JavaScript async functions, passing arguments from the host, and ClearScript's support for promise-task interoperability: public static async Task Main() {
using (var engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableTaskPromiseConversion)) {
engine.Script.delay = new Func<int, Task>(Task.Delay);
engine.AddHostType(typeof(Console));
engine.Execute(@"
async function repeatWithDelay(message, count, ms) {
for (let i = 0; i < count; ++i) {
await delay(ms);
Console.WriteLine(message);
}
}
");
await engine.Script.repeatWithDelay("Hello!", 5, 1000);
}
} As for the Good luck! |
Beta Was this translation helpful? Give feedback.
-
Hello: (async function () To use the script, pass 2 parameters, one is exchange name, as appeared in the first script, pick any one from the 120 items shown above; the second parameter is one crypto-currency name, like: BTC/USDT. |
Beta Was this translation helpful? Give feedback.
-
hi @zydjohnHotmail,
Since standard JavaScript has no I/O facilities, a script can't implement
That script uses several non-standard facilities: Instead of using Cheers! |
Beta Was this translation helpful? Give feedback.
-
Hello: I can run this code, however, it seems impossible to see any output from the CCXT node.js script. The process window just show less than 1 second, and it disappears, no time to see the output, which should show 100 exchanges CCXT supports. |
Beta Was this translation helpful? Give feedback.
-
Hi @zydjohnHotmail,
You should be able to capture the output as follows: Process p = new();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c node D:\nodejs\CCXT_Exchanges\ccxt_all_exchanges.js";
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
var output = p.StandardOutput.ReadToEnd();
p.WaitForExit(); Now you can display or process Good luck! |
Beta Was this translation helpful? Give feedback.
-
Hello: D:\nodejs\CCXT> namespace ConsoleCallCCXT When I run this, I can hear beep, but I saw the following error: Error: Cannot find module 'D:\nodejs\CCXT\hello_world.js.js' Node.js v19.0.0 D:\Helpers\ConsoleCallCCXT\ConsoleCallCCXT\bin\Debug\net6.0\ConsoleCallCCXT.exe (process 13356) exited with code 0. |
Beta Was this translation helpful? Give feedback.
-
Hi @zydjohnHotmail,
Your problem might be here: p.StartInfo.Arguments = "/c node D:\nodejs\CCXT\hello_world.js.js"; // ← wrong file name? Cheers! |
Beta Was this translation helpful? Give feedback.
-
Hello: |
Beta Was this translation helpful? Give feedback.
-
The code above captures the Node.js output in the |
Beta Was this translation helpful? Give feedback.
-
Hello: |
Beta Was this translation helpful? Give feedback.
-
Something like this: Process p = new();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c node D:\nodejs\CCXT\hello_world.js";
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
var output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine(output); // ← new line here
Console.Beep(); |
Beta Was this translation helpful? Give feedback.
-
Hello: |
Beta Was this translation helpful? Give feedback.
-
Hi @zydjohnHotmail,
The 'use strict';
const ccxt = require('ccxt');
console.log(ccxt.version);
var all_exchanges = ccxt.exchanges;
console.log(JSON.stringify(all_exchanges, undefined, 4)); Here's another possibility: 'use strict';
const ccxt = require('ccxt');
const util = require('util')
console.log(ccxt.version);
var all_exchanges = ccxt.exchanges;
console.log(util.inspect(all_exchanges, { maxArrayLength: null })); Good luck! |
Beta Was this translation helpful? Give feedback.
-
Hello: if (process.argv.length != 3) let exchange = new ccxt.binance const pair1OrderBook = async (pair1) => { To use this code, call this with one cryptocurrency trading pair, the biggest pair is: BTC/USDT, but the output contains too many rows, so calling it with not very active pairs, like this: Or you can call one pair, which exists, but no order book to show, the result like this: Now, I create one WinForms app, and write the following code: CCXT update very quickly, in the past a few days, it released more than 100 version, so the latest web version is at: When I run my code, I got the following error: This exception was originally thrown at this call stack: Inner Exception 1: Inner Exception 2: Please advise on how to fix this. I think this way is much better than using CMD console output. |
Beta Was this translation helpful? Give feedback.
-
Here's the last line of your script: pair1OrderBook(pair1); The script fails at that line because If you remove that line, the script should succeed, and you should be able to call |
Beta Was this translation helpful? Give feedback.
-
Hello: This exception was originally thrown at this call stack: Inner Exception 1: I believe ClearScripit engine complains pair1OrderBook not found. |
Beta Was this translation helpful? Give feedback.
-
Hi @zydjohnHotmail, At least one problem is in this C# code: await engine.Script.pair1OrderBook("BTC/USDT"); To be able to Good luck! |
Beta Was this translation helpful? Give feedback.
-
It doesn't. Unfortunately, as we've already discussed, the CCXT code relies too heavily on Web/Node.js APIs. The most critical of these is
We aren't aware of any such plan. ClearScript isn't affiliated in any way with the .NET project. Sorry! |
Beta Was this translation helpful? Give feedback.
-
Hello:
I want to know if I can find how can I call some Node.js script from C#, which call a npm package called ccxt, and return the truncated strings to C#. And one step further, how can I call similar Node.js script and pass some parameter and get the results back to C#.
My OS: Window 10 Pro (version 21H2)
Node.js: version: 18.10.0
CCXT: version: 2.0.79
The following is node.js script:
D:\nodejs\CCXT_Exchanges>type ccxt_all_exchanges.js
'use strict';
const ccxt = require('ccxt');
console.log(ccxt.version);
var all_exchanges = ccxt.exchanges
console.log(all_exchanges)
D:\nodejs\CCXT_Exchanges>
The output for running the node.js script:
D:\nodejs\CCXT_Exchanges>node ccxt_all_exchanges.js
2.0.79
[
'aax', 'alpaca', 'ascendex',
'bequant', 'bibox', 'bigone',
'binance', 'binancecoinm', 'binanceus',
'binanceusdm', 'bit2c', 'bitbank',
'bitbay', 'bitbns', 'bitcoincom',
'bitfinex', 'bitfinex2', 'bitflyer',
'bitforex', 'bitget', 'bithumb',
'bitmart', 'bitmex', 'bitopro',
'bitpanda', 'bitrue', 'bitso',
'bitstamp', 'bitstamp1', 'bittrex',
'bitvavo', 'bkex', 'bl3p',
'blockchaincom', 'btcalpha', 'btcbox',
'btcex', 'btcmarkets', 'btctradeua',
'btcturk', 'buda', 'bw',
'bybit', 'bytetrade', 'cex',
'coinbase', 'coinbaseprime', 'coinbasepro',
'coincheck', 'coinex', 'coinfalcon',
'coinmate', 'coinone', 'coinspot',
'crex24', 'cryptocom', 'currencycom',
'delta', 'deribit', 'digifinex',
'exmo', 'flowbtc', 'fmfwio',
'ftx', 'ftxus', 'gate',
'gateio', 'gemini', 'hitbtc',
'hitbtc3', 'hollaex', 'huobi',
'huobijp', 'huobipro', 'idex',
'independentreserve', 'indodax', 'itbit',
'kraken', 'kucoin', 'kucoinfutures',
'kuna', 'latoken', 'lbank',
'lbank2', 'liquid', 'luno',
'lykke', 'mercado', 'mexc',
'mexc3', 'ndax', 'novadax',
'oceanex', 'okcoin', 'okex',
'okex5', 'okx', 'paymium',
'phemex',
... 20 more items
]
D:\nodejs\CCXT_Exchanges>
The issue here is that console.log only shows the first 100 items, there are 20 more items will be returned. I want to use ClearScript to run the above node.js script and return all 120 items to C#.
How can I do this?
One step further:
I modified the above node.js script to add one parameter, so the script will return detailed information about only one exchange from total 120 exchanges.
D:\nodejs\CCXT_Exchanges>type ccxt_get1_exchange.js
'use strict';
const ccxt = require('ccxt');
console.log(ccxt.version);
const [nodejs, script1, exchange1] = process.argv;
let exchange = new ccxt[exchange1];
console.log(exchange)
D:\nodejs\CCXT_Exchanges>
To use this script, add one exchange name as show from the first node.js, like the following:
D:\nodejs\CCXT_Exchanges>node ccxt_get1_exchange.js aax
2.0.79
aax {
isBrowser: false,
…..
A lot of output, here are ignored.
I want to know how I can call the node.js script and pass one parameter, like: aax, and get the result, a very long string, back to C#.
I am using Visual Studio 2022, version 17.3.6; I can install NUGET package for ClearScript version 7.3.4.
Please advise on how can I write some C# code in Console program or in WinForms project for this job.
Thanks,
Beta Was this translation helpful? Give feedback.
All reactions