public void _toWebHook(string message)
        {
            if (!WebhookEnabled || !(RunningMode == RunningMode.RealTime || RunningMode == RunningMode.VisualBacktesting))
            {
                return;
            }

            string messageformat = string.Format("{0} : {1}", Environment.MachineName, message);

            try
            {
                // --> Mi servono i permessi di sicurezza per il dominio, compreso i redirect
                Uri myuri = new Uri(Webhook);

                string pattern = string.Format("{0}://{1}/.*", myuri.Scheme, myuri.Host);

                // --> Autorizzo tutte le pagine di questo dominio
                Regex         urlRegEx = new Regex(pattern);
                WebPermission p        = new WebPermission(NetworkAccess.Connect, urlRegEx);
                p.Assert();

                // --> Protocollo di sicurezza https://
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;

                using (WebClient wc = new WebClient())
                {
                    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                    string HtmlResult = wc.UploadString(myuri, string.Format(PostParams, messageformat));
                }
            } catch (Exception exc)
            {
                MessageBox.Show(string.Format("{0}\r\nstopping cBots...", exc.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Stop();
            }
        }
        public void ToWebHook(string custom)
        {
            if (!WebhookEnabled || custom == null || custom.Trim().Length < 1)
            {
                return;
            }

            string messageformat = custom.Trim();

            try
            {
                Uri myuri = new Uri(Webhook);

                string pattern = string.Format("{0}://{1}/.*", myuri.Scheme, myuri.Host);

                Regex         urlRegEx = new Regex(pattern);
                WebPermission p        = new WebPermission(NetworkAccess.Connect, urlRegEx);
                p.Assert();

                ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;

                using (WebClient wc = new WebClient())
                {
                    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                    string HtmlResult = wc.UploadString(myuri, string.Format(PostParams, messageformat));
                }
            } catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
示例#3
0
        /// <summary>
        /// Richiesta HTTP --> GET, tiene in considerazione i protocolli di sicurezza, il redirect e la cache.
        /// <para>Wiki : https://github.com/cTraderGURU/cTrader-GURU-Utility/wiki/Browser.GET() </para>
        /// </summary>
        /// <returns>
        /// Restituisce il source della pagina
        /// </returns>
        /// <param name="url">L'indirizzo della pagina per la richiesta</param>
        /// <param name="nocache">Effettua la richiesta con parametro aggiuntivo mutevole</param>
        /// <param name="useragent">User-Agent personalizzato</param>
        public static string GET(string url, bool nocache = true, string useragent = "cTrader GURU")
        {
            string responseInString = "";

            // --> Richiesta originale senza cache ?

            if (nocache)
            {
                url = AddGetParamToUrl(url, "t", DateTime.Now.ToString("yyyyMMddHHmmssffff"));
            }

            // --> Mi servono i permessi di sicurezza per il dominio, compreso i redirect

            Uri myuri = new Uri(url);

            string pattern = string.Format("{0}://{1}/.*", myuri.Scheme, myuri.Host);

            // --> Autorizzo tutte le pagine di questo dominio

            Regex         urlRegEx = new Regex(@pattern);
            WebPermission p        = new WebPermission(NetworkAccess.Connect, urlRegEx);

            p.Assert();

            // --> Protocollo di sicurezza https://

            ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;

            // --> Prelevo la pagina e la restituisco

            using (var wb = new WebClient())
            {
                wb.Headers.Add("User-Agent", useragent);

                wb.Encoding      = Encoding.UTF8;
                responseInString = wb.DownloadString(myuri);
                // --> responseInString = Encoding.UTF8.GetString(wb.DownloadData(url));
            }

            return(responseInString);
        }
示例#4
0
        public void OnPositionOpened(PositionOpenedEventArgs args)
        {
            // --> Condividiamo solo il cross corrente?
            if (OonlyThis && args.Position.SymbolName != SymbolName)
            {
                return;
            }

            double sl = (args.Position.StopLoss == null) ? 0 : (double)args.Position.StopLoss;
            double tp = (args.Position.TakeProfit == null) ? 0 : (double)args.Position.TakeProfit;

            string messageformat = string.Format(Message, args.Position.SymbolName, args.Position.TradeType, args.Position.EntryPrice, args.Position.Quantity, sl, tp);

            try
            {
                // --> Mi servono i permessi di sicurezza per il dominio, compreso i redirect
                Uri myuri = new Uri(Webhook);

                string pattern = string.Format("{0}://{1}/.*", myuri.Scheme, myuri.Host);

                // --> Autorizzo tutte le pagine di questo dominio
                Regex         urlRegEx = new Regex(pattern);
                WebPermission p        = new WebPermission(NetworkAccess.Connect, urlRegEx);
                p.Assert();

                // --> Protocollo di sicurezza https://
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;

                using (WebClient wc = new WebClient())
                {
                    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                    string HtmlResult = wc.UploadString(myuri, string.Format(PostParams, messageformat));
                }
            } catch (Exception exc)
            {
                MessageBox.Show(string.Format("{0}\r\nstopping cBots 'Share Opened Trades To Webhook' ...", exc.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Stop();
            }
        }
        public void _toWebHook(string custom = null)
        {
            if (!WebhookEnabled)
            {
                return;
            }

            string tmpMex = custom != null && custom.Length > 0 ? custom : "{0} : {1} breakout, Ask {2} / Bid {3}";

            string messageformat = string.Format(tmpMex, NAME, SymbolName, string.Format("{0:N" + Symbol.Digits + "}", Ask), string.Format("{0:N" + Symbol.Digits + "}", Bid));

            try
            {
                // --> Mi servono i permessi di sicurezza per il dominio, compreso i redirect
                Uri myuri = new Uri(Webhook);

                string pattern = string.Format("{0}://{1}/.*", myuri.Scheme, myuri.Host);

                // --> Autorizzo tutte le pagine di questo dominio
                Regex         urlRegEx = new Regex(pattern);
                WebPermission p        = new WebPermission(NetworkAccess.Connect, urlRegEx);
                p.Assert();

                // --> Protocollo di sicurezza https://
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;

                using (WebClient wc = new WebClient())
                {
                    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                    string HtmlResult = wc.UploadString(myuri, string.Format(PostParams, messageformat));
                }
            } catch (Exception exc)
            {
                MessageBox.Show(string.Format("{0}\r\nstopping cBots 'TrendLine Power' ...", exc.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Stop();
            }
        }
示例#6
0
        //status code initial value set to -1
        //You should never get that value.
        //It should be 200 for succes
        //204 for succes but empty response
        //any other return code is an error
        //408 is a timeout error.
        public Tuple <String, int> Web_Read(string url, int timeout)
        {
            int          statusCode = -1;
            string       result     = "";
            StreamReader reader     = null;

            try
            {
                //asking for permission to call the specified url.
                var permission = new WebPermission();
                permission.AddPermission(NetworkAccess.Connect, url);
                permission.Assert();

                WebRequest request = WebRequest.Create(url);
                request.Timeout = (timeout == 0) ? request.Timeout : timeout;
                WebResponse response = request.GetResponse();

                Stream grs = response.GetResponseStream();
                if (grs != null)
                {
                    reader = new StreamReader(grs);
                    result = reader.ReadToEnd();
                }
                //if the response is empty it will officially return a 204 status code.
                //This is according to the http specification.
                if (result.Length < 1)
                {
                    result     = "error";
                    statusCode = 204;
                }
                else
                {
                    //response code 200: HTTP OK request was made succesfully.
                    statusCode = 200;
                }
            }
            catch (WebException ex)
            {
                var resp = (HttpWebResponse)ex.Response;
                if (resp == null)
                {
                    statusCode = 500;
                }
                else
                {
                    //Will parse all .net known http status codes.
                    int.TryParse(resp.StatusCode.ToString(), out statusCode);
                }
                result = "error";
            }
            catch (Exception e)
            {
                Log.Warn("Web_Read", e);
            }
            finally
            {
                // general cleanup
                if (reader != null)
                {
                    reader.Close(); //closes the reader and the response stream it was working on at the same time.
                }
            }

            return(Tuple.Create(result, statusCode));
        }
示例#7
0
        /// <summary>
        /// Richiede le informazioni del prodotto richiesto
        /// </summary>
        /// <param name="Request"></param>
        public API(RequestProductInfo Request)
        {
            RequestProduct = Request;

            // --> Non controllo se non ho l'ID del prodotto
            if (Request.MyProduct.ID <= 0)
            {
                return;
            }

            // --> Rendo disponibile il file del cookie
            _pathsetup = string.Format("{0}\\{1}.json", _mainpath, Request.MyProduct.ID);

            CookieInformation MySetup = new CookieInformation();
            DateTime          now     = DateTime.Now;

            // --> Evito di chiamare il server se non sono passate almeno 24h
            try
            {
                string json = _loadSetup();

                if (json != null && json.Trim().Length > 0)
                {
                    json = json.Trim();

                    MySetup = JsonConvert.DeserializeObject <CookieInformation>(json);
                    DateTime ExpireDate = MySetup.LastCheck.AddDays(1);

                    // --> Impedisco di controllare se non è passato il tempo necessario
                    if (now < ExpireDate)
                    {
                        ProductInfo.Exception = string.Format("Check for updates scheduled for {0}", ExpireDate.ToString());
                        return;
                    }
                }
            }
            catch (Exception Exp)
            {
                // --> Setup corrotto ? resetto!
                _writeSetup(MySetup);

                // --> Se ci sono errori non controllo perchè non è gestito ed evito di sovraccaricare il server che mi bloccherebbe
                ProductInfo.Exception = Exp.Message;
                return;
            }

            // --> Dobbiamo supervisionare la chiamata per registrare l'eccexione
            try
            {
                // --> Strutturo le informazioni per la richiesta POST
                NameValueCollection data = new NameValueCollection
                {
                    {
                        "account_broker",
                        Request.AccountBroker
                    },
                    {
                        "account_number",
                        Request.AccountNumber.ToString()
                    },
                    {
                        "my_version",
                        Request.MyProduct.Version
                    },
                    {
                        "productid",
                        Request.MyProduct.ID.ToString()
                    }
                };

                // --> Autorizzo tutte le pagine di questo dominio
                Uri    myuri   = new Uri(Service);
                string pattern = string.Format("{0}://{1}/.*", myuri.Scheme, myuri.Host);

                Regex         urlRegEx = new Regex(pattern);
                WebPermission p        = new WebPermission(NetworkAccess.Connect, urlRegEx);
                p.Assert();

                // --> Protocollo di sicurezza https://
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;

                // -->> Richiedo le informazioni al server
                using (var wb = new WebClient())
                {
                    wb.Headers.Add("User-Agent", UserAgent);

                    var response = wb.UploadValues(myuri, "POST", data);
                    ProductInfo.Source = Encoding.UTF8.GetString(response);
                }

                // -->>> Nel cBot necessita l'attivazione di "AccessRights = AccessRights.FullAccess"
                ProductInfo.LastProduct = JsonConvert.DeserializeObject <Product>(ProductInfo.Source);

                // --> Salviamo la sessione
                MySetup.LastCheck = now;
                _writeSetup(MySetup);
            }
            catch (Exception Exp)
            {
                // --> Qualcosa è andato storto, registro l'eccezione
                ProductInfo.Exception = Exp.Message;
            }
        }
示例#8
0
        public Tuple <String, int> Web_Read(string url)
        {
            int          statusCode = 200;
            string       result     = "";
            StreamReader reader     = null;

            try
            {
                //asking for permission to call the specified url.
                var permission = new WebPermission();
                permission.AddPermission(NetworkAccess.Connect, url);
                permission.Assert();


                WebRequest  request  = WebRequest.Create(url);
                WebResponse response = request.GetResponse();

                Stream grs = response.GetResponseStream();
                if (grs != null)
                {
                    reader = new StreamReader(grs);
                    result = reader.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                //Properly handling http errors here
                if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
                {
                    var resp = (HttpWebResponse)ex.Response;
                    switch (resp.StatusCode)
                    {
                    case HttpStatusCode.NotFound:
                        result     = "eror";
                        statusCode = 404;
                        break;

                    case HttpStatusCode.Forbidden:
                        result     = "error";
                        statusCode = 403;
                        break;

                    case HttpStatusCode.InternalServerError:
                        result     = "error";
                        statusCode = 500;
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }
            }
            finally
            {
                // general cleanup
                if (reader != null)
                {
                    reader.Close(); //closes the reader and the response stream it was working on at the same time.
                }
            }

            return(Tuple.Create(result, statusCode));
        }
示例#9
0
        /// <summary>
        /// Richiede le informazioni del prodotto richiesto
        /// </summary>
        /// <param name="Request"></param>
        public API(RequestProductInfo Request)
        {
            RequestProduct = Request;

            // --> Non controllo se non ho l'ID del prodotto
            if (Request.MyProduct.ID <= 0)
            {
                return;
            }

            // --> Dobbiamo supervisionare la chiamata per registrare l'eccexione
            try
            {
                // --> Strutturo le informazioni per la richiesta POST
                NameValueCollection data = new NameValueCollection
                {
                    {
                        "account_broker",
                        Request.AccountBroker
                    },
                    {
                        "account_number",
                        Request.AccountNumber.ToString()
                    },
                    {
                        "my_version",
                        Request.MyProduct.Version
                    },
                    {
                        "productid",
                        Request.MyProduct.ID.ToString()
                    }
                };

                // --> Autorizzo tutte le pagine di questo dominio
                Uri    myuri   = new Uri(Service);
                string pattern = string.Format("{0}://{1}/.*", myuri.Scheme, myuri.Host);

                Regex         urlRegEx = new Regex(pattern);
                WebPermission p        = new WebPermission(NetworkAccess.Connect, urlRegEx);
                p.Assert();

                // --> Protocollo di sicurezza https://
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;

                // -->> Richiedo le informazioni al server
                using (var wb = new WebClient())
                {
                    wb.Headers.Add("User-Agent", UserAgent);

                    var response = wb.UploadValues(myuri, "POST", data);
                    ProductInfo.Source = Encoding.UTF8.GetString(response);
                }

                // -->>> Nel cBot necessita l'attivazione di "AccessRights = AccessRights.FullAccess"
                ProductInfo.LastProduct = JsonConvert.DeserializeObject <Product>(ProductInfo.Source);
            } catch (Exception Exp)
            {
                // --> Qualcosa è andato storto, registro l'eccezione
                ProductInfo.Exception = Exp.Message;
            }
        }
示例#10
0
        internal Tuple <string, int> DoWebRequest(string url, int timeout = 0, string data = null)
        {
            int    statusCode = 0;
            string result     = "";

            try
            {
                Uri uriResult;
                if (!Uri.TryCreate(url, UriKind.Absolute, out uriResult) || (uriResult.Scheme != Uri.UriSchemeHttp && uriResult.Scheme != Uri.UriSchemeHttps))
                {
                    return(Tuple.Create("URL is in an invalid format", 0));
                }

                //asking for permission to call the specified url.
                result = "Failed Setting Web Permissions";
                var permission = new WebPermission();
                permission.AddPermission(NetworkAccess.Connect, url);
                permission.Assert();

                result = "Failed Constructing WebRequest";
                var request = WebRequest.Create(url);
                request.Timeout = (timeout == 0) ? request.Timeout : timeout;
                request.Headers["UserAgent"] = "OCTGN_" + Const.OctgnVersion.ToString() + "/" + Program.GameEngine.Definition.Name + "_" + Program.GameEngine.Definition.Version.ToString();
                request.Method = data == null ? "GET" : "POST";

                if (data != null)
                {
                    var byteArray = Encoding.UTF8.GetBytes(data);
                    request.ContentType   = "application/x-www-form-urlencoded";
                    request.ContentLength = byteArray.Length;

                    using (var webpageStream = request.GetRequestStream()) {
                        webpageStream.Write(byteArray, 0, byteArray.Length);
                    }
                }

                result = "Failed Making WebRequest";
                using (var response = (HttpWebResponse)request.GetResponse())
                    using (var grs = response.GetResponseStream()) {
                        if (grs == null)
                        {
                            return(Tuple.Create("Null Stream Error", 0));
                        }

                        using (var reader = new StreamReader(grs)) {
                            result = reader.ReadToEnd();

                            //if the response is empty it will officially return a 204 status code.
                            if (result.Length == 0)
                            {
                                return(Tuple.Create("No Content Error", 204));
                            }
                            statusCode = 200;
                        }
                    }
            } catch (WebException ex) {
                var resp = (HttpWebResponse)ex.Response;
                if (resp == null)
                {
                    result     = "Unknown Error: " + ex.ToString();
                    statusCode = 500;
                }
                else
                {
                    result     = "Error";
                    statusCode = (int)resp.StatusCode;
                }
            } catch (Exception e) {
                Log.Warn("Web_Read", e);
                result     = "Unknown Error: " + result + " " + e.ToString();
                statusCode = 500;
            }

            return(Tuple.Create(result, statusCode));
        }