Exemple #1
0
        public async Task AuthorizeApp(auth.App app)
        {
            VerifyConnection();

            var authRequest = new ProtoOAApplicationAuthReq
            {
                ClientId     = app.ClientId,
                ClientSecret = app.Secret,
            };

            bool isLiveClientAppAuthorized = false;
            bool isDemoClientAppAuthorized = false;

            using var liveDisposable = _liveClient.OfType <ProtoOAApplicationAuthRes>()
                                       .Subscribe(response => isLiveClientAppAuthorized = true);
            using var demoDisposable = _demoClient.OfType <ProtoOAApplicationAuthRes>()
                                       .Subscribe(response => isDemoClientAppAuthorized = true);

            await _liveClient.SendMessage(authRequest, ProtoOAPayloadType.ProtoOaApplicationAuthReq);

            await _demoClient.SendMessage(authRequest, ProtoOAPayloadType.ProtoOaApplicationAuthReq);

            var waitStartTime = DateTime.Now;

            while (!isLiveClientAppAuthorized && !isDemoClientAppAuthorized && DateTime.Now - waitStartTime < TimeSpan.FromSeconds(5))
            {
                await Task.Delay(1000);
            }

            if (!isLiveClientAppAuthorized || !isDemoClientAppAuthorized)
            {
                throw new TimeoutException("The API didn't responded");
            }
        }
        public ProtoMessage CreateAppAuthorizationRequest(string clientId, string clientSecret, string clientMsgId = null)
        {
            var _msg = ProtoOAApplicationAuthReq.CreateBuilder();

            _msg.SetClientId(clientId);
            _msg.SetClientSecret(clientSecret);
            return(CreateMessage((uint)_msg.PayloadType, _msg.Build().ToByteString(), clientMsgId));
        }
Exemple #3
0
        public static ProtoMessage Application_Auth_Req(string clientId,
                                                        string clientSecret)
        {
            ProtoOAApplicationAuthReq message = new ProtoOAApplicationAuthReq
            {
                payloadType  = ProtoOAPayloadType.ProtoOaApplicationAuthReq,
                clientId     = clientId,
                clientSecret = clientSecret
            };

            Log.Info("ProtoOAApplicationAuthReq:: " +
                     $"clientId: {clientId}; " +
                     $"clientSecret: {clientSecret}");

            InnerMemoryStream.SetLength(0);
            Serializer.Serialize(InnerMemoryStream, message);

            return(Encode((uint)message.payloadType, InnerMemoryStream.ToArray()));
        }
Exemple #4
0
        public async void AppAuthTest(string host, int port, string appId, string appSecret)
        {
            if (string.IsNullOrWhiteSpace(appId))
            {
                throw new ArgumentException($"'{nameof(appId)}' cannot be null or whitespace", nameof(appId));
            }

            if (string.IsNullOrWhiteSpace(appSecret))
            {
                throw new ArgumentException($"'{nameof(appSecret)}' cannot be null or whitespace", nameof(appSecret));
            }

            var client = new OpenClient(host, port, TimeSpan.FromSeconds(10));

            await client.Connect();

            var isResponseReceived = false;

            Exception exception = null;

            client.OfType <ProtoOAApplicationAuthRes>().Subscribe(message => isResponseReceived = true, ex => exception = ex);

            var appAuhRequest = new ProtoOAApplicationAuthReq
            {
                ClientId     = appId,
                ClientSecret = appSecret
            };

            await client.SendMessage(appAuhRequest, ProtoOAPayloadType.ProtoOaApplicationAuthReq);

            await Task.Delay(3000);

            client.Dispose();

            Assert.True(isResponseReceived && exception is null);
        }
 public ProtoOAApplicationAuthReq GetApplicationAuthorizationRequest(byte[] msg = null)
 {
     return(ProtoOAApplicationAuthReq.CreateBuilder().MergeFrom(GetPayload(msg)).Build());
 }
