Beispiel #1
0
        private async void UpdateBalancesAsync()
        {
            if (this.updateBalancesCancellation != null)
            {
                this.updateBalancesCancellation.Cancel();
            }

            this.updateBalancesCancellation = new CancellationTokenSource();

            HitError error = null;

            await Task.Factory.StartNew(() => this.UpdateBalances(this.updateBalancesCancellation.Token, out error))
            .ContinueWith((t) =>
            {
                if (error == null)
                {
                    this.balancesCache.ForEach(b => this.PushMessage(b));
                }
                else
                {
                    var dealTicket = DealTicketGenerator.CreateRefuseDealTicket(error.ToString());

                    this.PushMessage(dealTicket);
                }
            });
        }
Beispiel #2
0
 private void SocketApi_ConnectionStateChanged(HitSocketApi hitSocketApi, HitEventArgs e)
 {
     if (e.SocketError != null)
     {
         var dealTicket = DealTicketGenerator.CreateRefuseDealTicket(e.SocketError.Message);
         this.PushMessage(dealTicket);
     }
 }
Beispiel #3
0
        private void SocketApi_Notification(HitSocketApi hitSocketApi, HitEventArgs e)
        {
            if (e.SocketError != null)
            {
                this.PushMessage(DealTicketGenerator.CreateRefuseDealTicket(e.SocketError.Message));
                Core.Instance.Loggers.Log(e.SocketError);
                return;
            }

            this.ProcessSocketNotification(e);
        }
Beispiel #4
0
        protected T CheckHitResponse <T>(HitResponse <T> hitResponse, out HitError hitError, bool pushDealTicketOnError = false)
        {
            T result = hitResponse.Result;

            hitError = hitResponse.Error;

            if (hitError != null && pushDealTicketOnError)
            {
                var dealTicket = DealTicketGenerator.CreateRefuseDealTicket(hitError.Format());

                this.PushMessage(dealTicket);
            }

            return(result);
        }
