private static IPlayerGateway InitPlayerGateway()
        {
            using (ILogMethod method = Log.LogMethod("HandlerHelper", "InitPlayerGateway"))
            {
                IPlayerGateway gateway = default(IPlayerGateway);

                try
                {
                    gateway = GatewayFactory.GetGateway(GatewayType.SDT);
                    gateway.Initialize();

                    gateway.SocketSenderPT2.ReceiveTimeout = GatewaySettings.PTAsyncReceiveTimeout;
                    gateway.SocketSenderPT.ReceiveTimeout  = GatewaySettings.PTAsyncReceiveTimeout;
                    gateway.SocketSenderCA2.ReceiveTimeout = GatewaySettings.CAAsyncReceiveTimeout;
                    gateway.SocketSenderCA.ReceiveTimeout  = GatewaySettings.CAAsyncReceiveTimeout;

                    gateway.SocketSenderPT.Initialize(_configStore.PT_GATEWAY_IP, _configStore.SDT_SendPTPortNo);
                    gateway.SocketSenderPT2.Initialize(_configStore.PT_GATEWAY_IP, _configStore.SDT_ReceivePTPortNo);
                    gateway.SocketSenderCA.Initialize(_configStore.PT_GATEWAY_IP, _configStore.SDT_SendCAPortNo);
                    gateway.SocketSenderCA2.Initialize(_configStore.PT_GATEWAY_IP, _configStore.SDT_ReceiveCAPortNo);

                    if (GatewaySettings.SocketSendWithoutReconnect)
                    {
                        gateway.SocketSenderPT.SendTimeout = GatewaySettings.PTAsyncSendTimeout;
                        gateway.SocketSenderCA.SendTimeout = GatewaySettings.CAAsyncSendTimeout;
                    }
                }
                catch (Exception ex)
                {
                    method.Exception(ex);
                }

                return(gateway);
            }
        }
        // Open a database, or return empty object if null
        public DatabaseConnector OpenDatabase(string name = null, bool load = true)
        {
            if (IsTest)
            {
                return new DatabaseConnector {
                           Selector = this, Name = TestDatabaseSearchPath
                }
            }
            ;
            if (name == null)
            {
                return new DatabaseConnector {
                           Selector = this, Name = ""
                }
            }
            ;
            try {
                _settings["Load"] = load.ToString();

                var gateway = GatewayFactory.Create(name, _settings);
                gateway.OpenSession();
                return(new DatabaseConnector {
                    Selector = this, Name = name, Gateway = gateway
                });
            } catch (ProgramException e) {
                var msg = string.Format("Error: {0}", e.Message);
                MessageBox.Show(msg, "Database error");
                return(new DatabaseConnector {
                    Selector = this, Name = name
                });
            }
        }
示例#3
0
        void ShowCatalog()
        {
            var api = GatewayFactory.Create(DatabaseName, _settingsdict);

            byte[] result;
            var    ret = api.NativeCall("andl_catalog", new byte[0], out result);
        }
示例#4
0
        /// <summary>
        /// Get Billing Token in exchange of Credit Card and Billing Information
        /// </summary>
        /// <param name="tokenRequest">TokenRequest containing billing information</param>
        /// <returns>TokenResponse</returns>
        public async Task <TokenResponse> get(TokenRequest tokenRequest, bool isPreProd)
        {
            try
            {
                var context = new ValidationContext(tokenRequest);
                var results = new List <ValidationResult>();

                var isValid = Validator.TryValidateObject(tokenRequest, context, results, true);

                if (!isValid)
                {
                    TokenResponse tokenResponse = new TokenResponse();
                    foreach (var validationResult in results)
                    {
                        tokenResponse.addError(new Error(string.Join(", ", validationResult.MemberNames), validationResult.ErrorMessage));
                    }
                    return(await Task.FromResult <TokenResponse>(tokenResponse));
                }
                else
                {
                    BillingGateway billingGateway = GatewayFactory.getBillingGateway(billingProvider);

                    return(await billingGateway.getBillingToken(tokenRequest, isPreProd));
                }
            }
            catch (Exception ex)
            {
                TokenResponse tokenResponse = new TokenResponse();
                tokenResponse.addError(new Error("unknown", "Unknown Exception"));
                return(tokenResponse);
            }
        }
示例#5
0
 internal void Repl()
 {
     _api = GatewayFactory.Create(DatabaseName, _settingsdict);
     for (; ;)
     {
         Console.Write(">>>");
         var line = Console.ReadLine();
         Run(line);
     }
 }
示例#6
0
        public PaymentStatusVM ProcessPaymentRequest(PaymentRequestVM paymentRequest)
        {
            GatewayFactory gatewayFactory = new GatewayFactory(unitOfWork);

            IPaymentGateway paymentGateway = gatewayFactory.GetPaymentGateway(paymentRequest.Amount);

            PaymentInfo pi = mapper.Map <PaymentRequestVM, PaymentInfo>(paymentRequest);

            return(paymentGateway.ProcessPayment(pi));
        }
示例#7
0
        void CallFunc()
        {
            var api  = GatewayFactory.Create(DatabaseName, _settingsdict);
            var args = ArgWriter.Create().Put("abcdef").Out();

            byte[] result;
            var    ret = api.NativeCall("func", args, out result);
            var    rr  = ResultReader.Create(result);

            Console.WriteLine("Result={0}", rr.ReadText());
        }
 public void ResolveGatewayTests(Gateway identifier, bool success)
 {
     if (!success)
     {
         Assert.Throws <NotImplementedException>(() => GatewayFactory.ResolveGateway(identifier));
     }
     else
     {
         var gateway = GatewayFactory.ResolveGateway(identifier);
         Assert.NotNull(gateway);
     }
 }
示例#9
0
        /// <summary>
        /// Connects the client to the broker's remote servers
        /// </summary>
        public override void Connect()
        {
            if (IsConnected)
            {
                return;
            }

            Log.Trace("FxcmBrokerage.Connect()");

            _cancellationTokenSource = new CancellationTokenSource();

            // create new thread to fire order events in queue
            _orderEventThread = new Thread(() =>
            {
                while (!_cancellationTokenSource.IsCancellationRequested)
                {
                    OrderEvent orderEvent;
                    if (!_orderEventQueue.TryDequeue(out orderEvent))
                    {
                        Thread.Sleep(1);
                        continue;
                    }

                    OnOrderEvent(orderEvent);
                }
            });
            _orderEventThread.Start();
            while (!_orderEventThread.IsAlive)
            {
                Thread.Sleep(1);
            }

            // create the gateway
            _gateway = GatewayFactory.createGateway();

            // register the message listeners with the gateway
            _gateway.registerGenericMessageListener(this);
            _gateway.registerStatusMessageListener(this);

            // create local login properties
            var loginProperties = new FXCMLoginProperties(_userName, _password, _terminal, _server);

            // log in
            _gateway.login(loginProperties);

            // load instruments, accounts, orders, positions
            LoadInstruments();
            LoadAccounts();
            LoadOpenOrders();
            LoadOpenPositions();
        }