Exemple #6
0
        private static async Task Main()
        {
            Console.Write("Enter App ID: ");

            var appId = Console.ReadLine();

            Console.Write("Enter App Secret: ");

            var appSecret = Console.ReadLine();

            Console.Write("Enter App Redirect URL: ");

            var redirectUrl = Console.ReadLine();

            _app = new App(appId, appSecret, redirectUrl);

            Console.Write("Enter Connection Mode (Live or Demo): ");

            var connectionMode = Console.ReadLine();

            var mode = (Mode)Enum.Parse(typeof(Mode), connectionMode, true);

            var auth = new Auth(_app, mode: mode);

            System.Diagnostics.Process.Start("explorer.exe", $"\"{auth.AuthUri}\"");

            ShowDashLine();

            Console.WriteLine("Follow the authentication steps on your browser, then copy the authentication code from redirect" +
                              " URL and paste it here.");

            Console.WriteLine("The authentication code is at the end of redirect URL and it starts after '?code=' parameter.");

            ShowDashLine();

            Console.Write("Enter Authentication Code: ");

            var code = Console.ReadLine();

            var authCode = new AuthCode(code, _app);

            _token = TokenFactory.GetToken(authCode);

            Console.WriteLine("Access token generated");

            ShowDashLine();

            _client = new Client();

            _streamDisposables.Add(_client.Streams.MessageStream.Subscribe(OnMessageReceived));
            _streamDisposables.Add(_client.Streams.ErrorStream.Subscribe(OnError));

            _streamDisposables.Add(_client.Streams.ListenerExceptionStream.Subscribe(OnListenerException));

            _streamDisposables.Add(_client.Streams.SenderExceptionStream.Subscribe(OnSenderException));

            _streamDisposables.Add(_client.Streams.RefreshTokenResponseStream.Subscribe(OnRefreshTokenResponse));

            Console.WriteLine("Connecting Client...");

            await _client.Connect(mode);

            ShowDashLine();

            Console.WriteLine("Client successfully connected");

            ShowDashLine();

            Console.WriteLine("Sending App Auth Req...");

            Console.WriteLine("Please wait...");

            ShowDashLine();

            var applicationAuthReq = new ProtoOAApplicationAuthReq
            {
                ClientId     = _app.ClientId,
                ClientSecret = _app.Secret,
            };

            await _client.SendMessage(applicationAuthReq, ProtoOAPayloadType.ProtoOaApplicationAuthReq);

            await Task.Delay(5000);

            Console.WriteLine("You should see the application auth response message before entering any command");

            Console.WriteLine("For commands list and description use 'help' command");

            ShowDashLine();

            GetCommand();
        }
        static string OpenApiMessageToString(ProtoMessage msg)
        {
            switch ((ProtoOAPayloadType)msg.PayloadType)
            {
            case ProtoOAPayloadType.PROTO_OA_APPLICATION_AUTH_REQ:
                var app_auth_req = ProtoOAApplicationAuthReq.CreateBuilder().MergeFrom(msg.Payload).Build();
                return("AppAuthRequest{clientId:" + app_auth_req.ClientId + ", clientSecret:" + app_auth_req.ClientSecret + "}");

            case ProtoOAPayloadType.PROTO_OA_APPLICATION_AUTH_RES:
                return("ApAuthResponse");

            case ProtoOAPayloadType.PROTO_OA_ACCOUNT_AUTH_REQ:
                var acc_auth_req = ProtoOAAccountAuthReq.CreateBuilder().MergeFrom(msg.Payload).Build();
                return("AccAuthRequest{CtidTraderAccountId:" + acc_auth_req.CtidTraderAccountId + "}");

            case ProtoOAPayloadType.PROTO_OA_ACCOUNT_AUTH_RES:
                return("AccAuthResponse");

            case ProtoOAPayloadType.PROTO_OA_GET_ACCOUNTS_BY_ACCESS_TOKEN_REQ:
                return("GetAccountsByAccessTokenReq");

            case ProtoOAPayloadType.PROTO_OA_GET_ACCOUNTS_BY_ACCESS_TOKEN_RES:
                var accounts_list = ProtoOAGetAccountListByAccessTokenRes.CreateBuilder().MergeFrom(msg.Payload).Build();
                var sbAccounts    = new StringBuilder();
                foreach (var account in accounts_list.CtidTraderAccountList)
                {
                    sbAccounts.Append("ID: " + account.CtidTraderAccountId + (account.IsLive ? " Status: Live" + Environment.NewLine : " Status: Demo " + Environment.NewLine));
                }
                return("GetAccountsByAccessTokenRes{" + sbAccounts.ToString() + "}");

            case ProtoOAPayloadType.PROTO_OA_TRADER_REQ:
                return("PotoOATraderReq");

            case ProtoOAPayloadType.PROTO_OA_SYMBOLS_LIST_REQ:
                return("GetSymbolsList");

            case ProtoOAPayloadType.PROTO_OA_SYMBOLS_LIST_RES:
                var symbols_list = ProtoOASymbolsListRes.CreateBuilder().MergeFrom(msg.Payload).Build();
                var sbSymbols    = new StringBuilder();
                foreach (var symbol in symbols_list.SymbolList)
                {
                    sbSymbols.Append("ID: " + symbol.SymbolId + Environment.NewLine);
                    sbSymbols.Append("Name: " + symbol.SymbolName + Environment.NewLine);
                }
                return("Symbols{" + sbSymbols.ToString() + "}");

            case ProtoOAPayloadType.PROTO_OA_SYMBOL_BY_ID_REQ:
                return("GetSymbolsById");

            case ProtoOAPayloadType.PROTO_OA_SYMBOL_BY_ID_RES:
                var symbol_by_id_list = ProtoOASymbolByIdRes.CreateBuilder().MergeFrom(msg.Payload).Build();
                var sbSymbolByID      = new StringBuilder();
                foreach (var symbol in symbol_by_id_list.SymbolList)
                {
                    sbSymbolByID.Append("ID: " + symbol.SymbolId + Environment.NewLine);
                }
                return("Symbols{" + sbSymbolByID.ToString() + "}");

            case ProtoOAPayloadType.PROTO_OA_EXECUTION_EVENT:
                return(OpenApiExecEventsToString(msg));

            case ProtoOAPayloadType.PROTO_OA_DEAL_LIST_REQ:
                return("DealListRequest{}");

            case ProtoOAPayloadType.PROTO_OA_DEAL_LIST_RES:
                var deal_list = ProtoOADealListRes.CreateBuilder().MergeFrom(msg.Payload).Build();
                var sbDeals   = new StringBuilder();
                foreach (var deal in deal_list.DealList)
                {
                    sbDeals.Append("ID: " + deal.DealId + Environment.NewLine);
                    sbDeals.Append("Status: " + deal.DealStatus + Environment.NewLine);
                    sbDeals.Append("Volume: " + deal.Volume + Environment.NewLine);
                }
                return("DealList{" + sbDeals.ToString() + "}");

            case ProtoOAPayloadType.PROTO_OA_RECONCILE_REQ:
                return("ReconcileRequest{}");

            case ProtoOAPayloadType.PROTO_OA_RECONCILE_RES:
                var reconcile_response = ProtoOAReconcileRes.CreateBuilder().MergeFrom(msg.Payload).Build();
                var sbReconcile        = new StringBuilder();
                foreach (var order in reconcile_response.OrderList)
                {
                    sbReconcile.Append("ID: " + order.OrderId + Environment.NewLine);
                    sbReconcile.Append("Status: " + order.OrderStatus + Environment.NewLine);
                    sbReconcile.Append("Volume: " + order.TradeData.Volume + Environment.NewLine);
                }
                foreach (var position in reconcile_response.PositionList)
                {
                    sbReconcile.Append("ID: " + position.HasPositionId + Environment.NewLine);
                    sbReconcile.Append("Status: " + position.PositionStatus + Environment.NewLine);
                    sbReconcile.Append("Volume: " + position.TradeData.Volume + Environment.NewLine);
                }
                return("ReconcileList{" + sbReconcile.ToString() + "}");

            case ProtoOAPayloadType.PROTO_OA_CASH_FLOW_HISTORY_LIST_REQ:
                return("CashFlowHistoryRequest{}");

            case ProtoOAPayloadType.PROTO_OA_CASH_FLOW_HISTORY_LIST_RES:
                var cashflow_history = ProtoOACashFlowHistoryListRes.CreateBuilder().MergeFrom(msg.Payload).Build();
                var sbDCashflow      = new StringBuilder();
                foreach (var entry in cashflow_history.DepositWithdrawList)
                {
                    sbDCashflow.Append("ID: " + entry.BalanceHistoryId + Environment.NewLine);
                    sbDCashflow.Append("Type: " + entry.OperationType + Environment.NewLine);
                    sbDCashflow.Append("Delta: " + entry.Delta + Environment.NewLine);
                }
                return("CashFlowHistory{" + sbDCashflow.ToString() + "}");

            case ProtoOAPayloadType.PROTO_OA_GET_TRENDBARS_REQ:
                return("GetTrendbarsRequest{}");

            case ProtoOAPayloadType.PROTO_OA_GET_TRENDBARS_RES:
                var trendbar   = ProtoOAGetTrendbarsRes.CreateBuilder().MergeFrom(msg.Payload).Build();
                var sbTrendbar = new StringBuilder();
                foreach (var entry in trendbar.TrendbarList)
                {
                    sbTrendbar.Append("Open: " + entry.DeltaOpen + Environment.NewLine);
                    sbTrendbar.Append("High: " + entry.DeltaHigh + Environment.NewLine);
                    sbTrendbar.Append("Low: " + entry.Low + Environment.NewLine);
                    sbTrendbar.Append("Close: " + entry.DeltaClose + Environment.NewLine);
                }
                return("Trendbars{" + sbTrendbar.ToString() + "}");

            case ProtoOAPayloadType.PROTO_OA_GET_TICKDATA_REQ:
                return("GetTickDataRequest{}");

            case ProtoOAPayloadType.PROTO_OA_GET_TICKDATA_RES:
                var tickData   = ProtoOAGetTickDataRes.CreateBuilder().MergeFrom(msg.Payload).Build();
                var sbTickData = new StringBuilder();
                foreach (var entry in tickData.TickDataList)
                {
                    sbTickData.Append("Tick: " + entry.Tick + Environment.NewLine + " " + msg.ClientMsgId);
                }
                return("Tick Data{" + sbTickData.ToString() + "}");

            case ProtoOAPayloadType.PROTO_OA_CANCEL_ORDER_REQ:
                return("CancelOrderRequest{}");

            case ProtoOAPayloadType.PROTO_OA_NEW_ORDER_REQ:
                return("CreateOrderRequest{}");

            case ProtoOAPayloadType.PROTO_OA_CLOSE_POSITION_REQ:
                return("ClosePositionRequest{}");

            case ProtoOAPayloadType.PROTO_OA_AMEND_ORDER_REQ:
                return("AmendOrderRequest{}");

            case ProtoOAPayloadType.PROTO_OA_AMEND_POSITION_SLTP_REQ:
                return("AmendPositionRequest{}");

            case ProtoOAPayloadType.PROTO_OA_SUBSCRIBE_SPOTS_REQ:
                return("SubscribeForSpotsRequest{}");

            case ProtoOAPayloadType.PROTO_OA_SUBSCRIBE_SPOTS_RES:
                return("SubscribeForSpotsResponse{}");

            case ProtoOAPayloadType.PROTO_OA_UNSUBSCRIBE_SPOTS_REQ:
                return("UnsubscribeFromSpotsRequest{}");

            case ProtoOAPayloadType.PROTO_OA_UNSUBSCRIBE_SPOTS_RES:
                return("UnsubscribeFromSpotsResponse{}");

            case ProtoOAPayloadType.PROTO_OA_SPOT_EVENT:
                var _spot_event = ProtoOASpotEvent.CreateBuilder().MergeFrom(msg.Payload).Build();
                return("SpotEvent{symbolId:" + _spot_event.SymbolId + ", bidPrice:" + (_spot_event.HasBid ? _spot_event.Bid.ToString() : "       ") + ", askPrice:" + (_spot_event.HasAsk ? _spot_event.Ask.ToString() : "       ") + "}");

            case ProtoOAPayloadType.PROTO_OA_ERROR_RES:
                var _err = ProtoOAErrorRes.CreateBuilder().MergeFrom(msg.Payload).Build();
                return("ErrorResponse{errorCode:" + _err.ErrorCode + (_err.HasDescription ? ", description:" + _err.Description : "") + "}");

            case ProtoOAPayloadType.PROTO_OA_ORDER_ERROR_EVENT:
                var _orderErr = ProtoOAOrderErrorEvent.CreateBuilder().MergeFrom(msg.Payload).Build();
                return("OrderErrorResponse{errorCode:" + _orderErr.ErrorCode + (_orderErr.HasDescription ? ", description:" + _orderErr.Description : "") + "}");

            default:
                return("unknown");
            }
        }