Beispiel #5
0
        public override IList <IHistoryItem> LoadHistory(HistoryRequestParameters requestParameters)
        {
            var result = new List <IHistoryItem>();

            if (!this.allSymbolsCache.TryGetValue(requestParameters.SymbolId, out var okexSymbol))
            {
                return(result);
            }

            if (requestParameters.Period == Period.TICK1)
            {
                var ticks = this.client.GetTickHistory(okexSymbol, requestParameters.CancellationToken, out string error);

                if (!string.IsNullOrEmpty(error))
                {
                    this.PushMessage(DealTicketGenerator.CreateRefuseDealTicket(error));
                    return(result);
                }

                long prevTickTime = default;

                for (int i = ticks.Length - 1; i >= 0; i--)
                {
                    var tick = ticks[i];

                    if (tick.Time >= requestParameters.FromTime && tick.Time <= requestParameters.ToTime)
                    {
                        var item = new HistoryItemLast()
                        {
                            Price     = tick.Price ?? default,
                            Volume    = tick.Size ?? default,
                            TicksLeft = tick.Time.Ticks
                        };

                        if (prevTickTime >= item.TicksLeft)
                        {
                            item.TicksLeft = prevTickTime + 1;
                        }

                        prevTickTime = item.TicksLeft;
                        result.Add(item);
                    }
                }
            }
            else
            {
                var  okexPeriod  = requestParameters.Period.ToOKEx();
                var  historyType = requestParameters.HistoryType.ToOKEx();
                var  after       = requestParameters.ToTime;
                bool keepGoing   = true;

                while (keepGoing)
                {
                    var candles = this.client.GetCandleHistory(okexSymbol, after, okexPeriod, historyType, requestParameters.CancellationToken, out string error);

                    if (!string.IsNullOrEmpty(error))
                    {
                        this.PushMessage(DealTicketGenerator.CreateRefuseDealTicket(error));
                        break;
                    }

                    foreach (var item in candles)
                    {
                        if (item.Time < requestParameters.FromTime)
                        {
                            keepGoing = false;
                            break;
                        }

                        if (requestParameters.ToTime >= item.Time)
                        {
                            result.Add(new HistoryItemBar()
                            {
                                Close     = item.Close,
                                Open      = item.Open,
                                High      = item.High,
                                Low       = item.Low,
                                TicksLeft = item.Time.Ticks,
                                Volume    = (okexSymbol.IsInverseContractSymbol ? item.CurrencyVolume : item.Volume) ?? default
                            });
Beispiel #6
0
        protected override void ProcessSocketNotification(HitEventArgs e)
        {
            try
            {
                switch (e.NotificationMethod)
                {
                case HitNotificationMethod.ActiveOrders:
                    this.ordersCache = new Dictionary <string, MessageOpenOrder>();

                    foreach (var order in e.ActiveOrders)
                    {
                        var message = this.CreateOpenOrder(order);

                        this.ordersCache.Add(message.OrderId, message);
                    }
                    break;

                case HitNotificationMethod.Report:
                    var messages = new List <Message>();

                    MessageOpenOrder    openOrder    = null;
                    MessageOrderHistory orderHistory = null;

                    var reportType = e.Report.ReportType;

                    if (reportType == HitReportType.New || reportType == HitReportType.Replaced || reportType == HitReportType.Suspended)
                    {
                        messages.Add(openOrder    = this.CreateOpenOrder(e.Report));
                        messages.Add(orderHistory = new MessageOrderHistory(openOrder));
                        messages.Add(DealTicketGenerator.CreateTradingDealTicket(orderHistory, HitBTCVendor.VENDOR_NAME));

                        if (reportType == HitReportType.Replaced)
                        {
                            messages.Add(this.CreateCloseOrder(e.Report));
                            this.ordersCache.Remove(e.Report.OriginalRequestClientOrderId);
                        }

                        this.ordersCache[e.Report.ClientOrderId] = openOrder;
                    }
                    else
                    {
                        messages.Add(this.CreateCloseOrder(e.Report));
                        messages.Add(orderHistory = this.CreateOrderHistory(e.Report));
                        messages.Add(DealTicketGenerator.CreateTradingDealTicket(orderHistory, HitBTCVendor.VENDOR_NAME));

                        this.ordersCache.Remove(e.Report.ClientOrderId);

                        if (reportType == HitReportType.Trade)
                        {
                            messages.Add(this.CreateTrade(e.Report));
                        }
                    }

                    messages.ForEach(m => this.PushMessage(m));

                    this.UpdateBalancesAsync();
                    break;

                default:
                    base.ProcessSocketNotification(e);
                    break;
                }
            }
            catch (Exception ex)
            {
                Core.Instance.Loggers.Log(ex);
            }
        }
        /// <summary>
        /// Called when user requests history in the trading platform
        /// </summary>
        public override IList <IHistoryItem> LoadHistory(HistoryRequestParameters requestParameters)
        {
            List <IHistoryItem> result = new List <IHistoryItem>();

            string symbol = requestParameters.SymbolId;

            long fromUnix = Core.Instance.TimeUtils.ConvertDateTimeToUnixMiliseconds(requestParameters.FromTime);
            long toUnix   = Core.Instance.TimeUtils.ConvertDateTimeToUnixMiliseconds(requestParameters.ToTime);

            Stack <List <IHistoryItem> > itemsStack = new Stack <List <IHistoryItem> >();

            try
            {
                if (requestParameters.Period.BasePeriod == BasePeriod.Tick)
                {
                    long currentToUnix = toUnix;

                    while (fromUnix < currentToUnix)
                    {
                        var trades = this.restApi.GetTrades(symbol, fromUnix, currentToUnix).Result;

                        if (trades.Length == 0)
                        {
                            break;
                        }

                        List <IHistoryItem> ticks = new List <IHistoryItem>();
                        foreach (var trade in trades)
                        {
                            var last = CreateHistoryItemLast(trade);

                            ticks.Add(last);
                        }

                        itemsStack.Push(ticks);

                        currentToUnix = trades.Last().Timestamp - 1;
                    }
                }
                else
                {
                    string timeFrame = GetTimeFrameFromPeriod(requestParameters.Period);
                    long   millisecondsInRequestPeriod = requestParameters.Period.Ticks / TimeSpan.TicksPerMillisecond;
                    long   currentToUnix = toUnix;

                    while (fromUnix < currentToUnix)
                    {
                        var candles = this.restApi.GetCandles(symbol, timeFrame, fromUnix, currentToUnix).Result;

                        if (candles.Length == 0)
                        {
                            break;
                        }

                        List <IHistoryItem> bars = new List <IHistoryItem>();

                        for (int i = 0; i < candles.Length; i++)
                        {
                            var bar = CreateHistoryItemBar(candles[i]);

                            bars.Add(bar);
                        }

                        itemsStack.Push(bars);

                        currentToUnix = candles.Last().Timestamp - millisecondsInRequestPeriod;
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException is WebException wex && wex.Response is HttpWebResponse httpWebResponse && httpWebResponse.StatusCode == (HttpStatusCode)429)
                {
                    var dealTicket = DealTicketGenerator.CreateRefuseDealTicket($"{BitfinexConsts.VENDOR_NAME} request limit reached. Limit will be reseted in 1 minute");
                    PushMessage(dealTicket);
                }
            }
            finally
            {
                while (itemsStack.Count > 0)
                {
                    var items = itemsStack.Pop();

                    for (int i = items.Count - 1; i >= 0; i--)
                    {
                        result.Add(items[i]);
                    }
                }
            }

            return(result);
        }