示例#10
0
        public async Task <ServiceResult <OrderDto> > ProcessInternalAsync(OrderDto order)
        {
            var gateway = GatewayFactory.ResolveGateway(order.PaymentGateway);

            if (gateway == null)
            {
                return(new ServiceResult <OrderDto>(
                           new ApiError($"{nameof(order.PaymentGateway)} is not yet implemented"),
                           HttpStatusCode.BadGateway));
            }

            var result = await gateway.ProcessAsync(order);

            return(Map(result, order));
        }
 public CPlayerData()
 {
     InitializeComponent();
     cmbMessageTypes.ItemsSource = GetMessageTypes();
     LogManager.WriteLog("CPlayerData[GateWay Initializing]", LogManager.enumLogLevel.Debug);
     try
     {
         BMC.PlayerGateway.SharedData.ActiveLogger.WriteToExternalLog += new BMC.PlayerGateway.WriteToExternalLogHandler(ActiveLogger_WriteToExternalLog);
         BMC.PlayerGateway.GatewaySettings.GlobalExecutorService       = ExecutorServiceFactory.CreateExecutorService();
         oGateWay = GatewayFactory.GetGateway(GatewayType.SDT);
         BMC.PlayerGateway.GatewaySettings.ConnectionString = oCommonUtilities.CreateInstance().GetConnectionString();
         oGateWay.Initialize(true);
         oGateWay.SocketSenderPT.Initialize(Settings.PT_GATEWAY_IP, Settings.SDT_SendPTPortNo);
         oGateWay.SocketSenderCA.Initialize(Settings.PT_GATEWAY_IP, Settings.SDT_SendCAPortNo);
         LogManager.WriteLog("CPlayerData[GateWay Initialized]", LogManager.enumLogLevel.Debug);
     }
     catch (Exception Ex)
     {
         ExceptionManager.Publish(Ex);
     }
 }
示例#12
0
        bool FindSupplier(string id, out Supplier[] supplier)
        {
            var api = GatewayFactory.Create(DatabaseName, _settingsdict);

            byte[] args = ArgWriter.Create().Put(id).Out();
            byte[] result;
            supplier = null;
            if (!api.NativeCall("find_supplier", args, out result))
            {
                return(false);
            }
            int n;
            var r = ResultReader.Create(result).Get(out n);

            supplier = new Supplier[n];
            for (int i = 0; i < n; ++i)
            {
                supplier[i] = new Supplier();
                r.Get(out supplier[i].SNAME).Get(out supplier[i].STATUS).Get(out supplier[i].CITY).Get(out supplier[i].Sid);
            }
            return(true);
        }
示例#13
0
        /// <summary>
        /// 基本执行调用方法
        /// </summary>
        /// <param name="sessionId">sessionId</param>
        /// <param name="jsonRpc">请求内容</param>
        /// <param name="context">请求上下文</param>
        /// <returns>执行结果(空则无错误信息)</returns>
        private static string Execute(string sessionId, string jsonRpc, object context)
        {
            var handler = Handler.GetSessionHandler(sessionId);

            try
            {
                //从请求内容中构建请求与响应上下文,转换请求上下文
                Tuple <JsonRpcRequestContext, JsonRpcResponseContext>[] batch = null;
                if (IsSingle(jsonRpc))
                {
                    batch = new[] { Tuple.Create(JsonConvert.DeserializeObject <JsonRpcRequestContext>(jsonRpc), new JsonRpcResponseContext()) };
                }
                else
                {
                    batch = JsonConvert.DeserializeObject <JsonRpcRequestContext[]>(jsonRpc)
                            .Select(request => new Tuple <JsonRpcRequestContext, JsonRpcResponseContext>(request, new JsonRpcResponseContext()))
                            .ToArray();

                    if (batch.Length > 1)
                    {
                        //将所有请求上下文Tags都赋值为第一个请求上下文的Tags
                        Dictionary <string, object> firstTags = batch[0].Item1.Tags;
                        for (int i = 1; i < batch.Length; i++)
                        {
                            batch[i].Item1.Tags = firstTags;
                        }
                    }
                }

                //基本验证
                if (batch.Length == 0)
                {
                    return(JsonConvert.SerializeObject(new JsonRpcResponseContext
                    {
                        Error = handler.ProcessParseException(jsonRpc,
                                                              new JsonRpcException(-32600, "无效请求", "请求调用为空", jsonRpc))
                    }));
                }

                //网关预处理
                try
                {
                    var gateways = GatewayFactory.GetGateways();
                    foreach (var gateway in gateways)
                    {
                        gateway.PreProcess(jsonRpc);
                    }
                }
                catch (AuthenticationException ex)
                {
                    return(JsonConvert.SerializeObject(new JsonRpcResponseContext
                    {
                        Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32600, ex.Message, ex.ToString(), jsonRpc))
                    }));
                }
                catch (JsonRpcException ex)
                {
                    ex.rpcRequestRaw = jsonRpc;
                    return(JsonConvert.SerializeObject(new JsonRpcResponseContext
                    {
                        Error = handler.ProcessParseException(jsonRpc, ex)
                    }));
                }
                catch (Exception ex)
                {
                    return(JsonConvert.SerializeObject(new JsonRpcResponseContext
                    {
                        Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32603, "内部错误", ex.Message, jsonRpc))
                    }));
                }

                //循环请求上下文,并调用Handler处理请求
                foreach (var tuple in batch)
                {
                    var requestContext  = tuple.Item1;
                    var responseContext = tuple.Item2;
                    if (requestContext == null)
                    {
                        responseContext.Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32700, "转换错误", "服务器接收到无效的json文本,解析json文本时服务器出现错误", jsonRpc));
                    }
                    else
                    {
                        responseContext.Id = requestContext.Id;
                        if (string.IsNullOrWhiteSpace(requestContext.Method))
                        {
                            responseContext.Error = handler.ProcessParseException(jsonRpc,
                                                                                  new JsonRpcException(-32600, "无效请求", "未检测到'Method'", jsonRpc));
                        }
                        else
                        {
                            var response = handler.Handle(requestContext, context);
                            if (response == null)
                            {
                                continue;
                            }
                            responseContext.Error  = response.Error;
                            responseContext.Result = response.Result;
                        }
                    }
                }

                //提取所有错误并返回
                var responses  = new string[0];
                var batchError = batch.Where(x => x.Item2.Id != null || x.Item2.Error != null);
                if (batchError != null)
                {
                    var index = 0;
                    responses = new string[batchError.Count()];
                    foreach (var item in batchError)
                    {
                        responses[index++] = JsonConvert.SerializeObject(item.Item2);
                    }
                }
                return(responses.Length == 0 ? string.Empty : responses.Length == 1 ? responses[0] : string.Format("[{0}]", string.Join(",", responses)));
            }
            catch (Exception ex)
            {
                return(JsonConvert.SerializeObject(new JsonRpcResponseContext
                {
                    Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32700, "转换错误", ex, jsonRpc))
                }));
            }
        }
示例#14
0
 static GatewayBase AppStartup(string database, Dictionary <string, string> settings)
 {
     //var appsettings = ConfigurationManager.AppSettings;
     return(GatewayFactory.Create(database, settings));
 }
