After creating an instance of the below indicator, you will be able to navigate between various web pages on cTrader.com. Your chosen output window will behave similarly to a web browser.
The WebView class has two powerful members, namely the ExecuteScript() method and the WebMessageReceived event. You can use them to create algos that access a web page of your choice (for example, a Forex news feed or any page with custom HTML), execute custom JavaScript on this page, and correctly handle any messages sent from the WebView back to the algo.
Execute scripts
To execute a custom script inside your WebView, all you need to do is call the WebView.ExecuteScript(StringjavaScript) method as shown below.
The script that needs to be executed inside the WebView can simply be passed as a string to the ExecuteString() method.
Note that this string has to contain fully accurate JavaScript. For example, it has to include a semicolon after every executable line.
Multi-line JavaScript
You can freely pass multi-line JavaScript to the ExecuteScript() method as shown in the example below (note the use of a string literal).
1234
_webView.ExecuteScript(@"const element = document.getElementById('nextButton');element.style.display = 'none';");
Handle message events
The WebMessageReceived event is raised when the content displayed in a WebView sends a message. You can react to this event by subscribing to any suitable event handler.
To send a message from a WebView, all you have to do is call window.postMessage() from the JavaScript code inside the HTML page. For instance, you can pass the script in the below example to calculate the percentile difference between two numbers (such as possible entry and exit prices for a position).
Context is not shared between C# and JavaScript when you call the ExecuteScript() method. If you want to pass a variable from the C# scope to the JavaScript scope, you will have to use string interpolation.
It is possible to combine ExecuteScript() and OnWebMessageReceived to place controls inside a page opened via WebView that, on interaction, send messages back to the cBot. In the example below, we use this functionality to allow trading directly inside the WebView. Note that the WebView opens a custom HTML page rather than an existing resource.
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;}}}
Via WebView, the cBot opens a custom HTML page containing controls that allow us to place new orders. Using the SendSymbolsToHtml() method, the cBot fills a dropdown menu inside the HTML with a list of all symbols that an account can trade. While the cBot is running, the user can select a symbol, specify the order volume and then place a new order directly inside the web page without ever interacting with controls inside cTrader.