Exemplo n.º 1
0
        public JsonResult SendMarketOrder([FromBody] Params param)
        {
            _tcpClient = new TcpClient(param.ApiHost, param.ApiPort);;
            _apiSocket = new SslStream(_tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
            _apiSocket.AuthenticateAsClient(param.ApiHost);
            SendAuthorizationRequest(param);
            List <string> data = new List <string>();

            ProtoTradeSide tradeType = new ProtoTradeSide();

            if (param.TradeSide.ToUpper() == "BUY")
            {
                tradeType = ProtoTradeSide.BUY;
            }
            if (param.TradeSide.ToUpper() == "SELL")
            {
                tradeType = ProtoTradeSide.SELL;
            }
            var msgFactory = new OpenApiMessagesFactory();
            var msg        = msgFactory.CreateMarketOrderRequest(param.AccountId, param.AccessToken, param.SymbolName, tradeType, param.Volume * 100,
                                                                 param.StopLossInPips, param.TakeProfitInPips, param.Comment);

            Transmit(msg);
            byte[] _message     = Listen(_apiSocket);
            var    protoMessage = msgFactory.GetMessage(_message);

            data.Add(OpenApiMessagesPresentation.ToString(protoMessage));

            Thread.Sleep(1000);
            _message     = Listen(_apiSocket);
            protoMessage = msgFactory.GetMessage(_message);
            data.Add(OpenApiMessagesPresentation.ToString(protoMessage));
            return(Json(new { data }));
        }
Exemplo n.º 2
0
        private async Task RequestSubscribeForSymbol(string symbol, params ProtoOATrendbarPeriod[] periods)
        {
            await ValidateConnected();

            if (periods.Length == 0)
            {
                periods = new ProtoOATrendbarPeriod[] {
                    ProtoOATrendbarPeriod.M1 // TEMP TEST - For Spotware troubleshooting missing trendbars
                };
            }

            var subscribed = GetSubscribed(symbol);

            List <ProtoOATrendbarPeriod> list = new List <ProtoOATrendbarPeriod>(periods.Where(p => !subscribed.Contains(p)));

            // TODO: Verify previously subscribed trendbars stay subscribed.  Otherwise, eliminate the where clause above.

            var _msg = outgoingMsgFactory.CreateSubscribeForSpotsRequest(AccountId, AccessToken, symbol, clientMsgId, list);

            if (isDebugIsOn)
            {
                //#if LOG_SENTITIVE_INFO
#if TRACE_SUBSCRIPTIONS
                Debug.WriteLine("[tradeapi] SendSubscribeForSpotsRequest(): {0}", OpenApiMessagesPresentation.ToString(_msg));
#endif
                //#else
                //                Console.WriteLine("SendSubscribeForSpotsRequest(): {0}", OpenApiMessagesPresentation.ToString(_msg));
                //#endif
            }
            writeQueueSync.Enqueue(_msg.ToByteArray());
        }
Exemplo n.º 3
0
        protected void RequestUnsubscribeForSymbol(string symbol, params ProtoOATrendbarPeriod[] periods)
        {
            var _msg = outgoingMsgFactory.CreateUnsubscribeFromSymbolSpotsRequest(symbol, clientMsgId);

#if TRACE_SUBSCRIPTIONS
            if (isDebugIsOn)
            {
                Console.WriteLine("Send UnsubscribeFromSymbolSpotsRequest(): {0}", OpenApiMessagesPresentation.ToString(_msg));
            }
#endif
            writeQueueSync.Enqueue(_msg.ToByteArray());

            var subscribed = GetSubscribed(symbol);
            foreach (var period in periods)
            {
                subscribed.Remove(period);
            }

            if (subscribed.Count > 0 || periods.Length > 0)
            {
                RequestSubscribeForSymbol(symbol, subscribed.ToArray()).FireAndForget();
            }
            else
            {
                var s = GetSymbol(symbol);
                s.Bid = double.NaN;
                s.Ask = double.NaN;
            }

            //throw new NotImplementedException();
            //var _msg = outgoingMsgFactory.CreateUnsubscribeAccountFromSpotsRequest(AccountId, AccessToken, symbol, clientMsgId);
            //if (isDebugIsOn) Console.WriteLine("SendSubscribeForSpotsRequest() Message to be sent:\n{0}", OpenApiMessagesPresentation.ToString(_msg));
            //writeQueueSync.Enqueue(_msg.ToByteArray());
        }
Exemplo n.º 4
0
        static void SendHeartbeatEvent(OpenApiMessagesFactory msgFactory, Queue writeQueue)
        {
            var _msg = msgFactory.CreateHeartbeatEvent();

            if (isDebugIsOn)
            {
                Console.WriteLine("SendHeartbeatEvent() Message to be send:\n{0}", OpenApiMessagesPresentation.ToString(_msg));
            }
            writeQueue.Enqueue(Utils.Serialize(_msg));
        }
Exemplo n.º 5
0
        static void SendPingRequest(OpenApiMessagesFactory msgFactory, Queue writeQueue)
        {
            var _msg = msgFactory.CreatePingRequest((ulong)DateTime.Now.Ticks);

            if (isDebugIsOn)
            {
                Console.WriteLine("SendPingRequest() Message to be send:\n{0}", OpenApiMessagesPresentation.ToString(_msg));
            }
            writeQueue.Enqueue(Utils.Serialize(_msg));
        }
Exemplo n.º 6
0
        void SendStopOrderRequest(OpenApiMessagesFactory msgFactory, Queue writeQueue)
        {
            var _msg = msgFactory.CreateStopOrderRequest(AccountId, AccessToken, "EURUSD", OpenApiLib.ProtoTradeSide.BUY, 1000000, 0.2, clientMsgId);

            if (isDebugIsOn)
            {
                Console.WriteLine("SendStopOrderRequest() Message to be sent:\n{0}", OpenApiMessagesPresentation.ToString(_msg));
            }
            writeQueue.Enqueue(_msg.ToByteArray());
        }
        private void SendStopOrderRequest(long testAccountId)
        {
            var _msg = outgoingMsgFactory.CreateStopOrderRequest(testAccountId, authToken, "EURUSD", ProtoTradeSide.BUY, 1000000, 0.2, clientMsgId);

            if (isDebugIsOn)
            {
                Console.WriteLine("SendStopOrderRequest() Message to be send:\n{0}", OpenApiMessagesPresentation.ToString(_msg));
            }
            writeQueue.Enqueue(Utils.Serialize(_msg));
        }
Exemplo n.º 8
0
        private void SendAuthorizationRequest()
        {
            var msgFactory = new OpenApiMessagesFactory();
            var msg        = msgFactory.CreateAuthorizationRequest(_clientId, _clientSecret);

            Transmit(msg);
            byte[] _message     = Listen(_apiSocket);
            var    protoMessage = msgFactory.GetMessage(_message);

            lblResponse.Text = OpenApiMessagesPresentation.ToString(protoMessage);
        }
Exemplo n.º 9
0
        protected void btnSendPingRequest_Click(object sender, EventArgs e)
        {
            var msgFactory = new OpenApiMessagesFactory();
            var msg        = msgFactory.CreatePingRequest((ulong)DateTime.Now.Ticks);

            Transmit(msg);
            byte[] _message     = Listen(_apiSocket);
            var    protoMessage = msgFactory.GetMessage(_message);

            lblResponse.Text = OpenApiMessagesPresentation.ToString(protoMessage);
        }
Exemplo n.º 10
0
        protected void btnSendGetAllSubscriptionsForSpotEventsRequest_Click(object sender, EventArgs e)
        {
            SendAuthorizationRequest();
            var msgFactory = new OpenApiMessagesFactory();
            var msg        = msgFactory.CreateGetAllSpotSubscriptionsRequest();

            Transmit(msg);
            byte[] _message     = Listen(_apiSocket);
            var    protoMessage = msgFactory.GetMessage(_message);

            lblResponse.Text = OpenApiMessagesPresentation.ToString(protoMessage);
        }
Exemplo n.º 11
0
        void SendPingRequest(OpenApiMessagesFactory msgFactory, Queue writeQueue)
        {
            var _msg = msgFactory.CreatePingRequest((ulong)DateTime.Now.Ticks);

#if TRACE_PING
            if (isDebugIsOn)
            {
                Console.WriteLine("SendPingRequest() Message to be sent:\n{0}", OpenApiMessagesPresentation.ToString(_msg));
            }
#endif
            writeQueue.Enqueue(_msg.ToByteArray());
        }
Exemplo n.º 12
0
        void SendHeartbeatEvent(OpenApiMessagesFactory msgFactory, Queue writeQueue)
        {
            var _msg = msgFactory.CreateHeartbeatEvent();

#if TRACE_HEARTBEAT
            if (isDebugIsOn)
            {
                Console.WriteLine("SendHeartbeatEvent() Message to be sent:\n{0}", OpenApiMessagesPresentation.ToString(_msg));
            }
#endif
            writeQueue.Enqueue(_msg.ToByteArray());
        }
Exemplo n.º 13
0
        protected void btnUnsubscribeForTradingEvents_Click(object sender, EventArgs e)
        {
            SendAuthorizationRequest();
            var accountID  = ddlTradingAccounts.SelectedValue;
            var msgFactory = new OpenApiMessagesFactory();
            var msg        = msgFactory.CreateUnsubscribeForTradingEventsRequest(Convert.ToInt32(accountID));

            Transmit(msg);
            byte[] _message     = Listen(_apiSocket);
            var    protoMessage = msgFactory.GetMessage(_message);

            lblResponse.Text = OpenApiMessagesPresentation.ToString(protoMessage);
        }
Exemplo n.º 14
0
        private void Transmit(ProtoMessage msg, bool log = true)
        {
            if (log)
            {
                txtMessages.Text += "Send: " + OpenApiMessagesPresentation.ToString(msg);
                txtMessages.Text += Environment.NewLine;
            }
            var msgByteArray = msg.ToByteArray();

            byte[] length = BitConverter.GetBytes(msgByteArray.Length).Reverse().ToArray();
            _apiSocket.Write(length);
            _apiSocket.Write(msgByteArray);
        }
Exemplo n.º 15
0
        protected void btnSendClosePositionRequest_Click(object sender, EventArgs e)
        {
            SendAuthorizationRequest();
            var accountID  = ddlTradingAccounts.SelectedValue;
            var token      = Session["Token"].ToString();
            var msgFactory = new OpenApiMessagesFactory();
            var msg        = msgFactory.CreateClosePositionRequest(Convert.ToInt32(accountID), token, 100, 100000);

            Transmit(msg);
            byte[] _message     = Listen(_apiSocket);
            var    protoMessage = msgFactory.GetMessage(_message);

            lblResponse.Text = OpenApiMessagesPresentation.ToString(protoMessage);
        }
Exemplo n.º 16
0
        public JsonResult SendAmendPosition([FromBody] Params param)
        {
            _tcpClient = new TcpClient(param.ApiHost, param.ApiPort);;
            _apiSocket = new SslStream(_tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
            _apiSocket.AuthenticateAsClient(param.ApiHost);
            SendAuthorizationRequest(param);
            List <string> data = new List <string>();

            var msgFactory = new OpenApiMessagesFactory();
            var msg        = msgFactory.CreateAmendPositionProtectionRequest(param.AccountId, param.AccessToken.ToString(), param.PositionId, param.StopLossPrice, param.TakeProfitPrice);

            Transmit(msg);
            byte[] _message     = Listen(_apiSocket);
            var    protoMessage = msgFactory.GetMessage(_message);

            data.Add(OpenApiMessagesPresentation.ToString(protoMessage));
            return(Json(new { data }));
        }
Exemplo n.º 17
0
        public JsonResult SendClosePosition([FromBody] Params param)
        {
            _tcpClient = new TcpClient(param.ApiHost, param.ApiPort);;
            _apiSocket = new SslStream(_tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
            _apiSocket.AuthenticateAsClient(param.ApiHost);
            SendAuthorizationRequest(param);
            List <string> data = new List <string>();

            var msgFactory = new OpenApiMessagesFactory();

            if (!string.IsNullOrEmpty(param.SelectedType))
            {
                foreach (var p in param.SelectedPositions)
                {
                    var msg = msgFactory.CreateClosePositionRequest(param.AccountId, param.AccessToken, p.PositionId, p.Volume);
                    Transmit(msg);
                }
            }
            byte[] _message     = Listen(_apiSocket);
            var    protoMessage = msgFactory.GetMessage(_message);

            data.Add(OpenApiMessagesPresentation.ToString(protoMessage));
            return(Json(new { data }));
        }
Exemplo n.º 18
0
        void SendAmendLimitOrderRequest(OpenApiMessagesFactory msgFactory, Queue writeQueue)
        {
            var _msg = msgFactory.CreateAmendLimitOrderRequest(AccountId, AccessToken, orderId, 1.10, clientMsgId);

            if (isDebugIsOn)
            {
                Console.WriteLine("SendLimitOrderRequest() Message to be sent:\n{0}", OpenApiMessagesPresentation.ToString(_msg));
            }
            writeQueue.Enqueue(_msg.ToByteArray());
        }
Exemplo n.º 19
0
        void SendGetAllSubscriptionsForSpotEventsRequest(OpenApiMessagesFactory msgFactory, Queue writeQueue)
        {
            var _msg = msgFactory.CreateGetAllSpotSubscriptionsRequest();

            if (isDebugIsOn)
            {
                Console.WriteLine("SendGetAllSubscriptionsForSpotEventsRequest() Message to be sent:\n{0}", OpenApiMessagesPresentation.ToString(_msg));
            }
            writeQueue.Enqueue(_msg.ToByteArray());
        }
Exemplo n.º 20
0
        void SendUnsubscribeForTradingEventsRequest(OpenApiMessagesFactory msgFactory, Queue writeQueue)
        {
            var _msg = msgFactory.CreateUnsubscribeForTradingEventsRequest(AccountId);

            if (isDebugIsOn)
            {
                Console.WriteLine("SendUnsubscribeForTradingEventsRequest() Message to be sent:\n{0}", OpenApiMessagesPresentation.ToString(_msg));
            }
            writeQueue.Enqueue(_msg.ToByteArray());
        }
Exemplo n.º 21
0
        void SendAuthorizationRequest()
        {
            var _msg = outgoingMsgFactory.CreateAuthorizationRequest(ClientPublicId, ClientSecret);

            if (isDebugIsOn)
            {
                //#if LOG_SENTITIVE_INFO
                Console.WriteLine("SendAuthorizationRequest() Message to be sent:{0}", OpenApiMessagesPresentation.ToString(_msg));
                //#else
                //Console.WriteLine("SendAuthorizationRequest() Message to be sent: *********");
                //#endif
            }
            writeQueueSync.Enqueue(_msg.ToByteArray());
        }
Exemplo n.º 22
0
        void SendAuthorizationRequest(OpenApiMessagesFactory msgFactory, Queue writeQueue)
        {
            var _msg = msgFactory.CreateAuthorizationRequest(ClientPublicId, ClientSecret);

            if (isDebugIsOn)
            {
                Console.WriteLine("SendAuthorizationRequest() Message to be sent:\n{0}", OpenApiMessagesPresentation.ToString(_msg));
            }
            writeQueue.Enqueue(_msg.ToByteArray());
        }
Exemplo n.º 23
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;
            }
            ;
        }
Exemplo n.º 24
0
        void SendGetAllSpotSubscriptionsReq()
        {
            var _msg = outgoingMsgFactory.CreateGetAllSpotSubscriptionsRequest(clientMsgId);

#if TRACE_SUBSCRIPTIONS
            if (isDebugIsOn)
            {
                Debug.WriteLine("SendGetAllSpotSubscriptionsReq() Message to be sent:\n{0}", OpenApiMessagesPresentation.ToString(_msg));
            }
#endif

            writeQueueSync.Enqueue(_msg.ToByteArray());
        }
Exemplo n.º 25
0
        void SendGetSpotSubscriptionReq(uint?subscriptionId = 0)
        {
            if (!subscriptionId.HasValue)
            {
                return;
            }
            var _msg = outgoingMsgFactory.CreateGetSpotSubscriptionRequest(subscriptionId.Value, clientMsgId);

#if TRACE_SUBSCRIPTIONS
            if (isDebugIsOn)
            {
                Debug.WriteLine("SendGetSpotSubscriptionReq() Message to be sent:\n{0}", OpenApiMessagesPresentation.ToString(_msg));
            }
#endif
            writeQueueSync.Enqueue(_msg.ToByteArray());
        }
Exemplo n.º 26
0
        static void SendGetAllSubscriptionsForTradingEventsRequest(OpenApiMessagesFactory msgFactory, Queue writeQueue)
        {
            var _msg = msgFactory.CreateAllSubscriptionsForTradingEventsRequest();

            if (isDebugIsOn)
            {
                Console.WriteLine("SendGetAllSubscriptionsForTradingEventsRequest() Message to be send:\n{0}", OpenApiMessagesPresentation.ToString(_msg));
            }
            writeQueue.Enqueue(Utils.Serialize(_msg));
        }
Exemplo n.º 27
0
        static void SendLimitOrderRequest(OpenApiMessagesFactory msgFactory, Queue writeQueue)
        {
            var _msg = msgFactory.CreateLimitOrderRequest(testAccountId, testAccessToken, "EURUSD", ProtoTradeSide.BUY, 1000000, 1.8, clientMsgId);

            if (isDebugIsOn)
            {
                Console.WriteLine("SendLimitOrderRequest() Message to be send:\n{0}", OpenApiMessagesPresentation.ToString(_msg));
            }
            writeQueue.Enqueue(Utils.Serialize(_msg));
        }
Exemplo n.º 28
0
        // listener thread
        private void Listen(SslStream sslStream, Queue messagesQueue)
        {
            isShutdown = false;
            while (!isShutdown)
            {
                Thread.Sleep(1);

                byte[] _length   = new byte[sizeof(int)];
                int    readBytes = 0;
                do
                {
                    Thread.Sleep(0);
                    readBytes += sslStream.Read(_length, readBytes, _length.Length - readBytes);
                } while (readBytes < _length.Length);

                int length = BitConverter.ToInt32(_length.Reverse().ToArray(), 0);
                if (length <= 0)
                {
                    continue;
                }

                if (length > MaxMessageSize)
                {
                    string exceptionMsg = "Message length " + length.ToString() + " is out of range (0 - " + MaxMessageSize.ToString() + ")";
                    throw new System.IndexOutOfRangeException();
                }

                byte[] _message = new byte[length];
                readBytes = 0;
                do
                {
                    Thread.Sleep(0);
                    readBytes += sslStream.Read(_message, readBytes, _message.Length - readBytes);
                } while (readBytes < length);
                var msgFactory   = new OpenApiMessagesFactory();
                var protoMessage = msgFactory.GetMessage(_message);
                messagesQueue.Enqueue("Received: " + OpenApiMessagesPresentation.ToString(protoMessage));
                switch ((ProtoOAPayloadType)protoMessage.PayloadType)
                {
                case ProtoOAPayloadType.PROTO_OA_EXECUTION_EVENT:
                    var _payload_msg = msgFactory.GetExecutionEvent(_message);
                    if (_payload_msg.HasOrder)
                    {
                        testOrderId = _payload_msg.Order.OrderId;
                    }
                    if (_payload_msg.HasPosition)
                    {
                        testPositionId = _payload_msg.Position.PositionId;
                    }
                    break;

                case ProtoOAPayloadType.PROTO_OA_GET_ACCOUNTS_BY_ACCESS_TOKEN_RES:
                    var _accounts_list = ProtoOAGetAccountListByAccessTokenRes.CreateBuilder().MergeFrom(protoMessage.Payload).Build();
                    _accounts = _accounts_list.CtidTraderAccountList;

                    break;

                case ProtoOAPayloadType.PROTO_OA_TRADER_RES:
                    var trader = ProtoOATraderRes.CreateBuilder().MergeFrom(protoMessage.Payload).Build();
                    _traders.Add(trader.Trader);
                    break;

                default:
                    break;
                }
                ;
            }
        }
Exemplo n.º 29
0
        void SendClosePositionRequest(OpenApiMessagesFactory msgFactory, Queue writeQueue)
        {
            var _msg = msgFactory.CreateClosePositionRequest(AccountId, AccessToken, positionId, testVolume, clientMsgId);

            if (isDebugIsOn)
            {
                Console.WriteLine("SendClosePositionRequest() Message to be sent:\n{0}", OpenApiMessagesPresentation.ToString(_msg));
            }
            writeQueue.Enqueue(_msg.ToByteArray());
        }
Exemplo n.º 30
0
        void SendSubscribeForSpotsRequest(OpenApiMessagesFactory msgFactory, Queue writeQueue)
        {
            var _msg = msgFactory.CreateSubscribeForSpotsRequest(AccountId, AccessToken, "EURUSD", clientMsgId);

            if (isDebugIsOn)
            {
                Console.WriteLine("SendSubscribeForSpotsRequest() Message to be sent:\n{0}", OpenApiMessagesPresentation.ToString(_msg));
            }
            writeQueue.Enqueue(_msg.ToByteArray());
        }