示例#15
0
        /// <summary>
        /// Get historical data enumerable for a single symbol, type and resolution given this start and end time (in UTC).
        /// </summary>
        /// <param name="symbol">Symbol for the data we're looking for.</param>
        /// <param name="type">Security type</param>
        /// <param name="resolution">Resolution of the data request</param>
        /// <param name="startUtc">Start time of the data in UTC</param>
        /// <param name="endUtc">End time of the data in UTC</param>
        /// <returns>Enumerable of base data for this symbol</returns>
        public IEnumerable <BaseData> Get(Symbol symbol, SecurityType type, Resolution resolution, DateTime startUtc, DateTime endUtc)
        {
            if (!_instruments.ContainsKey(symbol.Value))
            {
                throw new ArgumentException("Invalid symbol requested: " + symbol.Value);
            }

            if (resolution == Resolution.Tick)
            {
                throw new NotSupportedException("Resolution not available: " + resolution);
            }

            if (type != SecurityType.Forex && type != SecurityType.Cfd)
            {
                throw new NotSupportedException("SecurityType not available: " + type);
            }

            if (endUtc < startUtc)
            {
                throw new ArgumentException("The end date must be greater or equal than the start date.");
            }

            Console.WriteLine("Logging in...");

            // create the gateway
            _gateway = GatewayFactory.createGateway();

            // register the message listeners with the gateway
            _gateway.registerGenericMessageListener(this);
            _gateway.registerStatusMessageListener(this);

            // create local login properties
            var loginProperties = new FXCMLoginProperties(_userName, _password, _terminal, _server);

            // log in
            _gateway.login(loginProperties);

            // initialize session
            RequestTradingSessionStatus();

            Console.WriteLine("Downloading data from {0} to {1}...", startUtc.ToShortDateString(), endUtc.ToShortDateString());

            // download bars
            var totalBars = new List <TradeBar>();

            // calculate the maximum time span for one request (using 10-second bars)
            const int maxBarsPerRequest  = 300;
            var       timeSpanPerRequest = TimeSpan.FromSeconds(maxBarsPerRequest * 10);

            var start = startUtc;
            var end   = startUtc + timeSpanPerRequest;

            // request loop
            while (start < endUtc.AddDays(1))
            {
                _currentBars.Clear();

                var mdr = new MarketDataRequest();
                mdr.setSubscriptionRequestType(SubscriptionRequestTypeFactory.SNAPSHOT);
                mdr.setResponseFormat(IFixMsgTypeDefs.__Fields.MSGTYPE_FXCMRESPONSE);
                mdr.setFXCMTimingInterval(FXCMTimingIntervalFactory.SEC10);
                mdr.setMDEntryTypeSet(MarketDataRequest.MDENTRYTYPESET_ALL);

                mdr.setFXCMStartDate(new UTCDate(ToJavaDateUtc(start)));
                mdr.setFXCMStartTime(new UTCTimeOnly(ToJavaDateUtc(start)));
                mdr.setFXCMEndDate(new UTCDate(ToJavaDateUtc(end)));
                mdr.setFXCMEndTime(new UTCTimeOnly(ToJavaDateUtc(end)));
                mdr.addRelatedSymbol(_fxcmInstruments[_mapInstrumentSymbols[symbol]]);

                AutoResetEvent autoResetEvent;
                lock (_locker)
                {
                    _currentRequest = _gateway.sendMessage(mdr);
                    autoResetEvent  = new AutoResetEvent(false);
                    _mapRequestsToAutoResetEvents[_currentRequest] = autoResetEvent;
                }
                if (!autoResetEvent.WaitOne(1000))
                {
                    // no response, continue loop
                    start = end.AddSeconds(10);
                    // if saturday, fast-forward to sunday
                    if (start.DayOfWeek == DayOfWeek.Saturday)
                    {
                        start = start.AddDays(1);
                    }
                    end = start + timeSpanPerRequest;
                    continue;
                }

                var lastBarTime = _currentBars[_currentBars.Count - 1].Time;
                if (lastBarTime < start)
                {
                    // no more data available, exit loop
                    break;
                }

                // add bars received
                totalBars.AddRange(_currentBars.Where(x => x.Time.Date <= endUtc.Date));

                // calculate time span for next request
                start = lastBarTime.AddSeconds(10);
                end   = start + timeSpanPerRequest;

                if (start >= DateTime.UtcNow)
                {
                    // data in the future not available, exit loop
                    break;
                }
            }

            Console.WriteLine("Logging out...");

            // log out
            _gateway.logout();

            // remove the message listeners
            _gateway.removeGenericMessageListener(this);
            _gateway.removeStatusMessageListener(this);

            switch (resolution)
            {
            case Resolution.Second:
                foreach (var bar in totalBars)
                {
                    yield return(bar);
                }
                break;

            case Resolution.Minute:
            case Resolution.Hour:
            case Resolution.Daily:
                foreach (var bar in AggregateBars(symbol, totalBars, resolution.ToTimeSpan()))
                {
                    yield return(bar);
                }
                break;
            }
        }
示例#16
0
 internal void Exec()
 {
     _api = GatewayFactory.Create(DatabaseName, _settingsdict);
     Run("fact:0(n:0) => if(n<=1,1,n*fact(n-1))");
     Run("fact(6)");
 }
示例#17
0
        /// <summary>
        /// Refunds a specific payment by its Order Number.
        /// </summary>
        /// <param name="refundInvoice">RefundInvoice object</param>
        public static async Task <RefundResult> RefundAsync(RefundInvoice refundInvoice)
        {
            if (refundInvoice == null)
            {
                throw new ArgumentNullException(nameof(refundInvoice));
            }

            var paymentData = await SelectPaymentDataByOrderNumberAsync(refundInvoice.OrderNumber);

            if (paymentData == null)
            {
                return(new RefundResult(0, 0, RefundResultStatus.Failed, $"No payment found with order's number: {refundInvoice.OrderNumber}"));
            }

            if (refundInvoice.AmountToRefund > paymentData.Amount)
            {
                return(new RefundResult(0, 0, RefundResultStatus.Failed, $"Amount To Refund cannot be greater than original amount. Original Amount: {paymentData.Amount:N0}. Amount To Refund: {refundInvoice.AmountToRefund:N0}"));
            }

            ThrowExceptionIfGatewayIsNotConfigured(paymentData.Gateway);

            var gateway = GatewayFactory.CreateGateway(paymentData.Gateway);

            var amountToRefund = refundInvoice.AmountToRefund > 0 ? refundInvoice.AmountToRefund : paymentData.Amount;

            var gatewayRefundPaymentContext = new GatewayRefundPaymentContext(paymentData.OrderNumber, amountToRefund, paymentData.ReferenceId, paymentData.TransactionId, paymentData.AdditionalData);

            try
            {
                var refundResult = await gateway.RefundAsync(gatewayRefundPaymentContext);

                //  Log
                TryLog(() => new Log
                {
                    Type          = LogType.Refund,
                    Gateway       = paymentData.Gateway,
                    OrderNumber   = paymentData.OrderNumber,
                    Amount        = paymentData.Amount,
                    Message       = refundResult.Message,
                    CreatedOn     = DateTime.Now,
                    ReferenceId   = paymentData.ReferenceId,
                    TransactionId = paymentData.TransactionId,
                    Status        = refundResult.Status.ToString()
                });

                if (refundResult.IsSuccess())
                {
                    paymentData.Status = PaymentDataStatus.Refunded;

                    await UpdatePaymentDataAsync(paymentData);
                }

                return(refundResult);
            }
            catch (Exception exception)
            {
                //  Log
                TryLog(() => new Log
                {
                    Type          = LogType.Error,
                    Gateway       = paymentData.Gateway,
                    OrderNumber   = paymentData.OrderNumber,
                    Amount        = amountToRefund,
                    Message       = exception.Message,
                    CreatedOn     = DateTime.Now,
                    ReferenceId   = paymentData.ReferenceId,
                    TransactionId = paymentData.TransactionId,
                    Status        = string.Empty
                });

                return(new RefundResult(paymentData.Gateway, 0, RefundResultStatus.Failed, exception.Message));
            }
        }
