public async Task <List <Order> > CancelOrdersAsync(Product product)
        {
            string       json         = null;
            List <Order> ordersOutput = new List <Order>();

            try
            {
                if (product == null)
                {
                    return(ordersOutput);
                }
                ProcessLogBroadcast?.Invoke(ApplicationName, MessageType.General,
                                            "Updating Cancel Orders Information.");
                Request request = new Request(ConnectionAdapter.Authentication.EndpointUrl, "DELETE",
                                              $"/orders?product_id={product.ID ?? string.Empty}");
                json = await ConnectionAdapter.RequestAsync(request);

                if (!json.StartsWith('[') && !json.EndsWith(']'))
                {
                    string orderId = JsonSerializer.Deserialize <string>(json);
                    if (string.IsNullOrEmpty(orderId))
                    {
                        return(ordersOutput);
                    }
                    ordersOutput = Orders.Where(x => x.ID == orderId)?.ToList();
                    int removed = Orders.RemoveAll(x => x.ID == orderId);
                    ProcessLogBroadcast?.Invoke(ApplicationName, MessageType.General,
                                                removed > 0
                            ? $"Removing Order IDs: {orderId} from Orders."
                            : $"No update from order cancel\r\nRequested URL: {request.RequestUrl}");
                    if (!ordersOutput.Any())
                    {
                        ordersOutput.Add(new Order {
                            ID = orderId
                        });
                    }
                    return(ordersOutput);
                }
                else
                {
                    List <string> orderIds = JsonSerializer.Deserialize <string[]>(json)?.ToList();
                    if (orderIds == null)
                    {
                        return(ordersOutput);
                    }
                    ordersOutput = Orders.Where(x => orderIds.Contains(x.ID))?.ToList();
                    int removed = Orders.RemoveAll(x => orderIds.Contains(x.ID));
                    ProcessLogBroadcast?.Invoke(ApplicationName, MessageType.General,
                                                removed > 0
                            ? $"Removing Order IDs: {orderIds} from Orders."
                            : $"No update from order cancel\r\nRequested URL: {request.RequestUrl}");
                    if (!ordersOutput.Any())
                    {
                        ordersOutput = (from id in orderIds select new Order {
                            ID = id
                        })?.ToList();
                    }
                    return(ordersOutput);
                }
            }
            catch (Exception e)
            {
                ProcessLogBroadcast?.Invoke(ApplicationName, MessageType.Error,
                                            $"Method: CancelOrdersAsync\r\nException Stack Trace: {e.StackTrace}\r\nJSON: {json}");
            }

            return(ordersOutput);
        }
