Beispiel #1
0
        void ProcessIncomingDataStream(OpenApiMessagesFactory msgFactory, byte[] rawData)
        {
            var _msg = msgFactory.GetMessage(rawData);

#if TRACE_DATA_INCOMING
            if (isDebugIsOn)
            {
                //if (_msg.PayloadType == (int)OpenApiLib.ProtoOAPayloadType.OA_SPOT_EVENT)
                //{
                //    Console.Write(".");
                //}
                //else
                {
                    Console.WriteLine("ProcessIncomingDataStream() received: " + OpenApiMessagesPresentation.ToString(_msg));
                }
            }
#endif

            if (!_msg.HasPayload)
            {
                return;
            }

            var lastLastHeartBeatReceived = lastHeartBeatReceived;
            lastHeartBeatReceived = DateTime.UtcNow;

            switch (_msg.PayloadType)
            {
            case (int)OpenApiLib.ProtoPayloadType.PING_RES:
            {
                var payload = msgFactory.GetPingResponse(rawData);
                if (payload.HasTimestamp)
                {
                    ServerTime = new DateTime((long)payload.Timestamp);
                    Console.WriteLine("[time] " + Server.Time.ToShortTimeString());
                    //Server.Time = DateTime.FromFileTimeUtc();
                }
                break;
            }

            case (int)OpenApiLib.ProtoPayloadType.HEARTBEAT_EVENT:
                //var _payload_msg = msgFactory.GetHeartbeatEvent(rawData);
                var timeBetween = (lastHeartBeatReceived - lastLastHeartBeatReceived).TotalSeconds;
                Console.WriteLine($"<3 ({timeBetween.ToString("N1")}s)");
                break;

            case (int)OpenApiLib.ProtoOAPayloadType.OA_EXECUTION_EVENT:
            {
                var msg          = "";
                var _payload_msg = msgFactory.GetExecutionEvent(rawData);

                if (_payload_msg.HasReasonCode)
                {
                    var executionType = _payload_msg.ExecutionType.ToString().Replace("OA_ORDER_", "");
                    var reason        = _payload_msg.HasReasonCode ? $"({_payload_msg.ReasonCode})" : "";
                    msg += $"*** [EXECUTION: {executionType} {reason}] *** ";
                }

                if (_payload_msg.HasOrder)
                {
                    orderId = _payload_msg.Order.OrderId;
                    var slPrice    = _payload_msg.Order.HasStopLossPrice ? " sl:" + _payload_msg.Order.StopLossPrice : "";
                    var tpPrice    = _payload_msg.Order.HasTakeProfitPrice ? " tp:" + _payload_msg.Order.TakeProfitPrice : "";
                    var limitPrice = _payload_msg.Order.HasLimitPrice ? " limit:" + _payload_msg.Order.LimitPrice : "";
                    var stopPrice  = _payload_msg.Order.HasStopPrice ? " stop:" + _payload_msg.Order.StopPrice : "";
                    msg += $"[ORDER {orderId}] {_payload_msg.Order.TradeSide} {_payload_msg.Order.RequestedVolume} {_payload_msg.Order.SymbolName} {limitPrice}{stopPrice} {slPrice}{tpPrice}";
                }
                else if (_payload_msg.HasPosition)
                {
                    positionId = _payload_msg.Position.PositionId;
                    var p = _payload_msg.Position;
                    msg += $"[POSITION {positionId}] {p.TradeSide} {p.Volume} {p.SymbolName} @ {p.EntryPrice}";
                }
                else
                {
                }
                Console.WriteLine(msg);
            }
            break;

            case (int)OpenApiLib.ProtoOAPayloadType.OA_AUTH_RES:
                //var payload = msgFactory.GetAuthorizationResponse(rawData);
                IsAuthorized = true;
                Console.WriteLine("[authorized]");
                break;

            case (int)OpenApiLib.ProtoOAPayloadType.OA_SPOT_EVENT:
            {
                if (rawData.Length > 40)
                {
                    Console.WriteLine("================= GOT LONG SPOT EVENT: " + rawData.Length + " ===================");
                }
                var payload = msgFactory.GetSpotEvent(rawData);

                WriteUnknownFields(_msg.PayloadType, payload);

                //var timestamp = timestampField.VarintList[0];
                //var time = new DateTime(1970, 1, 1) + TimeSpan.FromMilliseconds(timestamp);
                var time = new DateTime(1970, 1, 1) + TimeSpan.FromMilliseconds(payload.Timestamp);

                if (payload.TrendbarCount > 0 || payload.TrendbarList.Count > 0)
                {
                    foreach (var bar in payload.TrendbarList)
                    {
                        Console.WriteLine($"*********************** TRENDBAR: {bar.Period} o:{bar.Open} h:{bar.High} l:{bar.Low} c:{bar.Close} [v:{bar.Volume}]");
                        if (bar.Period == ProtoOATrendbarPeriod.H1)
                        {
                            AccountStats.Increment(StatEventType.H1Bar);
                        }
                        else if (bar.Period == ProtoOATrendbarPeriod.H1)
                        {
                            AccountStats.Increment(StatEventType.H1Bar);
                        }
                        else
                        {
                            AccountStats.Increment(StatEventType.Other);
                        }
                        throw new Exception("***** got a trendbar!  Celebrate!");
                    }
                }
                var tick = new SymbolTick
                {
                    Symbol = payload.SymbolName,
                    Ask    = payload.HasAskPrice ? payload.AskPrice : double.NaN,
                    Bid    = payload.HasBidPrice ? payload.BidPrice : double.NaN,
                    Time   = time
                };
                if (payload.HasAskPrice || payload.HasBidPrice)
                {
                    AccountStats.Increment(StatEventType.Tick);
#if DEBUG
                    //if (AccountStats.Totals.Ticks % 100 == 0)
                    //{
                    //    Debug.WriteLine($"[stats] {AccountStats.Totals.Ticks} ticks received");
                    //}
#endif
                }

                var symbol = (ISymbolInternal)GetSymbol(payload.SymbolName);

                symbol.OnTick(tick);
                break;
            }

            case (int)OpenApiLib.ProtoOAPayloadType.OA_SUBSCRIBE_FOR_SPOTS_RES:
            {
                var payload = msgFactory.GetSubscribeForSpotsResponse(rawData);

                uint?subId = payload.HasSubscriptionId ? (uint?)payload.SubscriptionId : null;
#if TRACE_SUBSCRIPTIONS
                Console.WriteLine($"[SUBSCRIBED] {subId}");
#endif

#if GET_SUBS_AFTER_SUB
                SendGetSpotSubscriptionReq(subId);
                SendGetAllSpotSubscriptionsReq();
#endif

                WriteUnknownFields(_msg.PayloadType, payload);
                break;
            }

            case (int)OpenApiLib.ProtoOAPayloadType.OA_UNSUBSCRIBE_FROM_SPOTS_RES:
            {
                var payload = msgFactory.GetUnsubscribeFromSpotsResponse(rawData);

                //uint? subId = payload. ? (uint?)payload.SubscriptionId : null;
                Debug.WriteLine($"[UNSUBSCRIBED]");

#if GET_SUBS_AFTER_SUB
                SendGetAllSpotSubscriptionsReq();
#endif

                WriteUnknownFields(_msg.PayloadType, payload);

                break;
            }

            case (int)OpenApiLib.ProtoOAPayloadType.OA_GET_ALL_SPOT_SUBSCRIPTIONS_RES:
            {
#if TRACE_SUBSCRIPTIONS
                Debug.WriteLine($"--- GET_ALL_SPOT_SUBSCRIPTIONS_RES: ---");
                var payload = msgFactory.GetGetAllSpotSubscriptionsResponse(rawData);
                foreach (var x in payload.SpotSubscriptionsList)
                {
                    foreach (var y in x.SubscribedSymbolsList)
                    {
                        Debug.Write($" - subscription {x.SubscriptionId}: {y.SymbolName} periods: ");
                        foreach (var z in y.PeriodList)
                        {
                            Debug.Write($" {z.ToString()}");
                        }
                        Debug.WriteLine();
                    }
                }
                Debug.WriteLine($"--------------------------------------- ");
#endif
            }
            break;

            case (int)OpenApiLib.ProtoOAPayloadType.OA_GET_SPOT_SUBSCRIPTION_RES:
            {
#if TRACE_SUBSCRIPTIONS
                var payload = msgFactory.GetGetSpotSubscriptionResponse(rawData);
                Debug.WriteLine($"--- GET_SPOT_SUBSCRIPTION_RES for subscription {payload.SpotSubscription.SubscriptionId}: --- ");
                foreach (var y in payload.SpotSubscription.SubscribedSymbolsList)
                {
                    Debug.Write($" - {y.SymbolName} periods: ");
                    foreach (var z in y.PeriodList)
                    {
                        Debug.Write($"{z.ToString()} ");
                    }
                    Debug.WriteLine();
                }
                Debug.WriteLine($"------------------------------------------------------ ");
#endif
            }
            break;

            case (int)OpenApiLib.ProtoOAPayloadType.OA_SUBSCRIBE_FOR_TRADING_EVENTS_RES:
            {
                var payload = msgFactory.GetSubscribeForTradingEventsResponse(rawData);
                Console.WriteLine("[TRADE EVENTS] SUBSCRIBED");
            }
            break;

            default:
                Console.WriteLine("UNHANDLED MESSAGE: " + _msg.PayloadType);
                break;
            }
            ;
        }