示例#18
0
        /// <summary>
        /// Verifies request that comes from a gateway.
        /// </summary>
        /// <param name="httpContext">HttpContext object of current request.</param>
        /// <param name="verifyInvoiceHandler">This handler would be called before verifying the invoice. You can check the invoice with your database and decide whether or not you should call the Cancel method.</param>
        public static async Task <VerifyResult> VerifyAsync(HttpContext httpContext, Action <VerifyInvoice> verifyInvoiceHandler = null)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            //  1) Get PaymentData's ID from HttpRequest
            if (!httpContext.Request.TryGetPaymentDataId(out var paymentId))
            {
                return(new VerifyResult(0, string.Empty, string.Empty, VerifyResultStatus.NotValid, "Payment's ID is not valid."));
            }

            //  2) Load PaymentData by ID from storage
            var paymentData = await SelectPaymentDataByIdAsync(paymentId);

            if (paymentData == null)
            {
                return(new VerifyResult(0, string.Empty, string.Empty, VerifyResultStatus.NotValid, $"No payment found with ID: {paymentId:N}."));
            }

            ThrowExceptionIfGatewayIsNotConfigured(paymentData.Gateway);

            //  Some paymentData's checks...

            if (paymentData.Status != PaymentDataStatus.Requested)
            {
                if (paymentData.Status == PaymentDataStatus.Verified)
                {
                    return(new VerifyResult(paymentData.Gateway, paymentData.ReferenceId, paymentData.TransactionId, VerifyResultStatus.AlreadyVerified, "The payment is already verified."));
                }

                return(new VerifyResult(paymentData.Gateway, paymentData.ReferenceId, paymentData.TransactionId, VerifyResultStatus.NotValid, "Payment is not valid."));
            }

            if (paymentData.IsExpired())
            {
                return(new VerifyResult(paymentData.Gateway, paymentData.ReferenceId, paymentData.TransactionId, VerifyResultStatus.PaymentTimeExpired, "The time of payment is expired."));
            }

            //  Let developer decides to continue or stop the payment
            if (verifyInvoiceHandler != null)
            {
                var paymentVerify = new VerifyInvoice(paymentData.Gateway, paymentData.OrderNumber, paymentData.ReferenceId);

                verifyInvoiceHandler.Invoke(paymentVerify);

                if (paymentVerify.IsCanceled)
                {
                    //  Log canceling
                    TryLog(() => new Log
                    {
                        Type          = LogType.Verify,
                        Gateway       = paymentData.Gateway,
                        OrderNumber   = paymentData.OrderNumber,
                        Amount        = paymentData.Amount,
                        Message       = paymentVerify.CancellationReason,
                        CreatedOn     = DateTime.Now,
                        ReferenceId   = paymentData.ReferenceId,
                        TransactionId = string.Empty,
                        Status        = VerifyResultStatus.CanceledProgrammatically.ToString()
                    });

                    paymentData.Status = PaymentDataStatus.Failed;

                    //  Update PaymentData in the Storage
                    await UpdatePaymentDataAsync(paymentData);

                    return(new VerifyResult(paymentData.Gateway, paymentData.ReferenceId, paymentData.TransactionId, VerifyResultStatus.CanceledProgrammatically, paymentVerify.CancellationReason));
                }
            }

            //  Making ready data to verify

            //  Incoming request parameters
            IRequestParameters requestParameters = new RequestParameters(httpContext.Request);

            //  Create VerifyContext
            var gatewayVerifyPaymentContext = CreateGatewayVerifyPaymentContext(paymentData, requestParameters);

            //  4) Create gateway from PaymentData's Gateway
            var gateway = GatewayFactory.CreateGateway(paymentData.Gateway);

            //  5) Verify
            var verifyResult = await gateway.VerifyAsync(gatewayVerifyPaymentContext);

            //  Log Verify
            TryLog(() => new Log
            {
                Type          = LogType.Verify,
                Gateway       = paymentData.Gateway,
                OrderNumber   = paymentData.OrderNumber,
                Amount        = paymentData.Amount,
                Message       = verifyResult.Message,
                CreatedOn     = DateTime.Now,
                ReferenceId   = paymentData.ReferenceId,
                TransactionId = verifyResult.TransactionId,
                Status        = verifyResult.Status.ToString()
            });

            //  Update PaymentData
            paymentData.TransactionId = verifyResult.TransactionId;
            paymentData.Status        = verifyResult.IsSuccess() ? PaymentDataStatus.Verified : PaymentDataStatus.Failed;

            //  Save PaymentData to the storage
            await UpdatePaymentDataAsync(paymentData);

            return(verifyResult);
        }
示例#19
0
 public Bridge(BridgeConfiguration configuration, GatewayFactory factory)
 {
     _configuration = configuration;
     _factory       = factory;
 }
