Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9703

C#から仮想通貨サイトのAPI(Node.js)を呼ぶ C#とNode.jsを連携させる

$
0
0
C#から仮想通貨サイトのAPI(Node.js)を呼ぶ バイナンスAPIをインストールする Node.jsからnpmを使いインストールします。 npm install -s node-binance-api サンプルスクリプト const Binance = require('node-binance-api'); const binance = new Binance(); binance.prices('BTCUSDT', (error, ticker) => { console.info(ticker); }); Node.js側 C#とNode.jsを連携させます。 C#から引数を受けます。 バイナンスAPIを実行し結果をJsonで返します。 const Binance = require('node-binance-api'); const binance = new Binance(); //C#から引数を受ける var SymbolCode = ''; if( process.argv.length > 2){ SymbolCode = process.argv[2]; } if(SymbolCode != ''){ binance.prices(SymbolCode, (error, ticker) => { var obj = { 'price' : ticker.BNBBTC }; var jesonStr = JSON.stringify(obj); console.clear(); //標準出力する console.info(jesonStr); }); } C#側 C#から引数で仮想通貨のシンボルコード(BNBBTC)を投げます。 結果をJson標準出力を取得しモデルに変換しています。 同期版 using System.Text.Json; private void Button1_Clicked(object sender, EventArgs a){ //同期版 System.Diagnostics.Process p = new System.Diagnostics.Process(); //nodeJSのパス p.StartInfo.FileName = @"/usr/local/bin/node"; //引数 p.StartInfo.Arguments = "/binance.js BNBBTC"; //出力を読み取れるようにする p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = false; //ウィンドウを表示しないようにする p.StartInfo.CreateNoWindow = false; p.Start(); string jsonStr = p.StandardOutput.ReadToEnd(); string error = p.StandardError.ReadToEnd(); //プロセス終了まで待機する p.WaitForExit(); p.Close(); //モデルにフェッチする BinancePriceModel BinancePriceModel1 = JsonSerializer.Deserialize<BinancePriceModel>(jsonStr); Console.WriteLine(BinancePriceModel1); } 非同期版 private void Button1_Clicked(object sender, EventArgs a){ //非同期 var p = new System.Diagnostics.Process(); p.StartInfo.FileName = @"/usr/local/bin/node"; p.StartInfo.Arguments = "/binance.js BNBBTC"; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = false; p.StartInfo.CreateNoWindow = false; p.EnableRaisingEvents = true; p.Exited += Proc_Exited; p.Start(); } private void Proc_Exited(object sender, EventArgs e){ System.Diagnostics.Process p = ((System.Diagnostics.Process)sender); string jsonStr = p.StandardOutput.ReadToEnd(); string error = p.StandardError.ReadToEnd(); p.Close(); BinancePriceModel BinancePriceModel1 = JsonSerializer.Deserialize<BinancePriceModel>(jsonStr); Console.WriteLine(BinancePriceModel1); } Model Jsから返されるJsonのモデルを事前に作っておきます。 BinancePriceModel.cs public class BinancePriceModel { public string price { get; set; } } バイナンスとは 世界最大の仮想通貨取引所です。 バイナンスへ 続く

Viewing all articles
Browse latest Browse all 9703

Trending Articles