Exemple #2
0
        private async void ProcessHistoryQuarterlyChartDownload()
        {
            await _processHistorySemaphoreSlim.WaitAsync();

            try
            {
                string fileName = FileName + $"_{RelativeStrengthIndexSettings.Product.ID.ToLower()}_15M.csv";
                string data     = "DateTime,High,Open,Close,Low,Volume,MA7,RSI14\n";
                //Validate file
                if (!File.Exists(fileName))
                {
                    string directoryName = Path.GetDirectoryName(fileName);
                    if (!string.IsNullOrEmpty(directoryName))
                    {
                        if (!Directory.Exists(directoryName))
                        {
                            Directory.CreateDirectory(directoryName);
                        }
                        File.Create(fileName).Close();
                        SaveAnalyticData(fileName, data);
                    }
                }

                //Initialise fields
                const int            period      = 14;
                const int            maPeriod    = 7;
                const int            granularity = 900;
                DateTime             startingDateTime;
                HistoricRate         previousHistoricRate = null;
                decimal              increases            = 0;
                decimal              decreases            = 0;
                Queue <HistoricRate> maQueue = new Queue <HistoricRate>();
                //Check if we have an empty file or not
                if (string.IsNullOrWhiteSpace(RelativeStrengthIndexSettings
                                              .HistoricChartPreviousHistoricDateTimeQuarterly))
                {
                    startingDateTime = new DateTime(2015, 4, 23).Date;
                    RelativeStrengthIndexSettings.HistoricChartAverageGainQuarterly        = 0;
                    RelativeStrengthIndexSettings.HistoricChartAverageLossQuarterly        = 0;
                    RelativeStrengthIndexSettings.HistoricChartCurrentPeriodCountQuarterly = 0;
                    RelativeStrengthIndexSettings.RelativeIndexQuarterly = -1;
                }
                else
                {
                    startingDateTime = RelativeStrengthIndexSettings.HistoricChartPreviousHistoricDateTimeQuarterly
                                       .ToDateTime().AddMinutes(15).ToUniversalTime();
                    previousHistoricRate = new HistoricRate
                    {
                        Close       = RelativeStrengthIndexSettings.HistoricChartPreviousHistoricRateCloseQuarterly,
                        Open        = RelativeStrengthIndexSettings.HistoricChartPreviousHistoricRateOpenQuarterly,
                        Low         = RelativeStrengthIndexSettings.HistoricChartPreviousHistoricRateLowQuarterly,
                        High        = RelativeStrengthIndexSettings.HistoricChartPreviousHistoricRateHighQuarterly,
                        Volume      = RelativeStrengthIndexSettings.HistoricChartPreviousHistoricRateVolumeQuarterly,
                        DateAndTime = RelativeStrengthIndexSettings.HistoricChartPreviousHistoricDateTimeQuarterly
                                      .ToDateTime().ToUniversalTime()
                    };
                }

                //Begin data parsing
                DateTime now = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour,
                                            DateTime.Now.Minute, 0).ToUniversalTime();
                int endGap = 2;
                while (startingDateTime < now)
                {
                    DateTime endingDateTime = startingDateTime.AddDays(endGap).ToUniversalTime();
                    //Get the latest historic data
                    HistoricCandlesSearch historicCandlesSearch = new HistoricCandlesSearch
                    {
                        Symbol           = RelativeStrengthIndexSettings.Product.ID,
                        StartingDateTime = startingDateTime,
                        EndingDateTime   = endingDateTime,
                        Granularity      = (Granularity)granularity
                    };
                    //Prevent overloaded calls by delaying for 1 second before call
                    await Task.Delay(1000);

                    //Get the latest historic data
                    List <HistoricRate> result = await UpdateProductHistoricCandles(historicCandlesSearch);

                    if (!result.Any())
                    {
                        //in the case that no data is available but current search date is not current date
                        startingDateTime = startingDateTime.AddDays(endGap).ToUniversalTime();
                        continue;
                    }

                    //Iterate though the historic data
                    foreach (HistoricRate rate in result)
                    {
                        if (rate.DateAndTime >= now)
                        {
                            break;
                        }
                        if (previousHistoricRate != null &&
                            previousHistoricRate.DateAndTime.ToString("dd/MM/yyyy HH:mm") ==
                            rate.DateAndTime.ToString("dd/MM/yyyy HH:mm"))
                        {
                            continue;
                        }
                        //Moving Average 7 days
                        if (maQueue.Count == maPeriod)
                        {
                            maQueue.Dequeue();
                        }
                        maQueue.Enqueue(rate);
                        //Calculate RSI 14 days
                        if (RelativeStrengthIndexSettings.HistoricChartCurrentPeriodCountQuarterly > 0 && previousHistoricRate != null)
                        {
                            decimal change = rate.Close - previousHistoricRate.Close;
                            if (change > 0)
                            {
                                increases += change;
                                if (RelativeStrengthIndexSettings.HistoricChartCurrentPeriodCountQuarterly > period)
                                {
                                    RelativeStrengthIndexSettings.HistoricChartAverageGainQuarterly =
                                        (RelativeStrengthIndexSettings.HistoricChartAverageGainQuarterly *
                                         (period - 1) + change) / period;
                                    RelativeStrengthIndexSettings.HistoricChartAverageLossQuarterly =
                                        RelativeStrengthIndexSettings.HistoricChartAverageLossQuarterly * (period - 1) /
                                        period;
                                }
                            }
                            else if (change < 0)
                            {
                                decreases += change * -1;
                                if (RelativeStrengthIndexSettings.HistoricChartCurrentPeriodCountQuarterly > period)
                                {
                                    RelativeStrengthIndexSettings.HistoricChartAverageGainQuarterly =
                                        RelativeStrengthIndexSettings.HistoricChartAverageGainQuarterly * (period - 1) /
                                        period;
                                    RelativeStrengthIndexSettings.HistoricChartAverageLossQuarterly =
                                        (RelativeStrengthIndexSettings.HistoricChartAverageLossQuarterly *
                                         (period - 1) + change * -1) / period;
                                }
                            }

                            if (RelativeStrengthIndexSettings.HistoricChartCurrentPeriodCountQuarterly >= period)
                            {
                                if (RelativeStrengthIndexSettings.HistoricChartCurrentPeriodCountQuarterly == period)
                                {
                                    RelativeStrengthIndexSettings.HistoricChartAverageGainQuarterly =
                                        increases / period;
                                    RelativeStrengthIndexSettings.HistoricChartAverageLossQuarterly =
                                        decreases / period;
                                }

                                if (RelativeStrengthIndexSettings.HistoricChartCurrentPeriodCountQuarterly >= period)
                                {
                                    RelativeStrengthIndexSettings.RelativeIndexQuarterly =
                                        RelativeStrengthIndexSettings.HistoricChartAverageLossQuarterly == 0
                                            ? 100
                                            : Math.Round(
                                            100 - 100 /
                                            (1 + RelativeStrengthIndexSettings.HistoricChartAverageGainQuarterly /
                                             RelativeStrengthIndexSettings.HistoricChartAverageLossQuarterly),
                                            2);
                                }
                                //Generate data
                                //DateTime,High,Open,Close,Low,Volume,MA7,RSI14
                                data =
                                    $"{rate.DateAndTime.ToUniversalTime()}," +
                                    $"{rate.High}," +
                                    $"{rate.Open}," +
                                    $"{rate.Close}," +
                                    $"{rate.Low}," +
                                    $"{rate.Volume}," +
                                    $"{maQueue.Average(x => x.Close)}," +
                                    $"{RelativeStrengthIndexSettings.RelativeIndexQuarterly}" +
                                    "\n";
                                SaveAnalyticData(fileName, data);
                            }
                        }

                        previousHistoricRate = rate;
                        RelativeStrengthIndexSettings.HistoricChartCurrentPeriodCountQuarterly++;
                    }
                    if (previousHistoricRate == null)
                    {
                        continue;
                    }
                    startingDateTime = previousHistoricRate.DateAndTime.AddMinutes(15).ToUniversalTime();
                    RelativeStrengthIndexSettings.HistoricChartPreviousHistoricRateCloseQuarterly =
                        previousHistoricRate.Close;
                    RelativeStrengthIndexSettings.HistoricChartPreviousHistoricRateOpenQuarterly =
                        previousHistoricRate.Open;
                    RelativeStrengthIndexSettings.HistoricChartPreviousHistoricRateLowQuarterly =
                        previousHistoricRate.Low;
                    RelativeStrengthIndexSettings.HistoricChartPreviousHistoricRateHighQuarterly =
                        previousHistoricRate.High;
                    RelativeStrengthIndexSettings.HistoricChartPreviousHistoricRateVolumeQuarterly =
                        previousHistoricRate.Volume;
                    RelativeStrengthIndexSettings.HistoricChartPreviousHistoricDateTimeQuarterly =
                        previousHistoricRate.DateAndTime.ToString();
                    Dictionary <string, string> indicatorInformation = new Dictionary <string, string>
                    {
                        ["RSI-15MIN"] =
                            RelativeStrengthIndexSettings.RelativeIndexQuarterly.ToString(CultureInfo
                                                                                          .InvariantCulture),
                        ["RSI-1HOUR"] =
                            RelativeStrengthIndexSettings.RelativeIndexHourly
                            .ToString(CultureInfo.InvariantCulture),
                        ["RSI-1DAY"] =
                            RelativeStrengthIndexSettings.RelativeIndexDaily.ToString(CultureInfo.InvariantCulture),
                        ["OPEN-15MIN"] =
                            RelativeStrengthIndexSettings.HistoricChartPreviousHistoricRateOpenQuarterly.ToString(
                                CultureInfo.InvariantCulture),
                        ["OPEN-1HOUR"] =
                            RelativeStrengthIndexSettings.HistoricChartPreviousHistoricRateOpenHourly.ToString(
                                CultureInfo.InvariantCulture),
                        ["OPEN-1DAY"] =
                            RelativeStrengthIndexSettings.HistoricChartPreviousHistoricRateOpen.ToString(CultureInfo
                                                                                                         .InvariantCulture)
                    };
                    TechnicalIndicatorInformationBroadcast?.Invoke(indicatorInformation);
                    Save();
                }
            }
            catch (Exception ex)
            {
                ProcessLogBroadcast?.Invoke(MessageType.Error,
                                            $"Method: ProcessHistoryHourlyChartDownload\r\nException Stack Trace: {ex.StackTrace}");
            }
            finally
            {
                _processHistorySemaphoreSlim.Release();
            }
        }
        public void LoadINI(string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    if (Authentication == null)
                    {
                        Authentication = new Authentication();
                    }
                    string       line;
                    StreamReader streamReader = new StreamReader(filePath);
                    while ((line = streamReader.ReadLine()) != null)
                    {
                        if (string.IsNullOrEmpty(line))
                        {
                            continue;
                        }
                        string env = TestMode ? "test" : "live";
                        if (line.StartsWith($"{env}_uri="))
                        {
                            line = line.Replace($"{env}_uri=", "").Trim();
                            if (string.IsNullOrEmpty(line))
                            {
                                continue;
                            }
                            Authentication.WebSocketUri = new Uri(line);
                        }
                        else if (line.StartsWith($"{env}_key="))
                        {
                            line = line.Replace($"{env}_key=", "").Trim();
                            if (string.IsNullOrEmpty(line))
                            {
                                continue;
                            }
                            Authentication.ApiKey = line;
                        }
                        else if (line.StartsWith($"{env}_secret="))
                        {
                            line = line.Replace($"{env}_secret=", "").Trim();
                            if (string.IsNullOrEmpty(line))
                            {
                                continue;
                            }
                            Authentication.Secret = line;
                        }
                        else if (line.StartsWith($"{env}_endpoint="))
                        {
                            line = line.Replace($"{env}_endpoint=", "").Trim();
                            if (string.IsNullOrEmpty(line))
                            {
                                continue;
                            }
                            Authentication.EndpointUrl = line;
                        }
                        else if (line.StartsWith($"{env}_passphrase="))
                        {
                            line = line.Replace($"{env}_passphrase=", "").Trim();
                            if (string.IsNullOrEmpty(line))
                            {
                                continue;
                            }
                            Authentication.Passphrase = line;
                        }
                    }

                    ConnectionAdapter.Authentication  = Authentication;
                    ConnectionAdapter.ClientWebSocket = ClientWebSocket;
                }
            }
            catch (Exception e)
            {
                ProcessLogBroadcast?.Invoke(ApplicationName, MessageType.Error,
                                            $"Method: LoadINI\r\nException Stack Trace: {e.StackTrace}");
            }
        }
        public virtual async Task <string> RequestAsync(IRequest request)
        {
            try
            {
                await _ioRequestSemaphoreSlim.WaitAsync();

                StringContent       requestBody = new StringContent("");
                HttpResponseMessage response;
                Uri absoluteUri;
                if (Authentication == null)
                {
                    throw new Exception("Invalid Authentication.");
                }
                if (string.IsNullOrEmpty(Authentication.Passphrase))
                {
                    request.RequestSignature = Authentication.ComputeSignature(request.RequestQuery);
                    request.RequestQuery     = null;
                    absoluteUri = request.ComposeRequestUriAbsolute(Authentication.EndpointUrl);
                    HttpClient.DefaultRequestHeaders.Clear();
                    HttpClient.DefaultRequestHeaders.Add("X-MBX-APIKEY", Authentication.ApiKey);
                    HttpClient.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json")); //ACCEPT header
                }
                else
                {
                    AuthenticationSignature authenticationSignature = Authentication.ComputeSignature(request);
                    requestBody = request.GetRequestBody();
                    absoluteUri = request.AbsoluteUri;
                    HttpClient.DefaultRequestHeaders.Clear();
                    //The api key as a string.
                    HttpClient.DefaultRequestHeaders.Add("CB-ACCESS-KEY", Authentication.ApiKey);
                    //The passphrase you specified when creating the API key.
                    HttpClient.DefaultRequestHeaders.Add("CB-ACCESS-PASSPHRASE", Authentication.Passphrase);
                    //The base64-encoded signature (see Signing a Message).
                    HttpClient.DefaultRequestHeaders.Add("CB-ACCESS-SIGN", authenticationSignature.Signature);
                    // A timestamp for your request.
                    HttpClient.DefaultRequestHeaders.Add("CB-ACCESS-TIMESTAMP", authenticationSignature.Timestamp);
                    //user-agent header
                    HttpClient.DefaultRequestHeaders.Add("User-Agent", "sefbkn.github.io");
                }

                switch (request.Method)
                {
                case "GET":
                    response = await HttpClient.GetAsync(absoluteUri);

                    break;

                case "POST":
                    response = await HttpClient.PostAsync(absoluteUri, requestBody);

                    break;

                case "DELETE":
                    response = await HttpClient.DeleteAsync(absoluteUri);

                    break;

                default:
                    throw new NotImplementedException("The supplied HTTP method is not supported: " +
                                                      request.Method);
                }

                if (response == null)
                {
                    throw new Exception(
                              $"null response from RequestAsync \r\n URI:{request.AbsoluteUri} \r\n:Request Body:{requestBody}");
                }
                return(await response.Content.ReadAsStringAsync());
            }
            catch (Exception ex)
            {
                ProcessLogBroadcast?.Invoke(MessageType.Error,
                                            $"Method: RequestAsync\r\nException Stack Trace: {ex.StackTrace}");
            }
            finally
            {
                _ioRequestSemaphoreSlim.Release();
            }

            return(null);
        }