示例#20
0
        public void Run()
        {
            _gateway = GatewayFactory.createGateway();

            // register the generic message listener with the gateway
            _gateway.registerGenericMessageListener(this);

            // register the status message listener with the gateway
            _gateway.registerStatusMessageListener(this);

            // attempt to login with the local login properties
            Console.WriteLine("Logging in...");
            var loginProperties = new FXCMLoginProperties(UserName, Password, Terminal, Server);

            // disable the streaming rates (default automatic subscriptions)
            loginProperties.addProperty(IConnectionManager.__Fields.MSG_FLAGS, IFixDefs.__Fields.CHANNEL_MARKET_DATA.ToString());
            _gateway.login(loginProperties);
            Console.WriteLine("Logged in.\n");

            // get instrument list
            Console.WriteLine("Requesting trading session status...");
            lock (_locker)
            {
                _currentRequest = _gateway.requestTradingSessionStatus();
                Console.WriteLine("\tRequestId = {0}\n", _currentRequest);
            }
            _requestTradingSessionStatusEvent.WaitOne();
            Console.WriteLine("Instruments: {0}\n", _securities.Count);
            foreach (var pair in _securities)
            {
                var security = pair.Value;

                Console.WriteLine(security.getSymbol() + " " +
                                  security.getCurrency() + " " +
                                  security.getFXCMSubscriptionStatus() + " " +
                                  security.getRoundLot() + " " +
                                  security.getContractMultiplier() + " " +
                                  security.getFXCMMinQuantity() + " " +
                                  security.getFXCMMaxQuantity() + " " +
                                  security.getFXCMSymPointSize() + " " +
                                  security.getFactor() + " " +
                                  security.getFXCMSymPrecision() + " " +
                                  security.getProduct() + " " +
                                  security.getFXCMProductID() + " " +
                                  (security.getFXCMProductID() == IFixValueDefs.__Fields.FXCMPRODUCTID_FOREX ? "Forex" : "CFD"));
            }
            Console.WriteLine();

            // get account list
            Console.WriteLine("Requesting account list...");
            lock (_locker)
            {
                _currentRequest = _gateway.requestAccounts();
                Console.WriteLine("\tRequestId = {0}\n", _currentRequest);
            }
            _requestAccountListEvent.WaitOne();
            Console.WriteLine("Accounts: {0}\n", _accounts.Count);

            // use first account
            var accountId = _accounts.Keys.First();

            // we are unable to continue if Hedging enabled
            if (_accounts[accountId].getParties().getFXCMPositionMaintenance() == "Y")
            {
                throw new NotSupportedException("The Lean engine does not support accounts with Hedging enabled. Please contact FXCM support to disable Hedging and try again.");
            }

            // get open order list
            Console.WriteLine("Requesting open order list...");
            lock (_locker)
            {
                _currentRequest = _gateway.requestOpenOrders();
                Console.WriteLine("\tRequestId = {0}\n", _currentRequest);
            }
            _requestOrderEvent.WaitOne();
            Console.WriteLine("Open orders: {0}\n", _orders.Keys.Count);

            // cancel all open orders
            if (_orders.Keys.Count > 0)
            {
                Console.WriteLine("Cancelling open orders...");
                foreach (var order in _orders.Values.ToList())
                {
                    Console.WriteLine("Cancelling order {0}...", order.getOrderID());
                    var request = MessageGenerator.generateOrderCancelRequest("", order.getOrderID(), order.getSide(), order.getAccount());
                    lock (_locker)
                    {
                        _currentRequest = _gateway.sendMessage(request);
                        Console.WriteLine("\tRequestId = {0}\n", _currentRequest);
                    }
                    _requestOrderEvent.WaitOne();
                    Console.WriteLine("Order {0} cancelled.", order.getOrderID());
                }
                _orders.Clear();
                Console.WriteLine("Open orders cancelled.\n");
            }

            // get open position list
            Console.WriteLine("Requesting open position list...");
            lock (_locker)
            {
                _currentRequest = _gateway.requestOpenPositions();
                Console.WriteLine("\tRequestId = {0}\n", _currentRequest);
            }
            _requestPositionListEvent.WaitOne();
            Console.WriteLine("Open position list complete.\n");

            // get closed position list
            Console.WriteLine("Requesting closed position list...");
            lock (_currentRequest)
            {
                _currentRequest = _gateway.requestClosedPositions();
                Console.WriteLine("\tRequestId = {0}\n", _currentRequest);
            }
            _requestPositionListEvent.WaitOne();
            Console.WriteLine("Closed position list complete.\n");

            // get current quotes for the instrument
            if (_securities.ContainsKey(Symbol))
            {
                Console.WriteLine("Requesting market data for " + Symbol + "...");
                var request = new MarketDataRequest();
                request.setMDEntryTypeSet(MarketDataRequest.MDENTRYTYPESET_ALL);
                request.setSubscriptionRequestType(SubscriptionRequestTypeFactory.SNAPSHOT);
                request.addRelatedSymbol(_securities[Symbol]);
                lock (_locker)
                {
                    _currentRequest = _gateway.sendMessage(request);
                    Console.WriteLine("\tRequestId = {0}\n", _currentRequest);
                }
                _requestMarketDataEvent.WaitOne();
                Console.WriteLine(Symbol + " - Bid: {0} Ask: {1}\n", _rates[Symbol].getBidClose(), _rates[Symbol].getAskClose());
            }

            // submit limit order
            Console.WriteLine("Submitting limit order...");
            var limitOrderRequest = MessageGenerator.generateOpenOrder(0.7, accountId, 10000, SideFactory.BUY, Symbol, "");

            limitOrderRequest.setOrdType(OrdTypeFactory.LIMIT);
            limitOrderRequest.setTimeInForce(TimeInForceFactory.GOOD_TILL_CANCEL);
            lock (_locker)
            {
                _currentRequest = _gateway.sendMessage(limitOrderRequest);
                Console.WriteLine("\tRequestId = {0}\n", _currentRequest);
            }
            _requestOrderEvent.WaitOne();
            Console.WriteLine("Limit order submitted.\n");

            var limitOrder = _orderRequests[_currentRequest];

            // update limit order
            Console.WriteLine("Updating limit order...");
            var orderReplaceRequest = MessageGenerator.generateOrderReplaceRequest("", limitOrder.getOrderID(), limitOrder.getSide(), limitOrder.getOrdType(), 0.8, limitOrder.getAccount());

            lock (_locker)
            {
                _currentRequest = _gateway.sendMessage(orderReplaceRequest);
                Console.WriteLine("\tRequestId = {0}\n", _currentRequest);
            }
            _requestOrderEvent.WaitOne();
            Console.WriteLine("Limit order updated.\n");

            // cancel limit order
            Console.WriteLine("Cancelling limit order...");
            var orderCancelRequest = MessageGenerator.generateOrderCancelRequest("", limitOrder.getOrderID(), limitOrder.getSide(), limitOrder.getAccount());

            lock (_locker)
            {
                _currentRequest = _gateway.sendMessage(orderCancelRequest);
                Console.WriteLine("\tRequestId = {0}\n", _currentRequest);
            }
            _requestOrderEvent.WaitOne();
            Console.WriteLine("Limit order cancelled.\n");

            // submit stop market order
            Console.WriteLine("Submitting stop market order...");
            var stopMarketOrderRequest = MessageGenerator.generateOpenOrder(0.7, accountId, 10000, SideFactory.SELL, Symbol, "");

            stopMarketOrderRequest.setOrdType(OrdTypeFactory.STOP);
            stopMarketOrderRequest.setTimeInForce(TimeInForceFactory.GOOD_TILL_CANCEL);
            lock (_locker)
            {
                _currentRequest = _gateway.sendMessage(stopMarketOrderRequest);
                Console.WriteLine("\tRequestId = {0}\n", _currentRequest);
            }
            _requestOrderEvent.WaitOne();
            Console.WriteLine("Stop market order submitted.\n");

            var stopMarketOrder = _orderRequests[_currentRequest];

            // cancel stop market order
            Console.WriteLine("Cancelling stop market order...");
            orderCancelRequest = MessageGenerator.generateOrderCancelRequest("", stopMarketOrder.getOrderID(), stopMarketOrder.getSide(), stopMarketOrder.getAccount());
            lock (_locker)
            {
                _currentRequest = _gateway.sendMessage(orderCancelRequest);
                Console.WriteLine("\tRequestId = {0}\n", _currentRequest);
            }
            _requestOrderEvent.WaitOne();
            Console.WriteLine("Stop market order cancelled.\n");

            // submit stop limit order
            Console.WriteLine("Submitting stop limit order...");
            var stopLimitOrderRequest = MessageGenerator.generateOpenOrder(0.7, accountId, 10000, SideFactory.SELL, Symbol, "");

            stopLimitOrderRequest.setOrdType(OrdTypeFactory.STOP_LIMIT);
            stopLimitOrderRequest.setStopPx(0.695);
            stopLimitOrderRequest.setTimeInForce(TimeInForceFactory.GOOD_TILL_CANCEL);
            lock (_locker)
            {
                _currentRequest = _gateway.sendMessage(stopLimitOrderRequest);
                Console.WriteLine("\tRequestId = {0}\n", _currentRequest);
            }
            _requestOrderEvent.WaitOne();
            Console.WriteLine("Stop limit order submitted.\n");

            var stopLimitOrder = _orderRequests[_currentRequest];

            // cancel stop limit order
            Console.WriteLine("Cancelling stop limit order...");
            orderCancelRequest = MessageGenerator.generateOrderCancelRequest("", stopLimitOrder.getOrderID(), stopLimitOrder.getSide(), stopLimitOrder.getAccount());
            lock (_locker)
            {
                _currentRequest = _gateway.sendMessage(orderCancelRequest);
                Console.WriteLine("\tRequestId = {0}\n", _currentRequest);
            }
            _requestOrderEvent.WaitOne();
            Console.WriteLine("Stop limit order cancelled.\n");

            // submit market order (buy)
            Console.WriteLine("Submitting buy market order...");
            var buyOrder = MessageGenerator.generateMarketOrder(accountId, 10000, SideFactory.BUY, Symbol, "");

            lock (_locker)
            {
                _currentRequest = _gateway.sendMessage(buyOrder);
                Console.WriteLine("\tRequestId = {0}\n", _currentRequest);
            }
            _requestOrderEvent.WaitOne();
            Console.WriteLine("Buy market order submitted.\n");

            // submit market order (sell)
            Console.WriteLine("Submitting sell market order...");
            var sellOrder = MessageGenerator.generateMarketOrder(accountId, 10000, SideFactory.SELL, Symbol, "");

            lock (_locker)
            {
                _currentRequest = _gateway.sendMessage(sellOrder);
                Console.WriteLine("\tRequestId = {0}\n", _currentRequest);
            }
            _requestOrderEvent.WaitOne();
            Console.WriteLine("Sell market order submitted.\n");

            Console.WriteLine();
            Console.WriteLine("Press Return to Logout and exit.\n");
            Console.ReadKey();

            // log out
            Console.WriteLine("Logging out...");
            _gateway.logout();
            Console.WriteLine("Logged out.");

            // remove the generic message listener, stop listening to updates
            _gateway.removeGenericMessageListener(this);

            // remove the status message listener, stop listening to status changes
            _gateway.removeStatusMessageListener(this);
        }
        /// <summary>
        /// Get historical data enumerable for a single symbol, type and resolution given this start and end time (in UTC).
        /// </summary>
        /// <param name="symbol">Symbol for the data we're looking for.</param>
        /// <param name="resolution">Resolution of the data request</param>
        /// <param name="startUtc">Start time of the data in UTC</param>
        /// <param name="endUtc">End time of the data in UTC</param>
        /// <returns>Enumerable of base data for this symbol</returns>
        public IEnumerable <BaseData> Get(Symbol symbol, Resolution resolution, DateTime startUtc, DateTime endUtc)
        {
            if (!_symbolMapper.IsKnownLeanSymbol(symbol))
            {
                throw new ArgumentException("Invalid symbol requested: " + symbol.Value);
            }

            if (symbol.ID.SecurityType != SecurityType.Forex && symbol.ID.SecurityType != SecurityType.Cfd)
            {
                throw new NotSupportedException("SecurityType not available: " + symbol.ID.SecurityType);
            }

            if (endUtc <= startUtc)
            {
                throw new ArgumentException("The end date must be greater than the start date.");
            }

            Console.WriteLine("Logging in...");

            // create the gateway
            _gateway = GatewayFactory.createGateway();

            // register the message listeners with the gateway
            _gateway.registerGenericMessageListener(this);
            _gateway.registerStatusMessageListener(this);

            // create local login properties
            var loginProperties = new FXCMLoginProperties(_userName, _password, _terminal, _server);

            // log in
            _gateway.login(loginProperties);

            // initialize session
            RequestTradingSessionStatus();

            Console.WriteLine("Downloading {0} data from {1} to {2}...", resolution, startUtc.ToString("yyyyMMdd HH:mm:ss"), endUtc.ToString("yyyyMMdd HH:mm:ss"));

            // Find best FXCM parameters
            var interval = FxcmBrokerage.ToFxcmInterval(resolution);

            var totalTicks = (endUtc - startUtc).Ticks;

            // download data
            var totalBaseData = new List <BaseData>();

            var end = endUtc;

            do //
            {
                //show progress
                progressBar(Math.Abs((end - endUtc).Ticks), totalTicks, Console.WindowWidth / 2, '█');
                _currentBaseData.Clear();

                var mdr = new MarketDataRequest();
                mdr.setSubscriptionRequestType(SubscriptionRequestTypeFactory.SNAPSHOT);
                mdr.setResponseFormat(IFixMsgTypeDefs.__Fields.MSGTYPE_FXCMRESPONSE);
                mdr.setFXCMTimingInterval(interval);
                mdr.setMDEntryTypeSet(MarketDataRequest.MDENTRYTYPESET_ALL);

                mdr.setFXCMStartDate(new UTCDate(FxcmBrokerage.ToJavaDateUtc(startUtc)));
                mdr.setFXCMStartTime(new UTCTimeOnly(FxcmBrokerage.ToJavaDateUtc(startUtc)));
                mdr.setFXCMEndDate(new UTCDate(FxcmBrokerage.ToJavaDateUtc(end)));
                mdr.setFXCMEndTime(new UTCTimeOnly(FxcmBrokerage.ToJavaDateUtc(end)));
                mdr.addRelatedSymbol(_fxcmInstruments[_symbolMapper.GetBrokerageSymbol(symbol)]);


                AutoResetEvent autoResetEvent;
                lock (_locker)
                {
                    _currentRequest = _gateway.sendMessage(mdr);
                    autoResetEvent  = new AutoResetEvent(false);
                    _mapRequestsToAutoResetEvents[_currentRequest] = autoResetEvent;
                }
                if (!autoResetEvent.WaitOne(1000 * 5))
                {
                    // no response, exit
                    break;
                }

                // Add data
                totalBaseData.InsertRange(0, _currentBaseData.Where(x => x.Time.Date >= startUtc.Date));

                if (end != _currentBaseData[0].Time)
                {
                    // new end date = first datapoint date.
                    end = _currentBaseData[0].Time;
                }
                else
                {
                    break;
                }
            } while (end > startUtc);


            Console.WriteLine("\nLogging out...");

            // log out
            _gateway.logout();

            // remove the message listeners
            _gateway.removeGenericMessageListener(this);
            _gateway.removeStatusMessageListener(this);

            return(totalBaseData.ToList());
        }