Exemple #8
0
        private static async Task Main()
        {
            Console.Write("Enter App ID: ");

            var appId = Console.ReadLine();

            Console.Write("Enter App Secret: ");

            var appSecret = Console.ReadLine();

            Console.Write("Enter App Redirect URL: ");

            var redirectUrl = Console.ReadLine();

            _app = new App(appId, appSecret, redirectUrl);

            Console.Write("Enter Connection Mode (Live or Demo): ");

            var modeString = Console.ReadLine();

            var mode = (Mode)Enum.Parse(typeof(Mode), modeString, true);

            Console.Write("Enter Scope (Trading or Accounts): ");

            var scopeString = Console.ReadLine();

            var scope = (Scope)Enum.Parse(typeof(Scope), scopeString, true);

            var authUri = _app.GetAuthUri();

            System.Diagnostics.Process.Start("explorer.exe", $"\"{authUri}\"");

            ShowDashLine();

            Console.WriteLine("Follow the authentication steps on your browser, then copy the authentication code from redirect" +
                              " URL and paste it here.");

            Console.WriteLine("The authentication code is at the end of redirect URL and it starts after '?code=' parameter.");

            ShowDashLine();

            Console.Write("Enter Authentication Code: ");

            var authCode = Console.ReadLine();

            _token = await TokenFactory.GetToken(authCode, _app);

            Console.WriteLine("Access token generated");

            ShowDashLine();

            var host = ApiInfo.GetHost(mode);

            _client = new OpenClient(host, ApiInfo.Port, TimeSpan.FromSeconds(10));

            _disposables.Add(_client.Where(iMessage => iMessage is not ProtoHeartbeatEvent).Subscribe(OnMessageReceived, OnException));
            _disposables.Add(_client.OfType <ProtoOAErrorRes>().Subscribe(OnError));
            _disposables.Add(_client.OfType <ProtoOARefreshTokenRes>().Subscribe(OnRefreshTokenResponse));

            Console.WriteLine("Connecting Client...");

            await _client.Connect();

            ShowDashLine();

            Console.WriteLine("Client successfully connected");

            ShowDashLine();

            Console.WriteLine("Sending App Auth Req...");

            Console.WriteLine("Please wait...");

            ShowDashLine();

            var applicationAuthReq = new ProtoOAApplicationAuthReq
            {
                ClientId     = _app.ClientId,
                ClientSecret = _app.Secret,
            };

            await _client.SendMessage(applicationAuthReq, ProtoOAPayloadType.ProtoOaApplicationAuthReq);

            await Task.Delay(5000);

            Console.WriteLine("You should see the application auth response message before entering any command");

            Console.WriteLine("For commands list and description use 'help' command");

            ShowDashLine();

            GetCommand();
        }