WebView 클래스에는 ExecuteScript() 메서드와 WebMessageReceived 이벤트라는 두 가지 강력한 멤버가 있습니다. 이를 사용하여 원하는 웹 페이지(예: Forex 뉴스 피드 또는 사용자 정의 HTML이 포함된 페이지)에 접근하고, 이 페이지에서 사용자 정의 JavaScript를 실행하며, WebView에서 알고로 전송된 메시지를 올바르게 처리하는 알고를 만들 수 있습니다.
스크립트 실행
WebView 내부에서 사용자 정의 스크립트를 실행하려면 아래와 같이 WebView.ExecuteScript(StringjavaScript) 메서드를 호출하기만 하면 됩니다.
WebView에서 메시지를 보내려면 HTML 페이지 내부의 JavaScript 코드에서 window.postMessage()를 호출하기만 하면 됩니다. 예를 들어, 아래 예제의 스크립트를 전달하여 두 숫자(예: 포지션의 가능한 진입 및 청산 가격) 사이의 백분율 차이를 계산할 수 있습니다.
ExecuteScript()와 OnWebMessageReceived를 결합하여 WebView를 통해 열린 페이지 내부에 컨트롤을 배치하고, 상호 작용 시 메시지를 cBot으로 다시 보낼 수 있습니다. 아래 예제에서는 이 기능을 사용하여 WebView 내부에서 직접 거래할 수 있도록 합니다. WebView는 기존 리소스가 아닌 사용자 정의 HTML 페이지를 엽니다.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingcAlgo.API;usingcAlgo.API.Collections;usingcAlgo.API.Indicators;usingcAlgo.API.Internals;usingSystem.Text.Json;namespacecAlgo.Robots{[Robot(AccessRights = AccessRights.None)]publicclassWebViewInteractionsExample:Robot{privateWebView_webView;protectedoverridevoidOnStart(){varwindow=newWindow();_webView=newWebView();_webView.Loaded+=WebView_Loaded;_webView.NavigationCompleted+=WebView_NavigationCompleted;_webView.WebMessageReceived+=WebView_WebMessageReceived;window.Child=_webView;window.Width=500;window.Height=500;window.Show();window.Closed+=args=>Stop();// stop cBot when window is closed}privatevoidWebView_WebMessageReceived(WebViewWebMessageReceivedEventArgsargs){Print("Message received from WebView: {0}",args.Message);vartradeMessage=JsonSerializer.Deserialize<TradeMessage>(args.Message);;vartradeType=tradeMessage.side=="buy"?TradeType.Buy:TradeType.Sell;ExecuteMarketOrder(tradeType,tradeMessage.symbolName,tradeMessage.volume);}privatevoidWebView_Loaded(WebViewLoadedEventArgsargs){args.WebView.NavigateToStringAsync(@" <script> function setSymbols(symbols) // called from the cBot { const symbolSelector = document.getElementById('symbolHtml'); symbolSelector.innerHTML = ''; symbols.forEach((symbol) => { symbolSelector.add(new Option(symbol)); }); } function trade(operation) { const symbolSelector = document.getElementById('symbolHtml'); const selectedSymbolName = symbolSelector.options[symbolSelector.selectedIndex].text; window.postMessage({ side: operation, volume: Number(document.getElementById('volumeHtml').value), symbolName: selectedSymbolName }); //send message to cBot } </script> <body bgcolor='white'> <div style='display:flex;flex-direction:column;width:300px'> <h1>This is HTML page</h1> <div>Symbol:</div> <select id='symbolHtml'></select> <span style='margin-top: 10px'>Volume:</span> <input id='volumeHtml' value='1000' /> <div style='margin-top:10px'> <input type='button' value='Buy' onclick='trade(`buy`)' /> <input type='button' value='Sell' onclick='trade(`sell`)' /> </div> </div> </body> ");}privatevoidWebView_NavigationCompleted(WebViewNavigationCompletedEventArgsobj){SendSymbolsToHtml();}privatevoidSendSymbolsToHtml(){varallSymbols="";foreach(varsymbolinSymbols){allSymbols=allSymbols+"'"+symbol+"',";}_webView.ExecuteScript("setSymbols(["+allSymbols+"]);");// invokes the corresponding function inside HTML}}classTradeMessage{publicstringside{get;set;}publicdoublevolume{get;set;}publicstringsymbolName{get;set;}}}
WebView를 통해 cBot은 새로운 주문을 할 수 있는 컨트롤이 포함된 사용자 정의 HTML 페이지를 엽니다. SendSymbolsToHtml() 메서드를 사용하여 cBot은 HTML 내부의 드롭다운 메뉴를 계정이 거래할 수 있는 모든 심볼 목록으로 채웁니다. cBot이 실행되는 동안 사용자는 심볼을 선택하고 주문 거래량을 지정한 후 웹 페이지 내부에서 직접 새로운 주문을 할 수 있습니다.