示例#22
0
        /// <summary>
        /// Connects the client to the broker's remote servers
        /// </summary>
        public override void Connect()
        {
            if (IsConnected)
            {
                return;
            }

            Log.Trace("FxcmBrokerage.Connect()");

            _cancellationTokenSource = new CancellationTokenSource();

            // create new thread to fire order events in queue
            _orderEventThread = new Thread(() =>
            {
                while (!_cancellationTokenSource.IsCancellationRequested)
                {
                    OrderEvent orderEvent;
                    if (!_orderEventQueue.TryDequeue(out orderEvent))
                    {
                        Thread.Sleep(1);
                        continue;
                    }

                    OnOrderEvent(orderEvent);
                }
            });
            _orderEventThread.Start();
            while (!_orderEventThread.IsAlive)
            {
                Thread.Sleep(1);
            }

            // create the gateway
            _gateway = GatewayFactory.createGateway();

            // register the message listeners with the gateway
            _gateway.registerGenericMessageListener(this);
            _gateway.registerStatusMessageListener(this);

            // create local login properties
            var loginProperties = new FXCMLoginProperties(_userName, _password, _terminal, _server);

            // log in
            _gateway.login(loginProperties);

            // create new thread to manage disconnections and reconnections
            _connectionMonitorThread = new Thread(() =>
            {
                _lastReadyMessageTime = DateTime.UtcNow;

                try
                {
                    while (!_cancellationTokenSource.IsCancellationRequested)
                    {
                        TimeSpan elapsed;
                        lock (_lockerConnectionMonitor)
                        {
                            elapsed = DateTime.UtcNow - _lastReadyMessageTime;
                        }

                        if (!_connectionLost && elapsed > TimeSpan.FromSeconds(5))
                        {
                            _connectionLost = true;

                            OnMessage(BrokerageMessageEvent.Disconnected("Connection with FXCM server lost. " +
                                                                         "This could be because of internet connectivity issues. "));
                        }
                        else if (_connectionLost && elapsed <= TimeSpan.FromSeconds(5))
                        {
                            try
                            {
                                _gateway.relogin();

                                _connectionLost = false;

                                OnMessage(BrokerageMessageEvent.Reconnected("Connection with FXCM server restored."));
                            }
                            catch (Exception exception)
                            {
                                Log.Error(exception);
                            }
                        }
                        else if (_connectionError)
                        {
                            try
                            {
                                // log out
                                _gateway.logout();

                                // remove the message listeners
                                _gateway.removeGenericMessageListener(this);
                                _gateway.removeStatusMessageListener(this);

                                // register the message listeners with the gateway
                                _gateway.registerGenericMessageListener(this);
                                _gateway.registerStatusMessageListener(this);

                                // log in
                                _gateway.login(loginProperties);

                                // load instruments, accounts, orders, positions
                                LoadInstruments();
                                LoadAccounts();
                                LoadOpenOrders();
                                LoadOpenPositions();

                                _connectionError = false;
                                _connectionLost  = false;

                                OnMessage(BrokerageMessageEvent.Reconnected("Connection with FXCM server restored."));
                            }
                            catch (Exception exception)
                            {
                                Log.Error(exception);
                            }
                        }

                        Thread.Sleep(5000);
                    }
                }
                catch (Exception exception)
                {
                    Log.Error(exception);
                }
            });
            _connectionMonitorThread.Start();
            while (!_connectionMonitorThread.IsAlive)
            {
                Thread.Sleep(1);
            }

            // load instruments, accounts, orders, positions
            LoadInstruments();
            LoadAccounts();
            LoadOpenOrders();
            LoadOpenPositions();
        }
示例#23
0
        /// <summary>
        /// 基本执行调用方法(异步)
        /// </summary>
        /// <param name="sessionId">sessionId</param>
        /// <param name="jsonRpc">请求内容</param>
        /// <param name="context">请求上下文</param>
        /// <param name="callback">回调,包含执行结果(空则无错误信息)</param>
        private static void ExecuteAsync(string sessionId, string jsonRpc, object context, Action <string> callback)
        {
            var handler = Handler.GetSessionHandler(sessionId);

            try
            {
                //从请求内容中构建请求上下文
                Tuple <JsonRpcRequestContext>[] batch = null;
                if (IsSingle(jsonRpc))
                {
                    batch = new[] { Tuple.Create(JsonConvert.DeserializeObject <JsonRpcRequestContext>(jsonRpc)) };
                }
                else
                {
                    batch = JsonConvert.DeserializeObject <JsonRpcRequestContext[]>(jsonRpc)
                            .Select(request => new Tuple <JsonRpcRequestContext>(request))
                            .ToArray();

                    if (batch.Length > 1)
                    {
                        //将所有请求上下文Tags都赋值为第一个请求上下文的Tags
                        Dictionary <string, object> firstTags = batch[0].Item1.Tags;
                        for (int i = 1; i < batch.Length; i++)
                        {
                            batch[i].Item1.Tags = firstTags;
                        }
                    }
                }

                //基本验证
                if (batch.Length == 0)
                {
                    callback.Invoke(JsonConvert.SerializeObject(new JsonRpcResponseContext
                    {
                        Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32600, "无效请求", "请求调用为空", jsonRpc))
                    }));
                }

                //网关预处理
                try
                {
                    var gateways = GatewayFactory.GetGateways();
                    foreach (var gateway in gateways)
                    {
                        gateway.PreProcess(jsonRpc);
                    }
                }
                catch (AuthenticationException ex)
                {
                    callback.Invoke(JsonConvert.SerializeObject(new JsonRpcResponseContext
                    {
                        Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32600, ex.Message, ex.ToString(), jsonRpc))
                    }));
                }
                catch (JsonRpcException ex)
                {
                    ex.rpcRequestRaw = jsonRpc;
                    callback.Invoke(JsonConvert.SerializeObject(new JsonRpcResponseContext
                    {
                        Error = handler.ProcessParseException(jsonRpc, ex)
                    }));
                }
                catch (Exception ex)
                {
                    callback.Invoke(JsonConvert.SerializeObject(new JsonRpcResponseContext
                    {
                        Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32603, "内部错误", ex.Message, jsonRpc))
                    }));
                }

                //循环请求上下文,并调用Handler处理请求
                foreach (var tuple in batch)
                {
                    var requestContext  = tuple.Item1;
                    var responseContext = new JsonRpcResponseContext();
                    if (requestContext == null)
                    {
                        responseContext.Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32700, "转换错误", "服务器接收到无效的json文本,解析json文本时服务器出现错误", jsonRpc));
                    }
                    else
                    {
                        responseContext.Id = requestContext.Id;
                        if (string.IsNullOrWhiteSpace(requestContext.Method))
                        {
                            responseContext.Error = handler.ProcessParseException(jsonRpc,
                                                                                  new JsonRpcException(-32600, "无效请求", "未检测到'Method'", jsonRpc));
                        }
                        else
                        {
                            handler.Handle(requestContext, context, (resContext) =>
                            {
                                resContext.Id = requestContext.Id;
                                if (resContext.Id != null || resContext.Error != null)
                                {
                                    callback.Invoke(JsonConvert.SerializeObject(resContext));
                                }
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                callback.Invoke(JsonConvert.SerializeObject(new JsonRpcResponseContext
                {
                    Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32700, "转换错误", ex, jsonRpc))
                }));
            }
        }
示例#24
0
        /// <summary>
        /// Connects the client to the broker's remote servers
        /// </summary>
        public override void Connect()
        {
            if (IsConnected)
            {
                return;
            }

            Log.Trace("FxcmBrokerage.Connect()");

            _cancellationTokenSource = new CancellationTokenSource();

            // create new thread to fire order events in queue
            if (!EnableOnlyHistoryRequests)
            {
                _orderEventThread = new Thread(() =>
                {
                    while (!_cancellationTokenSource.IsCancellationRequested)
                    {
                        try
                        {
                            OrderEvent orderEvent;
                            if (!_orderEventQueue.TryDequeue(out orderEvent))
                            {
                                Thread.Sleep(1);
                                continue;
                            }

                            OnOrderEvent(orderEvent);
                        }
                        catch (Exception exception)
                        {
                            Log.Error(exception);
                        }
                    }
                })
                {
                    IsBackground = true
                };
                _orderEventThread.Start();
                while (!_orderEventThread.IsAlive)
                {
                    Thread.Sleep(1);
                }
            }

            // create the gateway
            _gateway = GatewayFactory.createGateway();

            // register the message listeners with the gateway
            _gateway.registerGenericMessageListener(this);
            _gateway.registerStatusMessageListener(this);

            // create local login properties
            var loginProperties = new FXCMLoginProperties(_userName, _password, _terminal, _server);

            loginProperties.addProperty(IConnectionManager.APP_INFO, "QuantConnect");

            // log in
            try
            {
                _gateway.login(loginProperties);
            }
            catch (Exception err)
            {
                var message =
                    err.Message.Contains("ORA-20101") ? "Incorrect login credentials" :
                    err.Message.Contains("ORA-20003") ? "API connections are not available on Mini accounts. If you have a standard account contact [email protected] to enable API access" :
                    err.Message;

                _cancellationTokenSource.Cancel();

                throw new BrokerageException(message, err.InnerException);
            }

            // create new thread to manage disconnections and reconnections
            if (!EnableOnlyHistoryRequests)
            {
                _connectionMonitorThread = new Thread(() =>
                {
                    _lastReadyMessageTime = DateTime.UtcNow;

                    try
                    {
                        while (!_cancellationTokenSource.IsCancellationRequested)
                        {
                            TimeSpan elapsed;
                            lock (_lockerConnectionMonitor)
                            {
                                elapsed = DateTime.UtcNow - _lastReadyMessageTime;
                            }

                            if (!_connectionLost && elapsed > TimeSpan.FromSeconds(10))
                            {
                                _connectionLost = true;

                                OnMessage(BrokerageMessageEvent.Disconnected("Connection with FXCM server lost. " +
                                                                             "This could be because of internet connectivity issues. "));
                            }
                            else if (_connectionLost && IsWithinTradingHours())
                            {
                                Log.Trace("FxcmBrokerage.ConnectionMonitorThread(): Attempting reconnection...");

                                try
                                {
                                    // log out
                                    try
                                    {
                                        _gateway.logout();
                                    }
                                    catch (Exception)
                                    {
                                        // ignored
                                    }

                                    // remove the message listeners
                                    _gateway.removeGenericMessageListener(this);
                                    _gateway.removeStatusMessageListener(this);

                                    // register the message listeners with the gateway
                                    _gateway.registerGenericMessageListener(this);
                                    _gateway.registerStatusMessageListener(this);

                                    // log in
                                    _gateway.login(loginProperties);

                                    // load instruments, accounts, orders, positions
                                    LoadInstruments();
                                    if (!EnableOnlyHistoryRequests)
                                    {
                                        LoadAccounts();
                                        LoadOpenOrders();
                                        LoadOpenPositions();
                                    }

                                    _connectionLost = false;

                                    OnMessage(BrokerageMessageEvent.Reconnected("Connection with FXCM server restored."));
                                }
                                catch (Exception exception)
                                {
                                    Log.Trace("FxcmBrokerage.ConnectionMonitorThread(): reconnect failed.");
                                    Log.Error(exception);
                                }
                            }

                            Thread.Sleep(5000);
                        }
                    }
                    catch (Exception exception)
                    {
                        Log.Error(exception);
                    }
                })
                {
                    IsBackground = true
                };
                _connectionMonitorThread.Start();
                while (!_connectionMonitorThread.IsAlive)
                {
                    Thread.Sleep(1);
                }
            }

            // load instruments, accounts, orders, positions
            LoadInstruments();
            if (!EnableOnlyHistoryRequests)
            {
                LoadAccounts();
                LoadOpenOrders();
                LoadOpenPositions();
            }
        }
示例#25
0
        /// <summary>
        /// Sends pay request to selected gateway.
        /// </summary>
        /// <param name="gateway">Gateway to pay</param>
        /// <param name="invoice">Invoice object</param>
        public static RequestResult Request(Gateway gateway, Invoice invoice)
        {
            if (invoice == null)
            {
                throw new ArgumentNullException(nameof(invoice));
            }

            ThrowExceptionIfGatewayIsNotConfigured(gateway);

            var paymentData = SelectPaymentDataByOrderNumber(invoice.OrderNumber);

            if (paymentData != null)
            {
                //  Log
                TryLog(() => new Log
                {
                    Type          = LogType.Request,
                    Gateway       = gateway,
                    OrderNumber   = invoice.OrderNumber,
                    Amount        = invoice.Amount,
                    Message       = $"Order Number ({invoice.OrderNumber}) is used before and you cannot use it again. It must be unique for each requests.",
                    CreatedOn     = DateTime.Now,
                    ReferenceId   = string.Empty,
                    TransactionId = string.Empty,
                    Status        = RequestResultStatus.DuplicateOrderNumber.ToString()
                });

                return(new RequestResult(RequestResultStatus.DuplicateOrderNumber, $"The order number ({invoice.OrderNumber}) is already exists and you cannot use it again. It must be unique for each requests."));
            }

            var gatewayBase = GatewayFactory.CreateGateway(gateway);

            paymentData = invoice.CreatePaymentData(gateway);

            invoice.CallbackUrl = CreateCallbackUrl(invoice.CallbackUrl, paymentData.Id);

            try
            {
                var result = gatewayBase.Request(invoice);

                //  Set ReferenceId
                paymentData.ReferenceId    = result.ReferenceId;
                paymentData.AdditionalData = result.AdditionalData;

                if (!result.IsSuccess())
                {
                    paymentData.Status = PaymentDataStatus.Failed;
                }

                //  Log
                TryLog(() => new Log
                {
                    Type          = LogType.Request,
                    Gateway       = gateway,
                    OrderNumber   = invoice.OrderNumber,
                    Amount        = invoice.Amount,
                    Message       = result.Message,
                    CreatedOn     = DateTime.Now,
                    ReferenceId   = result.ReferenceId,
                    TransactionId = string.Empty,
                    Status        = result.Status.ToString()
                });

                return(result);
            }
            catch (Exception exception)
            {
                //  Log
                TryLog(() => new Log
                {
                    Type        = LogType.Error,
                    Gateway     = gateway,
                    OrderNumber = invoice.OrderNumber,
                    Amount      = invoice.Amount,
                    Message     = exception.Message,
                    CreatedOn   = DateTime.Now
                });

                paymentData.Status = PaymentDataStatus.Failed;

                return(new RequestResult(RequestResultStatus.Failed, "An error occurred."));
            }
            finally
            {
                InsertPaymentData(paymentData);
            }
        }