Example #1
0
        /********************************************************
        * CLASS CONSTRUCTOR
        *********************************************************/
        /// <summary>
        /// Initialise the Algorithm
        /// </summary>
        public QCAlgorithm()
        {
            //Initialise the Algorithm Helper Classes:
            //- Note - ideally these wouldn't be here, but because of the DLL we need to make the classes shared across
            //  the Worker & Algorithm, limiting ability to do anything else.
            Securities = new SecurityManager();
            Transacions = new SecurityTransactionManager(Securities);
            Portfolio = new SecurityPortfolioManager(Securities, Transacions);

            //Initialise Data Manager
            DataManager = new DataManager();

            //Initialise Error and Order Holders:
            Errors = new List<string>();

            //Initialise Algorithm RunMode to Automatic:
            _runMode = RunMode.Automatic;

            //Initialise to unlocked:
            _locked = false;

            //Initialise Start and End Dates:
            _startDate = new DateTime();
            _endDate = new DateTime();
        }
        public void FundsAreSettledImmediately()
        {
            var securities = new SecurityManager(TimeKeeper);
            var transactions = new SecurityTransactionManager(securities);
            var portfolio = new SecurityPortfolioManager(securities, transactions);
            var model = new ImmediateSettlementModel();
            var config = CreateTradeBarConfig();
            var security = new Security(SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config);

            portfolio.SetCash(1000);
            Assert.AreEqual(1000, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);

            var timeUtc = Noon.ConvertToUtc(TimeZones.NewYork);
            model.ApplyFunds(portfolio, security, timeUtc, "USD", 1000);

            Assert.AreEqual(2000, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);

            model.ApplyFunds(portfolio, security, timeUtc, "USD", -500);

            Assert.AreEqual(1500, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);

            model.ApplyFunds(portfolio, security, timeUtc, "USD", 1000);

            Assert.AreEqual(2500, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);
        }
        /// <summary>
        /// Initialise the transaction manager for holding and processing orders.
        /// </summary>
        public SecurityTransactionManager(SecurityManager security)
        {
            //Private reference for processing transactions
            _securities = security;

            //Internal storage for transaction records:
            _transactionRecord = new Dictionary<DateTime, decimal>();
        }
        public void SecurityManager_CreateMockX509Certificate_Will_Create_Mock_Certificate_Test()
        {
            SecurityManager manager = new SecurityManager();
            MockX509Certificate cert = manager.CreateMockX509Certificate();

            Confirm.Different(null, cert.PrivateKey);
            Confirm.Different(null, cert.PublicKey);
        }
Example #5
0
 /// <summary>
 /// Define an enumerable Date Range:
 /// </summary>
 /// <param name="securities">Securities we have in portfolio</param>
 /// <param name="from">start date</param>
 /// <param name="thru">end date</param>
 /// <returns>Enumerable Date Range:</returns>
 public static IEnumerable<DateTime> EachTradeableDay(SecurityManager securities, DateTime from, DateTime thru)
 {
     for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1)) {
         if (Time.TradableDate(securities, day)) {
             yield return day;
         }
     }
 }
Example #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ScheduleManager"/> class
        /// </summary>
        /// <param name="securities">Securities manager containing the algorithm's securities</param>
        /// <param name="timeZone">The algorithm's time zone</param>
        public ScheduleManager(SecurityManager securities, DateTimeZone timeZone)
        {
            _securities = securities;
            DateRules = new DateRules(securities);
            TimeRules = new TimeRules(securities, timeZone);

            // used for storing any events before the event schedule is set
            _preInitializedEvents = new List<ScheduledEvent>();
        }
        public void SellOnThursdaySettleOnTuesday()
        {
            var securities = new SecurityManager(TimeKeeper);
            var transactions = new SecurityTransactionManager(securities);
            var portfolio = new SecurityPortfolioManager(securities, transactions);
            // settlement at T+3, 8:00 AM
            var model = new DelayedSettlementModel(3, TimeSpan.FromHours(8));
            var config = CreateTradeBarConfig(Symbols.SPY);
            var security = new Security(SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency));

            portfolio.SetCash(3000);
            Assert.AreEqual(3000, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);

            // Sell on Thursday
            var timeUtc = Noon.AddDays(3).ConvertToUtc(TimeZones.NewYork);
            model.ApplyFunds(portfolio, security, timeUtc, "USD", 1000);
            portfolio.ScanForCashSettlement(timeUtc);
            Assert.AreEqual(3000, portfolio.Cash);
            Assert.AreEqual(1000, portfolio.UnsettledCash);

            // Friday, still unsettled
            timeUtc = timeUtc.AddDays(1);
            portfolio.ScanForCashSettlement(timeUtc);
            Assert.AreEqual(3000, portfolio.Cash);
            Assert.AreEqual(1000, portfolio.UnsettledCash);

            // Saturday, still unsettled
            timeUtc = timeUtc.AddDays(1);
            portfolio.ScanForCashSettlement(timeUtc);
            Assert.AreEqual(3000, portfolio.Cash);
            Assert.AreEqual(1000, portfolio.UnsettledCash);

            // Sunday, still unsettled
            timeUtc = timeUtc.AddDays(1);
            portfolio.ScanForCashSettlement(timeUtc);
            Assert.AreEqual(3000, portfolio.Cash);
            Assert.AreEqual(1000, portfolio.UnsettledCash);

            // Monday, still unsettled
            timeUtc = timeUtc.AddDays(1);
            portfolio.ScanForCashSettlement(timeUtc);
            Assert.AreEqual(3000, portfolio.Cash);
            Assert.AreEqual(1000, portfolio.UnsettledCash);

            // Tuesday at 7:55 AM, still unsettled
            timeUtc = timeUtc.AddDays(1).AddHours(-4).AddMinutes(-5);
            portfolio.ScanForCashSettlement(timeUtc);
            Assert.AreEqual(3000, portfolio.Cash);
            Assert.AreEqual(1000, portfolio.UnsettledCash);

            // Tuesday at 8 AM, now settled
            timeUtc = timeUtc.AddMinutes(5);
            portfolio.ScanForCashSettlement(timeUtc);
            Assert.AreEqual(4000, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);
        }
        /********************************************************
        * CLASS CONSTRUCTOR
        *********************************************************/
        /// <summary>
        /// Initialise the Algorithm Transaction Class
        /// </summary>
        public SecurityTransactionManager(SecurityManager security)
        {
            //Private reference for processing transactions
            this.Securities = security;

            //Initialise the Order Caches:
            this.ProcessedOrders = new Dictionary<int, Order>();
            this.OutstandingOrders = new Dictionary<int, Order>();
        }
        /********************************************************
        * CLASS CONSTRUCTOR
        *********************************************************/
        /// <summary>
        /// Initialise the Algorithm Transaction Class
        /// </summary>
        public SecurityTransactionManager(SecurityManager security)
        {
            //Private reference for processing transactions
            this.Securities = security;

            //Initialise the Order Cache -- Its a mirror of the TransactionHandler.
            this._orders = new ConcurrentDictionary<int, Order>();

            //Temporary Holding Queue of Orders to be Processed.
            this.OrderQueue = new ConcurrentQueue<Order>();
        }
        public void TestCashFills()
        {
            // this test asserts the portfolio behaves according to the Test_Cash algo, see TestData\CashTestingStrategy.csv
            // also "https://www.dropbox.com/s/oiliumoyqqj1ovl/2013-cash.csv?dl=1"

            const string fillsFile = "TestData\\test_cash_fills.xml";
            const string equityFile = "TestData\\test_cash_equity.xml";

            var fills = XDocument.Load(fillsFile).Descendants("OrderEvent").Select(x => new OrderEvent(
                x.Get<int>("OrderId"),
                SymbolMap[x.Get<string>("Symbol")],
                DateTime.MinValue, 
                x.Get<OrderStatus>("Status"),
                x.Get<int>("FillQuantity") < 0 ? OrderDirection.Sell 
              : x.Get<int>("FillQuantity") > 0 ? OrderDirection.Buy 
                                               : OrderDirection.Hold,
                x.Get<decimal>("FillPrice"),
                x.Get<int>("FillQuantity"),
                0m)
                ).ToList();

            var equity = XDocument.Load(equityFile).Descendants("decimal")
                .Select(x => decimal.Parse(x.Value, CultureInfo.InvariantCulture))
                .ToList();

            Assert.AreEqual(fills.Count + 1, equity.Count);

            // we're going to process fills and very our equity after each fill
            var subscriptions = new SubscriptionManager(TimeKeeper);
            var securities = new SecurityManager(TimeKeeper);
            var security = new Security(SecurityExchangeHours, subscriptions.Add(CASH, Resolution.Daily, TimeZones.NewYork, TimeZones.NewYork), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency));
            security.SetLeverage(10m);
            securities.Add(CASH, security);
            var transactions = new SecurityTransactionManager(securities);
            var portfolio = new SecurityPortfolioManager(securities, transactions);
            portfolio.SetCash(equity[0]);

            for (int i = 0; i < fills.Count; i++)
            {
                // before processing the fill we must deduct the cost
                var fill = fills[i];
                var time = DateTime.Today.AddDays(i);
                TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork));
                // the value of 'CASH' increments for each fill, the original test algo did this monthly
                // the time doesn't really matter though
                security.SetMarketPrice(new IndicatorDataPoint(CASH, time, i + 1));

                portfolio.ProcessFill(fill);
                Assert.AreEqual(equity[i + 1], portfolio.TotalPortfolioValue, "Failed on " + i);
            }
        }
Example #11
0
        public void EnsureCurrencyDataFeedAddsSubscription()
        {
            const int quantity = 100;
            const decimal conversionRate = 1 / 100m;
            var cash = new Cash("JPY", quantity, conversionRate);

            var subscriptions = new SubscriptionManager(TimeKeeper);
            var abcConfig = subscriptions.Add(Symbols.SPY, Resolution.Minute, TimeZone, TimeZone);
            var securities = new SecurityManager(TimeKeeper);
            securities.Add(Symbols.SPY, new Security(SecurityExchangeHours, abcConfig, 1m));
            cash.EnsureCurrencyDataFeed(securities, subscriptions, MarketHoursDatabase.AlwaysOpen);
            Assert.AreEqual(1, subscriptions.Subscriptions.Count(x => x.Symbol == Symbols.USDJPY));
            Assert.AreEqual(1, securities.Values.Count(x => x.Symbol == Symbols.USDJPY));
        }
        /// <summary>
        /// Initialise the transaction manager for holding and processing orders.
        /// </summary>
        public SecurityTransactionManager(SecurityManager security)
        {
            //Private reference for processing transactions
            _securities = security;

            //Initialise the Order Cache -- Its a mirror of the TransactionHandler.
            _orders = new ConcurrentDictionary<int, Order>();

            //Temporary Holding Queue of Orders to be Processed.
            _orderQueue = new ConcurrentQueue<Order>();

            // Internal order events storage.
            _orderEvents = new ConcurrentDictionary<int, List<OrderEvent>>();

            //Interal storage for transaction records:
            _transactionRecord = new Dictionary<DateTime, decimal>();
        }
Example #13
0
		private AdminServer()
		{
			_disposed = false;
			_isRunning = false;
			_securityManager = new SecurityManager();
			_gameServerManager = new GameServerManager();
			_connectionManager = new ConnectionManager();
			_messageEngine = new MessageEngine();
			_gameServerMonitor = new GameServerMonitor();			
			_automationManager = new AutomationManager();
			_strategyManager = new StrategyManager();
			_scheduledTaskManager = new ScheduledTaskManager();
            _FTPClient = new FTPClient();
			_batchTaskManager = new BatchTaskManager();
            _paysysManager = new PaysysManager();
            _ibShopManager = new IBShopManager();
		}
Example #14
0
        public void NotifiesWhenSecurityAddedViaIndexer()
        {
            var timeKeeper = new TimeKeeper(new DateTime(2015, 12, 07));
            var manager = new SecurityManager(timeKeeper);

            var security = new Security(SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), CreateTradeBarConfig(), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency));
            manager.CollectionChanged += (sender, args) =>
            {
                if (args.NewItems.OfType<object>().Single() != security)
                {
                    Assert.Fail("Expected args.NewItems to have exactly one element equal to security");
                }
                else
                {
                    Assert.IsTrue(args.Action == NotifyCollectionChangedAction.Add);
                    Assert.Pass();
                }
            };

            manager[security.Symbol] = security;
        }
Example #15
0
        public void NotifiesWhenSecurityRemoved()
        {
            var timeKeeper = new TimeKeeper(new DateTime(2015, 12, 07));
            var manager = new SecurityManager(timeKeeper);

            var security = new Security(SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), CreateTradeBarConfig());
            manager.Add(security.Symbol, security);
            manager.CollectionChanged += (sender, args) =>
            {
                if (args.OldItems.OfType<object>().Single() != security)
                {
                    Assert.Fail("Expected args.NewItems to have exactly one element equal to security");
                }
                else
                {
                    Assert.IsTrue(args.Action == NotifyCollectionChangedAction.Remove);
                    Assert.Pass();
                }
            };

            manager.Remove(security.Symbol);
        }
Example #16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DateRules"/> helper class
 /// </summary>
 /// <param name="securities">The security manager</param>
 public DateRules(SecurityManager securities)
 {
     _securities = securities;
 }
        /// <summary>
        /// Get the benchmark for this model
        /// </summary>
        /// <param name="securities">SecurityService to create the security with if needed</param>
        /// <returns>The benchmark for this brokerage</returns>
        public override IBenchmark GetBenchmark(SecurityManager securities)
        {
            var symbol = Symbol.Create("BTCUSD", SecurityType.Crypto, Market.Binance);

            return(SecurityBenchmark.CreateInstance(securities, symbol));
        }
Example #18
0
 public ModuleController(SecurityManager securityManager, IFilterService filterService)
 {
     _securityManager = securityManager;
     _filterService   = filterService;
 }
Example #19
0
        private static async Task ExecuteInternalAsync(BrokeredMessage message, ICollector <BrokeredMessage> response)
        {
            // We'll always need a response message, so create it now and populate it below.
            var responseMessage = new BrokeredMessage();

            // We'll create the app domain in the outer scope so we can unload it when we are finished (if it was created).
            AppDomain sandboxDomain = null;

            try
            {
                var requestId = (int)message.Properties["RequestId"];

                // Set correlation id of response message using the correlation ID of the request message.
                responseMessage.CorrelationId           = message.CorrelationId;
                responseMessage.Properties["RequestId"] = requestId;

                // The request will also load the associated route, so we'll use that feature
                // to reduce the number of SQL calls we make.
                var request = await Program.RequestRepository.GetRequestByIdAsync(requestId).TraceTimeAsync("Load Request");

                var route         = request.Route;
                var routeSettings = route.RouteSettings.ToArray();
                var routePackages = route.RoutePackages.ToArray();

                // Trace the incoming request URI.
                Trace.TraceInformation("Trace 'Request Uri' - {0}", request.Uri);

                try
                {
                    var ev = new Evidence();
                    ev.AddHostEvidence(new Zone(SecurityZone.Internet));

                    var assemblyType         = typeof(ExecutionSandbox);
                    var assemblyPath         = Path.GetDirectoryName(assemblyType.Assembly.Location);
                    var sandboxPermissionSet = TraceUtility.TraceTime("Create Sandbox Permission Set",
                                                                      () => SecurityManager.GetStandardSandbox(ev));

                    // Exit with an error code if for some reason we can't get the sandbox permission set.
                    if (sandboxPermissionSet == null)
                    {
                        throw new EntryPointException("Unable to load the sandbox environment, please contact Subroute.io for help with this error.");
                    }

                    // We'll create a new folder to hold an empty config file we create, and by
                    // doing this, it prevents the user from gaining access to our configuration
                    // file and the settings within, such as connection strings, infrastructure
                    // and other sensitive information we don't want them to have. Plus it will
                    // allow us to change any configuration settings that are specific to their
                    // application domain, such as default settings and other infrastructure.
                    // We must ensure that we have at least the root configuration XML tag in
                    // the configuration file we create or various dependencies will fail
                    // such as XmlSerializer and DataContractSerializer.
                    var directories = TraceUtility.TraceTime("Setup Filesystem",
                                                             () => SetupFilesystem(route, routeSettings));

                    TraceUtility.TraceTime("Reconfigure Appropriate Permission Sets", () =>
                    {
                        // Remove access to UI components since we are in a headless environment.
                        sandboxPermissionSet.RemovePermission(typeof(UIPermission));

                        // Remove access to the File System Dialog since we are headless.
                        sandboxPermissionSet.RemovePermission(typeof(FileDialogPermission));

                        // Add the ability to use reflection for invocation and serialization.
                        sandboxPermissionSet.AddPermission(new ReflectionPermission(PermissionState.Unrestricted));

                        // Add the ability to make web requests.
                        sandboxPermissionSet.AddPermission(new WebPermission(PermissionState.Unrestricted));

                        // Add the ability to use the XmlSerializer and the DataContractSerializer.
                        sandboxPermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter));

                        // Add permission to access the nuget package directory so that assemblies can be loaded.
                        sandboxPermissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read, Settings.NugetPackageDirectory));

                        // Add permission to read execution temp directory.
                        sandboxPermissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, new[] { directories.RootDirectory }));
                    });

                    TraceUtility.TraceTime("Create AppDomain", () =>
                    {
                        var appDomainSetup = new AppDomainSetup {
                            ApplicationBase = assemblyPath, ConfigurationFile = directories.ConfigFile
                        };
                        sandboxDomain = AppDomain.CreateDomain("Sandboxed", ev, appDomainSetup, sandboxPermissionSet);
                    });

                    // The ExecutionSandbox is a MarshalByRef type that allows us to dynamically
                    // load their assemblies via a byte array and execute methods inside of
                    // their app domain from our full-trust app domain. It's the bridge that
                    // crosses the app domain boundary.
                    var executionSandbox = TraceUtility.TraceTime("Create ExecutionSandbox Instance",
                                                                  () => (ExecutionSandbox)sandboxDomain.CreateInstance(
                                                                      assemblyType.Assembly.FullName,
                                                                      assemblyType.FullName,
                                                                      false,
                                                                      BindingFlags.Public | BindingFlags.Instance,
                                                                      null, null, null, null)
                                                                  .Unwrap());

                    // Prepare packages by locating the proper assemblies for the current framework and ensure
                    // they have been downloaded to the packages folder and return their paths.
                    executionSandbox.SetReferences(await PreparePackagesAsync(routePackages).TraceTimeAsync("Prepare Packages"));

                    // To properly load assemblies into the dynamic partial trust assembly, we have to override
                    // the AssemblyResolve method which is only called when an assembly load attempt is made
                    // and fails. We can't use a closure here because to do that, the entire class ExecutionMethods
                    // would have to be serailized across the app domain boundry. So we'll add a string array property
                    // to the ExecutionSandbox class so we can access the references from in the app domain boundry.
                    // Just remember this event is executed inside the partial trust domain.
                    sandboxDomain.AssemblyResolve += (sender, args) =>
                    {
                        var name = new AssemblyName(args.Name);
                        var path = ExecutionSandbox.References.FirstOrDefault(r => Path.GetFileNameWithoutExtension(r) == name.Name);

                        return(path == null ? null : Assembly.LoadFrom(path));
                    };

                    // Build the ExecutionRequest object that represents the incoming request
                    // which holds the payload, headers, method, etc. The class is serialized
                    // so it can cross the app domain boundary. So it's serialized in our
                    // full-trust host app domain, and deserialized and reinstantiated in
                    // the sandbox app domain.
                    var uri = new Uri(request.Uri, UriKind.Absolute);
                    var executionRequest = TraceUtility.TraceTime("Create RouteRequest Instance",
                                                                  () => new RouteRequest(uri, request.Method)
                    {
                        IpAddress = request.IpAddress,
                        Headers   = HeaderHelpers.DeserializeHeaders(request.RequestHeaders),
                        Body      = request.RequestPayload
                    });

                    try
                    {
                        // The ExecutionSandbox we'll attempt to locate the best method to execute
                        // based on the incoming request method (GET, POST, DELETE, etc.) and
                        // will pass the ExecutionRequest we created above. In return, we receive
                        // an instance of ExecutionResponse that has been serialized like the request
                        // and deserialized in our full-trust host domain.
                        var executionResponse = TraceUtility.TraceTime("Load and Execute Request",
                                                                       () => executionSandbox.Execute(route.Assembly, executionRequest));

                        // We'll use the data that comes back from the response to fill out the
                        // remainder of the database request record which will return the status
                        // code, message, payload, and headers. Then we update the database.
                        request.CompletedOn     = DateTimeOffset.UtcNow;
                        request.StatusCode      = (int)executionResponse.StatusCode;
                        request.StatusMessage   = executionResponse.StatusMessage;
                        request.ResponsePayload = executionResponse.Body;
                        request.ResponseHeaders = RouteResponse.SerializeHeaders(executionResponse.Headers);

                        await Program.RequestRepository.UpdateRequestAsync(request).TraceTimeAsync("Update Request Record");

                        // We'll pass back a small bit of data indiciating to the subscribers of
                        // the response topic listening for our specific correlation ID that indicates
                        // the route code was executed successfully and to handle it as such.
                        responseMessage.Properties["Result"]  = (int)ExecutionResult.Success;
                        responseMessage.Properties["Message"] = "Completed Successfully";

                        // Create the response message and send it on its way.
                        response.Add(responseMessage);
                    }
                    catch (TargetInvocationException invokationException)
                    {
                        // These exceptions can occur when we encounter a permission exception where
                        // the user doesn't have permission to execute a particular block of code.
                        if (invokationException.InnerException is SecurityException securityException)
                        {
                            throw new RoutePermissionException(GetPermissionErrorMessage(securityException), invokationException);
                        }

                        // Check for BadRequestException, we need to wrap it with the core exception.
                        // These exceptions can occur when query string parsing fails, and since the
                        // user's code doesn't have access to the core exceptions, we'll need to wrap
                        // it instead manually.
                        if (invokationException.InnerException is Common.BadRequestException badRequestException)
                        {
                            throw new Core.Exceptions.BadRequestException(badRequestException.Message, badRequestException);
                        }

                        // Otherwise it is most likely a custom user exception.
                        throw new CodeException(invokationException.InnerException?.Message ?? "Route raised a custom exception.", invokationException.InnerException);
                    }
                    catch (EntryPointException entryPointException)
                    {
                        // These exceptions occur when an entry point could not be located.
                        // Since we don't have a reference to core in the common library.
                        // We'll instead wrap this exception in a core
                        // exception to apply a status code.
                        throw new RouteEntryPointException(entryPointException.Message, entryPointException);
                    }
                    catch (SecurityException securityException)
                    {
                        // These exceptions can occur when we encounter a permission exception where
                        // the user doesn't have permission to execute a particular block of code.
                        throw new RoutePermissionException(GetPermissionErrorMessage(securityException), securityException);
                    }
                    catch (Common.BadRequestException badRequestException)
                    {
                        // These exceptions can occur when query string parsing fails, and since the
                        // user's code doesn't have access to the core exceptions, we'll need to wrap
                        // it instead manually.
                        throw new Core.Exceptions.BadRequestException(badRequestException.Message, badRequestException);
                    }
                    catch (AggregateException asyncException) // Captures async and task exceptions.
                    {
                        // These exceptions occur when an entry point could not be located.
                        // Since we don't have a reference to core in the common library.
                        // We'll instead wrap this exception in a core
                        // exception to apply a status code.
                        if (asyncException.InnerException is EntryPointException entryPointException)
                        {
                            throw new RouteEntryPointException(entryPointException.Message, entryPointException);
                        }

                        // These exceptions can occur when we encounter a permission exception where
                        // the user doesn't have permission to execute a particular block of code.
                        if (asyncException.InnerException is SecurityException securityException)
                        {
                            throw new RoutePermissionException(GetPermissionErrorMessage(securityException), securityException);
                        }

                        // These exceptions can occur when query string parsing fails, and since the
                        // user's code doesn't have access to the core exceptions, we'll need to wrap
                        // it instead manually.
                        if (asyncException.InnerException is SecurityException badRequestException)
                        {
                            throw new Core.Exceptions.BadRequestException(badRequestException.Message, badRequestException);
                        }

                        // These are all other exceptions that occur during the execution of
                        // a route. These exceptions are raised by the users code.
                        throw new RouteException(asyncException.InnerException?.Message ?? asyncException.Message, asyncException.InnerException);
                    }
                    catch (Exception routeException)
                    {
                        // These are all other exceptions that occur during the execution of
                        // a route. These exceptions are raised by the users code.
                        throw new RouteException(routeException.Message, routeException);
                    }
                }
                catch (Exception appDomainException)
                {
                    // This exception relates to exceptions configuring the AppDomain and we'll still notify the
                    // user, we just won't give them specific information that could reveal our infrastructure
                    // unless an IStatusCodeException was thrown, meaning it's a public exception.
                    var    statusCode          = 500;
                    var    statusMessage       = "An unexpected exception has occurred. Please contact Subroute.io regarding this error.";
                    var    statusCodeException = appDomainException as IStatusCodeException;
                    string stackTrace          = null;

                    if (statusCodeException != null)
                    {
                        statusCode    = (int)statusCodeException.StatusCode;
                        statusMessage = appDomainException.Message;

                        if (appDomainException is CodeException)
                        {
                            stackTrace = appDomainException.ToString();
                        }
                    }

                    request.CompletedOn     = DateTimeOffset.UtcNow;
                    request.StatusCode      = statusCode;
                    request.ResponsePayload = PayloadHelpers.CreateErrorPayload(statusMessage, stackTrace);
                    request.ResponseHeaders = HeaderHelpers.GetDefaultHeaders();

                    await Program.RequestRepository.UpdateRequestAsync(request).TraceTimeAsync("Update Request Record (Error)");

                    responseMessage.Properties["Result"]  = (int)ExecutionResult.Failed;
                    responseMessage.Properties["Message"] = appDomainException.Message;

                    // Create the response message and send it on its way.
                    response.Add(responseMessage);
                }
            }
            catch (Exception fatalException)
            {
                // These exceptions are absolutely fatal. We'll have to notify the waiting thread
                // via the service bus message, because we're unable to load a related request.
                responseMessage.Properties["Result"]  = (int)ExecutionResult.Fatal;
                responseMessage.Properties["Message"] = fatalException.Message;

                // Create the response message and send it on its way.
                response.Add(responseMessage);
            }
            finally
            {
                // Unload the users app domain to recover all memory used by it.
                if (sandboxDomain != null)
                {
                    TraceUtility.TraceTime("Unload AppDomain",
                                           () => AppDomain.Unload(sandboxDomain));
                }
            }
        }
Example #20
0
 /// <summary>
 /// Handles the Load event of the Page control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
 protected void Page_Load(object sender, EventArgs e)
 {
     SecurityManager.CheckRolePermission("order:admin:taxes:mng:import");
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SineHistoryProvider"/> class
 /// </summary>
 /// <param name="securities">Collection of securities that a history request can return</param>
 public SineHistoryProvider(SecurityManager securities)
 {
     _securities = securities;
 }
Example #22
0
        private void cmdDELETE_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime tglmemo   = ((DateTime)dataGridHeader.SelectedCells[0].OwningRow.Cells["TglMPR"].Value).Date;
                DateTime tglserver = GlobalVar.DateTimeOfServer.Date;
                switch (selectedGrid)
                {
                case enumSelectedGrid.HeaderSelected:
                    if (dataGridHeader.SelectedCells.Count == 0)
                    {
                        MessageBox.Show(Messages.Error.RowNotSelected);
                    }

                    if (tipeLokasi == "G")
                    {
                        MessageBox.Show("Anda tidak punya wewenang hapus data");
                        return;
                    }

                    if (bool.Parse(dataGridHeader.SelectedCells[0].OwningRow.Cells["isClosed"].Value.ToString()) == true)
                    {
                        MessageBox.Show("Tidak bisa hapus data sudah di audit");
                        return;
                    }

                    //if (dataGridHeader.SelectedCells[0].OwningRow.Cells["TglGudang"].Value.ToString() != "")
                    //{
                    //    MessageBox.Show("Sudah dibuat nota retur. Tidak bisa di hapus...!!!");
                    //    return;
                    //}

                    if (tglmemo != tglserver)
                    {
                        MessageBox.Show("Tidak bisa hapus record. Tanggal server beda dengan Tanggal Memo");
                        return;
                    }

                    if (dataGridDetail.Rows.Count > 0)
                    {
                        MessageBox.Show("Hapus detail dulu...!");
                        return;
                    }
                    if (!SecurityManager.IsManager())
                    {
                        MessageBox.Show("Hapus hanya dapat dilakukan oleh manager");
                        return;
                    }

                    //GlobalVar.LastClosingDate = (DateTime)dataGridHeader.SelectedCells[0].OwningRow.Cells["TglMPR"].Value;
                    //if ((DateTime)dataGridHeader.SelectedCells[0].OwningRow.Cells["TglMPR"].Value <= GlobalVar.LastClosingDate)
                    //{
                    //    throw new Exception(String.Format(Messages.Error.AlreadyClosingPJT, GlobalVar.LastClosingDate));
                    //}
                    if (MessageBox.Show("Hapus record ini?", "DELETE", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        Guid rowID = (Guid)dataGridHeader.SelectedCells[0].OwningRow.Cells["HeaderRowID"].Value;
                        try
                        {
                            this.Cursor = Cursors.WaitCursor;
                            using (Database db = new Database())
                            {
                                DataTable dt = new DataTable();
                                db.Commands.Add(db.CreateCommand("usp_ReturPenjualan_DELETE"));     //cek heri
                                db.Commands[0].Parameters.Add(new Parameter("@rowID", SqlDbType.UniqueIdentifier, rowID));

                                db.Commands[0].ExecuteNonQuery();
                            }

                            MessageBox.Show("Record telah dihapus");
                            this.RefreshDataReturJual();
                        }
                        catch (Exception ex)
                        {
                            Error.LogError(ex);
                        }
                        finally
                        {
                            this.Cursor = Cursors.Default;
                        }
                    }
                    break;

                case enumSelectedGrid.DetailSelected:
                    if (dataGridDetail.SelectedCells.Count == 0)
                    {
                        MessageBox.Show(Messages.Error.RowNotSelected);
                        return;
                    }

                    if (tipeLokasi == "G")
                    {
                        MessageBox.Show("Anda tidak punya wewenang hapus data");
                        return;
                    }

                    if (bool.Parse(dataGridHeader.SelectedCells[0].OwningRow.Cells["isClosed"].Value.ToString()) == true)
                    {
                        MessageBox.Show("Tidak bisa hapus data sudah di audit");
                        return;
                    }

                    //if (dataGridHeader.SelectedCells[0].OwningRow.Cells["TglGudang"].Value.ToString() != "")
                    //{
                    //    MessageBox.Show("Sudah dibuat nota retur. Tidak bisa di hapus...!!!");
                    //    return;
                    //}

                    bool link = (bool)(dataGridDetail.SelectedCells[0].OwningRow.Cells["DetailSyncFlag"].Value);
                    if (link)
                    {
                        MessageBox.Show("Sudah Link ke Piutang, tidak bisa dihapus");
                        return;
                    }

                    if (tglmemo != tglserver)
                    {
                        MessageBox.Show("Tidak bisa hapus record. Tanggal server beda dengan Tanggal Memo");
                        return;
                    }

                    if (!SecurityManager.IsManager())
                    {
                        MessageBox.Show("Hapus hanya dapat dilakukan oleh manager");
                        return;
                    }

                    GlobalVar.LastClosingDate = (DateTime)dataGridHeader.SelectedCells[0].OwningRow.Cells["TglMPR"].Value;
                    if ((DateTime)dataGridHeader.SelectedCells[0].OwningRow.Cells["TglMPR"].Value <= GlobalVar.LastClosingDate)
                    {
                        throw new Exception(String.Format(Messages.Error.AlreadyClosingPJT, GlobalVar.LastClosingDate));
                    }
                    if (MessageBox.Show("Hapus record ini?", "DELETE", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        Guid   rowID     = (Guid)dataGridDetail.SelectedCells[0].OwningRow.Cells["DetailRowID"].Value;
                        string kodeRetur = dataGridDetail.SelectedCells[0].OwningRow.Cells["KodeRetur"].Value.ToString();
                        string type_usp_DELETE;

                        if (kodeRetur == "1")
                        {
                            type_usp_DELETE = "usp_ReturPenjualanDetail_DELETE";     //cek heri
                        }
                        else
                        {
                            type_usp_DELETE = "usp_ReturPenjualanTarikanDetail_DELETE";     //cek heri
                        }
                        try
                        {
                            this.Cursor = Cursors.WaitCursor;
                            using (Database db = new Database())
                            {
                                db.Commands.Add(db.CreateCommand(type_usp_DELETE));
                                db.Commands[0].Parameters.Add(new Parameter("@rowID", SqlDbType.UniqueIdentifier, rowID));
                                db.Commands[0].ExecuteNonQuery();
                            }

                            MessageBox.Show("Record telah dihapus");
                            this.RefreshDataReturJualDetail();
                        }
                        catch (Exception ex)
                        {
                            Error.LogError(ex);
                        }
                        finally
                        {
                            this.Cursor = Cursors.Default;
                        }
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                Error.LogError(ex);
            }
        }
Example #23
0
        protected async Task <bool> HasAccessAsync(string securityKey)
        {
            bool result = await SecurityManager.HasAccessAsync(securityKey);

            return(result);
        }
Example #24
0
 protected bool HasAccess(string securityKey)
 {
     return(SecurityManager.HasAccess(securityKey));
 }
Example #25
0
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            var context = new HttpContextWrapper(HttpContext.Current);

            SecurityManager.PutOnCorrectTenant(context);
        }
Example #26
0
 public static IEnumerable <string> EnumerateFileSystemEntries(string path)
 {
     Path.Validate(path);                         // no need for EnumerateCheck since we supply valid arguments
     SecurityManager.EnsureElevatedPermissions(); // this is a no-op outside moonlight
     return(EnumerateKind(path, "*", SearchOption.TopDirectoryOnly, FileAttributes.Normal | FileAttributes.Directory));
 }
Example #27
0
        public void Start()
        {
            var entMan = new EntityManager();
            var relMan = new EntityRelationManager();
            var recMan = new RecordManager();
            var storeSystemSettings = DbContext.Current.SettingsRepository.Read();
            var systemSettings      = new SystemSettings(storeSystemSettings);

            //Open scope with a user we will use for the operations further ahead
            var user = new SecurityManager().GetUser(SystemIds.FirstUserId);

            using (SecurityContext.OpenScope(user))
            {
                //Create transaction
                using (var connection = DbContext.Current.CreateConnection())
                {
                    try
                    {
                        connection.BeginTransaction();
                        //Here we need to initialize or update the environment based on the plugin requirements.
                        //The default place for the plugin data is the "plugin_data" entity -> the "data" text field, which is used to store stringified JSON
                        //containing the plugin settings or version

                        #region << 1.Get the current ERP database version and checks for other plugin dependencies >>

                        if (systemSettings.Version > 0)
                        {
                            //Do something if database version is not what you expect
                        }

                        //This plugin needs the webvella-crm plugin to be installed, so we will check this here
                        var installedPlugins = new PluginService().Plugins;
                        var corePluginFound  = false;
                        foreach (var plugin in installedPlugins)
                        {
                            if (plugin.Name == "webvella-core")
                            {
                                corePluginFound = true;
                                break;
                            }
                        }

                        if (!corePluginFound)
                        {
                            throw new Exception("'webvella-core' plugin is required for the 'webvella-crm' to operate");
                        }

                        #endregion

                        #region << 2.Get the current plugin settings from the database >>
                        var         currentPluginSettings   = new PluginSettings();
                        QueryObject pluginDataQueryObject   = EntityQuery.QueryEQ("name", WEBVELLA_CRM_PLUGIN_NAME);
                        var         pluginDataQuery         = new EntityQuery("plugin_data", "*", pluginDataQueryObject);
                        var         pluginDataQueryResponse = recMan.Find(pluginDataQuery);
                        if (!pluginDataQueryResponse.Success)
                        {
                            throw new Exception("plugin 'webvella-project' failed to get its settings due to: " + pluginDataQueryResponse.Message);
                        }

                        if (pluginDataQueryResponse.Object == null || !pluginDataQueryResponse.Object.Data.Any() || pluginDataQueryResponse.Object.Data[0]["data"] == DBNull.Value)
                        {
                            //plugin was not installed
                            currentPluginSettings.Version = 20160429;
                            {
                                string json = JsonConvert.SerializeObject(currentPluginSettings);
                                var    settingsEntityRecord = new EntityRecord();
                                settingsEntityRecord["id"]   = WEBVELLA_CRM_PLUGIN_ID;
                                settingsEntityRecord["name"] = WEBVELLA_CRM_PLUGIN_NAME;
                                settingsEntityRecord["data"] = json;
                                var settingsSaveReponse = recMan.CreateRecord("plugin_data", settingsEntityRecord);
                                if (!settingsSaveReponse.Success)
                                {
                                    throw new Exception("plugin 'webvella-project' failed to save its settings in the database due to: " + pluginDataQueryResponse.Message);
                                }
                            }
                        }
                        else
                        {
                            string json = (string)((List <EntityRecord>)pluginDataQueryResponse.Object.Data)[0]["data"];
                            currentPluginSettings = JsonConvert.DeserializeObject <PluginSettings>(json);
                        }
                        #endregion

                        #region << 3. Run methods based on the current installed version of the plugin >>
                        if (currentPluginSettings.Version < 20160430)
                        {
                            currentPluginSettings.Version = 20160430;

                            #region << Create CRM admin area >>
                            //The areas are the main object for navigation for the user. You can attach entities and URLs later to them
                            {
                                var area = new EntityRecord();
                                area["id"]        = CRM_ADMIN_AREA_ID;
                                area["name"]      = "crm_admin";
                                area["label"]     = "CRM Admin";
                                area["icon_name"] = "users";
                                area["color"]     = "pink";
                                area["folder"]    = "Admin";
                                area["weight"]    = 100;
                                var areaRoles = new List <Guid>();
                                areaRoles.Add(SystemIds.AdministratorRoleId);
                                area["roles"] = JsonConvert.SerializeObject(areaRoles);
                                var createAreaResult = recMan.CreateRecord("area", area);
                                if (!createAreaResult.Success)
                                {
                                    throw new Exception("System error 10060. Area create with name : project_admin. Message:" + createAreaResult.Message);
                                }
                            }
                            #endregion

                            #region << wv_customer >>
                            {
                                #region << entity >>
                                {
                                    InputEntity entity = new InputEntity();
                                    entity.Id                          = CUSTOMER_ENTITY_ID;
                                    entity.Name                        = CUSTOMER_ENTITY_NAME;
                                    entity.Label                       = "Customer";
                                    entity.LabelPlural                 = "Customers";
                                    entity.System                      = true;
                                    entity.IconName                    = "building-o";
                                    entity.Weight                      = 2;
                                    entity.RecordPermissions           = new RecordPermissions();
                                    entity.RecordPermissions.CanCreate = new List <Guid>();
                                    entity.RecordPermissions.CanRead   = new List <Guid>();
                                    entity.RecordPermissions.CanUpdate = new List <Guid>();
                                    entity.RecordPermissions.CanDelete = new List <Guid>();
                                    //Create
                                    entity.RecordPermissions.CanCreate.Add(SystemIds.AdministratorRoleId);
                                    entity.RecordPermissions.CanCreate.Add(SystemIds.RegularRoleId);
                                    //READ
                                    entity.RecordPermissions.CanRead.Add(SystemIds.AdministratorRoleId);
                                    entity.RecordPermissions.CanRead.Add(SystemIds.RegularRoleId);
                                    //UPDATE
                                    entity.RecordPermissions.CanUpdate.Add(SystemIds.AdministratorRoleId);
                                    entity.RecordPermissions.CanUpdate.Add(SystemIds.RegularRoleId);

                                    {
                                        var response = entMan.CreateEntity(entity);
                                        if (!response.Success)
                                        {
                                            throw new Exception("System error 10050. Entity: " + CUSTOMER_ENTITY_NAME + " Field: entity creation" + " Message:" + response.Message);
                                        }
                                    }
                                }
                                #endregion

                                #region << name >>
                                {
                                    InputTextField textboxField = new InputTextField();
                                    textboxField.Id                    = new Guid("7fb95d0f-ab59-421d-974d-ab357e28a1f9");
                                    textboxField.Name                  = "name";
                                    textboxField.Label                 = "Name";
                                    textboxField.PlaceholderText       = "";
                                    textboxField.Description           = "";
                                    textboxField.HelpText              = "";
                                    textboxField.Required              = true;
                                    textboxField.Unique                = false;
                                    textboxField.Searchable            = true;
                                    textboxField.Auditable             = false;
                                    textboxField.System                = true;
                                    textboxField.DefaultValue          = string.Empty;
                                    textboxField.MaxLength             = null;
                                    textboxField.EnableSecurity        = true;
                                    textboxField.Permissions           = new FieldPermissions();
                                    textboxField.Permissions.CanRead   = new List <Guid>();
                                    textboxField.Permissions.CanUpdate = new List <Guid>();
                                    //READ
                                    textboxField.Permissions.CanRead.Add(SystemIds.AdministratorRoleId);
                                    textboxField.Permissions.CanRead.Add(SystemIds.RegularRoleId);
                                    //UPDATE
                                    textboxField.Permissions.CanUpdate.Add(SystemIds.AdministratorRoleId);
                                    {
                                        var response = entMan.CreateField(CUSTOMER_ENTITY_ID, textboxField, false);
                                        if (!response.Success)
                                        {
                                            throw new Exception("System error 10060. Entity: " + CUSTOMER_ENTITY_NAME + " Field: name" + " Message:" + response.Message);
                                        }
                                    }
                                }
                                #endregion
                            }
                            #endregion

                            #region << View name: admin_details >>
                            {
                                var createViewEntity = entMan.ReadEntity(CUSTOMER_ENTITY_ID).Object;
                                var createViewInput  = new InputRecordView();
                                var viewRegion       = new InputRecordViewRegion();
                                var viewSection      = new InputRecordViewSection();
                                var viewRow          = new InputRecordViewRow();
                                var viewColumn       = new InputRecordViewColumn();
                                var viewItem         = new InputRecordViewFieldItem();

                                #region << details >>
                                createViewInput.Id                  = new Guid("3a0e1319-5357-49ec-9e85-8d9be2363fcf");
                                createViewInput.Type                = "hidden";
                                createViewInput.Name                = "admin_details";
                                createViewInput.Label               = "Details";
                                createViewInput.Default             = false;
                                createViewInput.System              = false;
                                createViewInput.Weight              = 15;
                                createViewInput.CssClass            = null;
                                createViewInput.IconName            = "building-o";
                                createViewInput.DynamicHtmlTemplate = null;
                                createViewInput.DataSourceUrl       = null;
                                createViewInput.ServiceCode         = null;
                                createViewInput.Regions             = new List <InputRecordViewRegion>();
                                #endregion

                                #region << Header Region >>
                                viewRegion          = new InputRecordViewRegion();
                                viewRegion.Name     = "header";
                                viewRegion.Label    = "Header";
                                viewRegion.Render   = true;
                                viewRegion.Weight   = 1;
                                viewRegion.CssClass = "";
                                viewRegion.Sections = new List <InputRecordViewSection>();

                                #region << Section >>
                                viewSection           = new InputRecordViewSection();
                                viewSection.Id        = Guid.NewGuid();
                                viewSection.Name      = "details";
                                viewSection.Label     = "Details";
                                viewSection.ShowLabel = false;
                                viewSection.CssClass  = "";
                                viewSection.Collapsed = false;
                                viewSection.TabOrder  = "left-right";
                                viewSection.Weight    = 1;
                                viewSection.Rows      = new List <InputRecordViewRow>();

                                #region << Row >>
                                viewRow         = new InputRecordViewRow();
                                viewRow.Id      = Guid.NewGuid();
                                viewRow.Weight  = 1;
                                viewRow.Columns = new List <InputRecordViewColumn>();

                                #region << Column 1 >>
                                viewColumn = new InputRecordViewColumn();
                                viewColumn.GridColCount = 12;
                                viewColumn.Items        = new List <InputRecordViewItemBase>();


                                #region << name >>
                                {
                                    viewItem            = new InputRecordViewFieldItem();
                                    viewItem.EntityId   = CUSTOMER_ENTITY_ID;
                                    viewItem.EntityName = CUSTOMER_ENTITY_NAME;
                                    viewItem.FieldId    = createViewEntity.Fields.Single(x => x.Name == "name").Id;
                                    viewItem.FieldName  = "name";
                                    viewItem.Type       = "field";
                                    viewColumn.Items.Add(viewItem);
                                }
                                #endregion


                                //Save column
                                viewRow.Columns.Add(viewColumn);
                                #endregion

                                //Save row
                                viewSection.Rows.Add(viewRow);
                                #endregion

                                //Save section
                                viewRegion.Sections.Add(viewSection);
                                #endregion

                                //Save region
                                createViewInput.Regions.Add(viewRegion);
                                #endregion

                                #region << relation options >>
                                createViewInput.RelationOptions = new List <EntityRelationOptionsItem>();
                                #endregion

                                #region << Sidebar >>
                                createViewInput.Sidebar          = new InputRecordViewSidebar();
                                createViewInput.Sidebar.CssClass = "";
                                createViewInput.Sidebar.Render   = true;
                                createViewInput.Sidebar.Render   = true;
                                createViewInput.Sidebar.Items    = new List <InputRecordViewSidebarItemBase>();
                                #endregion

                                #region << action items >>
                                createViewInput.ActionItems = new List <ActionItem>();
                                var actionItem = new ActionItem();
                                {
                                    actionItem          = new ActionItem();
                                    actionItem.Name     = "wv_record_delete";
                                    actionItem.Menu     = "page-title-dropdown";
                                    actionItem.Weight   = 1;
                                    actionItem.Template = "" +
                                                          @"<a href=""javascript:void(0)"" confirmed-click=""ngCtrl.deleteRecord(ngCtrl)"" ng-confirm-click=""Are you sure?""
										ng-if=""::ngCtrl.userHasRecordPermissions('canDelete')"">
									<i class=""fa fa-trash go-red""></i> Delete Record
								</a>"                                ;
                                    createViewInput.ActionItems.Add(actionItem);
                                }
                                {
                                    actionItem          = new ActionItem();
                                    actionItem.Name     = "wv_back_button";
                                    actionItem.Menu     = "sidebar-top";
                                    actionItem.Weight   = 1;
                                    actionItem.Template = "" +
                                                          @"<a class=""back clearfix"" href=""javascript:void(0)"" ng-click=""sidebarData.goBack()""><i class=""fa fa-fw fa-arrow-left""></i> <span class=""text"">Back</span></a>";
                                    createViewInput.ActionItems.Add(actionItem);
                                }
                                #endregion

                                {
                                    var response = entMan.CreateRecordView(CUSTOMER_ENTITY_ID, createViewInput);
                                    if (!response.Success)
                                    {
                                        throw new Exception("System error 10060. Entity: " + CUSTOMER_ENTITY_NAME + " Updated view: admin_details" + " Message:" + response.Message);
                                    }
                                }
                            }
                            #endregion

                            #region << View name: admin_create >>
                            {
                                var createViewEntity = entMan.ReadEntity(CUSTOMER_ENTITY_ID).Object;
                                var createViewInput  = new InputRecordView();
                                var viewRegion       = new InputRecordViewRegion();
                                var viewSection      = new InputRecordViewSection();
                                var viewRow          = new InputRecordViewRow();
                                var viewColumn       = new InputRecordViewColumn();
                                var viewItem         = new InputRecordViewFieldItem();

                                #region << details >>
                                createViewInput.Id                  = new Guid("93043954-ae70-41a3-b4b7-665531a23a76");
                                createViewInput.Type                = "create";
                                createViewInput.Name                = "admin_create";
                                createViewInput.Label               = "Create customer";
                                createViewInput.Default             = false;
                                createViewInput.System              = false;
                                createViewInput.Weight              = 25;
                                createViewInput.CssClass            = null;
                                createViewInput.IconName            = "building-o";
                                createViewInput.DynamicHtmlTemplate = null;
                                createViewInput.DataSourceUrl       = null;
                                createViewInput.ServiceCode         = null;
                                createViewInput.Regions             = new List <InputRecordViewRegion>();
                                #endregion

                                #region << Header Region >>
                                viewRegion          = new InputRecordViewRegion();
                                viewRegion.Name     = "header";
                                viewRegion.Label    = "Header";
                                viewRegion.Render   = true;
                                viewRegion.Weight   = 1;
                                viewRegion.CssClass = "";
                                viewRegion.Sections = new List <InputRecordViewSection>();

                                #region << Section >>
                                viewSection           = new InputRecordViewSection();
                                viewSection.Id        = Guid.NewGuid();
                                viewSection.Name      = "details";
                                viewSection.Label     = "Details";
                                viewSection.ShowLabel = false;
                                viewSection.CssClass  = "";
                                viewSection.Collapsed = false;
                                viewSection.TabOrder  = "left-right";
                                viewSection.Weight    = 1;
                                viewSection.Rows      = new List <InputRecordViewRow>();

                                #region << Row >>
                                viewRow         = new InputRecordViewRow();
                                viewRow.Id      = Guid.NewGuid();
                                viewRow.Weight  = 1;
                                viewRow.Columns = new List <InputRecordViewColumn>();

                                #region << Column 1 >>
                                viewColumn = new InputRecordViewColumn();
                                viewColumn.GridColCount = 12;
                                viewColumn.Items        = new List <InputRecordViewItemBase>();


                                #region << name >>
                                {
                                    viewItem            = new InputRecordViewFieldItem();
                                    viewItem.EntityId   = CUSTOMER_ENTITY_ID;
                                    viewItem.EntityName = CUSTOMER_ENTITY_NAME;
                                    viewItem.FieldId    = createViewEntity.Fields.Single(x => x.Name == "name").Id;
                                    viewItem.FieldName  = "name";
                                    viewItem.Type       = "field";
                                    viewColumn.Items.Add(viewItem);
                                }
                                #endregion


                                //Save column
                                viewRow.Columns.Add(viewColumn);
                                #endregion

                                //Save row
                                viewSection.Rows.Add(viewRow);
                                #endregion

                                //Save section
                                viewRegion.Sections.Add(viewSection);
                                #endregion

                                //Save region
                                createViewInput.Regions.Add(viewRegion);
                                #endregion

                                #region << relation options >>
                                createViewInput.RelationOptions = new List <EntityRelationOptionsItem>();
                                #endregion

                                #region << Sidebar >>
                                createViewInput.Sidebar          = new InputRecordViewSidebar();
                                createViewInput.Sidebar.CssClass = "";
                                createViewInput.Sidebar.Render   = true;
                                createViewInput.Sidebar.Render   = true;
                                createViewInput.Sidebar.Items    = new List <InputRecordViewSidebarItemBase>();
                                #endregion

                                #region << action items >>
                                createViewInput.ActionItems = new List <ActionItem>();
                                var actionItem = new ActionItem();

                                {
                                    actionItem          = new ActionItem();
                                    actionItem.Name     = "wv_create_and_list";
                                    actionItem.Menu     = "create-bottom";
                                    actionItem.Weight   = 1;
                                    actionItem.Template = "" +
                                                          @"<a class=""btn btn-primary"" ng-click='ngCtrl.create(""default"")' ng-if=""ngCtrl.createViewRegion != null"">Create</a>";
                                    createViewInput.ActionItems.Add(actionItem);
                                }
                                {
                                    actionItem          = new ActionItem();
                                    actionItem.Name     = "wv_create_and_details";
                                    actionItem.Menu     = "create-bottom";
                                    actionItem.Weight   = 2;
                                    actionItem.Template = "" +
                                                          @"<a class=""btn btn-default btn-outline"" ng-click='ngCtrl.create(""details"")' ng-if=""ngCtrl.createViewRegion != null"">Create & Details</a>";
                                    createViewInput.ActionItems.Add(actionItem);
                                }
                                {
                                    actionItem          = new ActionItem();
                                    actionItem.Name     = "wv_create_cancel";
                                    actionItem.Menu     = "create-bottom";
                                    actionItem.Weight   = 3;
                                    actionItem.Template = "" +
                                                          @"<a class=""btn btn-default btn-outline"" ng-click=""ngCtrl.cancel()"">Cancel</a>";
                                    createViewInput.ActionItems.Add(actionItem);
                                }
                                {
                                    actionItem          = new ActionItem();
                                    actionItem.Name     = "wv_back_button";
                                    actionItem.Menu     = "sidebar-top";
                                    actionItem.Weight   = 1;
                                    actionItem.Template = "" +
                                                          @"<a class=""back clearfix"" href=""javascript:void(0)"" ng-click=""sidebarData.goBack()""><i class=""fa fa-fw fa-arrow-left""></i> <span class=""text"">Back</span></a>";
                                    createViewInput.ActionItems.Add(actionItem);
                                }
                                #endregion
                                {
                                    var response = entMan.CreateRecordView(CUSTOMER_ENTITY_ID, createViewInput);
                                    if (!response.Success)
                                    {
                                        throw new Exception("System error 10060. Entity: " + CUSTOMER_ENTITY_NAME + " Updated view: admin_create" + " Message:" + response.Message);
                                    }
                                }
                            }
                            #endregion

                            #region << List name: admin >>
                            {
                                var createListEntity = entMan.ReadEntity(CUSTOMER_ENTITY_ID).Object;
                                var createListInput  = new InputRecordList();
                                var listItem         = new InputRecordListFieldItem();
                                var listSort         = new InputRecordListSort();
                                var listQuery        = new InputRecordListQuery();

                                #region << details >>
                                createListInput.Id                  = new Guid("ff15f200-8e68-4683-8576-4c8244405ca9");
                                createListInput.Type                = "hidden";
                                createListInput.Name                = "admin";
                                createListInput.Label               = "Customers";
                                createListInput.Weight              = 11;
                                createListInput.Default             = false;
                                createListInput.System              = true;
                                createListInput.CssClass            = null;
                                createListInput.IconName            = "building-o";
                                createListInput.VisibleColumnsCount = 7;
                                createListInput.ColumnWidthsCSV     = null;
                                createListInput.PageSize            = 10;
                                createListInput.DynamicHtmlTemplate = null;
                                createListInput.DataSourceUrl       = null;
                                createListInput.ServiceCode         = null;
                                #endregion

                                #region << action items >>
                                createListInput.ActionItems = new List <ActionItem>();
                                var actionItem = new ActionItem();
                                {
                                    actionItem          = new ActionItem();
                                    actionItem.Name     = "wv_record_details";
                                    actionItem.Menu     = "record-row";
                                    actionItem.Weight   = 1;
                                    actionItem.Template = "" +
                                                          @"<a class=""btn btn-default btn-outline"" ng-href=""{{::ngCtrl.getRecordDetailsUrl(record, ngCtrl)}}"">
							<i class=""fa fa-fw fa-eye""></i>
							</a>"                            ;
                                    createListInput.ActionItems.Add(actionItem);
                                }
                                {
                                    actionItem          = new ActionItem();
                                    actionItem.Name     = "wv_create_record";
                                    actionItem.Menu     = "page-title";
                                    actionItem.Weight   = 1;
                                    actionItem.Template = "" +
                                                          @"<a class=""btn btn-default btn-outline hidden-xs"" ng-show=""::ngCtrl.userHasRecordPermissions('canCreate')"" 
    ng-href=""{{::ngCtrl.getRecordCreateUrl(ngCtrl)}}"">
	<i class=""fa fa-fw fa-plus""></i> Add New
</a>";
                                    createListInput.ActionItems.Add(actionItem);
                                }
                                #endregion

                                #region << Columns >>
                                createListInput.Columns = new List <InputRecordListItemBase>();
                                #region << name >>
                                {
                                    var fieldName = "name";
                                    listItem            = new InputRecordListFieldItem();
                                    listItem.EntityId   = CUSTOMER_ENTITY_ID;
                                    listItem.EntityName = CUSTOMER_ENTITY_NAME;
                                    listItem.FieldId    = createListEntity.Fields.Single(x => x.Name == fieldName).Id;
                                    listItem.FieldName  = fieldName;
                                    listItem.Type       = "field";
                                    createListInput.Columns.Add(listItem);
                                }
                                #endregion

                                #endregion

                                #region << relation options >>
                                createListInput.RelationOptions = new List <EntityRelationOptionsItem>();
                                #endregion

                                #region << query >>
                                listQuery = new InputRecordListQuery();
                                #endregion

                                #region << Sort >>
                                listSort = new InputRecordListSort();
                                #endregion
                                {
                                    var response = entMan.CreateRecordList(CUSTOMER_ENTITY_ID, createListInput);
                                    if (!response.Success)
                                    {
                                        throw new Exception("System error 10060. Entity: " + CUSTOMER_ENTITY_NAME + " Updated List: admin" + " Message:" + response.Message);
                                    }
                                }
                            }
                            #endregion

                            #region << area add subscription: CRM Admin -> Customer >>
                            {
                                var updatedAreaId    = CRM_ADMIN_AREA_ID;
                                var updateAreaResult = Helpers.UpsertEntityAsAreaSubscription(entMan, recMan, updatedAreaId, CUSTOMER_ENTITY_NAME, "admin_details", "admin_create", "admin");
                                if (!updateAreaResult.Success)
                                {
                                    throw new Exception("System error 10060. Area update with id : " + updatedAreaId + " Message:" + updateAreaResult.Message);
                                }
                            }
                            #endregion

                            #region << customer lookup list >>
                            {
                                var updateListEntity = entMan.ReadEntity(CUSTOMER_ENTITY_ID).Object;
                                var updateList       = updateListEntity.RecordLists.Single(x => x.Name == "lookup");
                                var updateListInput  = new InputRecordList();
                                var listItem         = new InputRecordListFieldItem();
                                var listSort         = new InputRecordListSort();
                                var listQuery        = new InputRecordListQuery();

                                //Convert recordList to recordListInput
                                updateListInput = updateList.DynamicMapTo <InputRecordList>();

                                //General list details
                                //updateListInput.IconName = "";

                                //Fields
                                #region << name >>
                                listItem            = new InputRecordListFieldItem();
                                listItem.EntityId   = CUSTOMER_ENTITY_ID;
                                listItem.EntityName = "customer";
                                listItem.FieldId    = updateListEntity.Fields.Single(x => x.Name == "name").Id;
                                listItem.FieldName  = "name";
                                listItem.Type       = "field";
                                updateListInput.Columns.Add(listItem);
                                #endregion

                                //Query
                                #region << query descr >>
                                listQuery = new InputRecordListQuery();
                                #endregion


                                //Sort
                                #region << Sort >>
                                listSort           = new InputRecordListSort();
                                listSort.FieldName = "name";
                                listSort.SortType  = "ascending";
                                updateListInput.Sorts.Add(listSort);
                                #endregion
                                {
                                    var responseObject = entMan.UpdateRecordList(CUSTOMER_ENTITY_ID, updateListInput);
                                    if (!responseObject.Success)
                                    {
                                        throw new Exception("System error 10060. Entity: " + "user" + " Updated List: list_name" + " Message:" + responseObject.Message);
                                    }
                                }
                            }
                            #endregion

                            if (createSampleRecords)
                            {
                                #region << Create Sample Customer >>
                                {
                                    var sampleRecord = new EntityRecord();
                                    sampleRecord["id"]   = new Guid("fb06213f-7632-495b-bb8d-ed5ff07dc515");
                                    sampleRecord["name"] = "Buckley Miller & Wright";
                                    var createSampleRecordResult = recMan.CreateRecord(CUSTOMER_ENTITY_NAME, sampleRecord);
                                    if (!createSampleRecordResult.Success)
                                    {
                                        throw new Exception("System error 10060. Create sample record. Message:" + createSampleRecordResult.Message);
                                    }
                                }
                                #endregion

                                #region << Create Sample Customer User >>
                                {
                                    var sampleRecord = new EntityRecord();
                                    sampleRecord["id"]         = new Guid("307fe376-a1c6-495e-a7c0-2a78797565f2");
                                    sampleRecord["first_name"] = "Sample";
                                    sampleRecord["last_name"]  = "Customer";
                                    sampleRecord["username"]   = "******";
                                    sampleRecord["email"]      = "*****@*****.**";
                                    sampleRecord["password"]   = "******";
                                    sampleRecord["enabled"]    = true;
                                    sampleRecord["verified"]   = true;
                                    sampleRecord["image"]      = "/plugins/webvella-core/assets/avatar-deep-purple.png";
                                    var createSampleRecordResult = recMan.CreateRecord(SystemIds.UserEntityId, sampleRecord);
                                    if (!createSampleRecordResult.Success)
                                    {
                                        throw new Exception("System error 10060. Create sample customer record. Message:" + createSampleRecordResult.Message);
                                    }
                                }
                                #endregion

                                #region << Create Sample User Role>>
                                {
                                    var sampleRecord = new EntityRecord();
                                    sampleRecord["id"]          = new Guid("27745245-09bd-4adb-8831-3870bcae46fe");
                                    sampleRecord["name"]        = "crm_customer";
                                    sampleRecord["description"] = "Sample Customer role for CRM application";
                                    var createSampleRecordResult = recMan.CreateRecord(SystemIds.RoleEntityId, sampleRecord);
                                    if (!createSampleRecordResult.Success)
                                    {
                                        throw new Exception("System error 10060. Create sample role record. Message:" + createSampleRecordResult.Message);
                                    }
                                }
                                #endregion

                                #region << Create relation between sample customer and role >>
                                {
                                    var createRelationNtoNResponse = recMan.CreateRelationManyToManyRecord(new Guid("0c4b119e-1d7b-4b40-8d2c-9e447cc656ab"), new Guid("27745245-09bd-4adb-8831-3870bcae46fe"), new Guid("307fe376-a1c6-495e-a7c0-2a78797565f2"));
                                    if (!createRelationNtoNResponse.Success)
                                    {
                                        throw new Exception("Could not create item image relation" + createRelationNtoNResponse.Message);
                                    }
                                }
                                #endregion

                                #region << Create relation between sample customer and regular role >>
                                {
                                    var createRelationNtoNResponse = recMan.CreateRelationManyToManyRecord(new Guid("0c4b119e-1d7b-4b40-8d2c-9e447cc656ab"), new Guid("f16ec6db-626d-4c27-8de0-3e7ce542c55f"), new Guid("307fe376-a1c6-495e-a7c0-2a78797565f2"));
                                    if (!createRelationNtoNResponse.Success)
                                    {
                                        throw new Exception("Could not create item image relation" + createRelationNtoNResponse.Message);
                                    }
                                }
                                #endregion
                            }
                        }
                        #endregion

                        #region << 4. Save needed changes to the plugin setting data >>
                        {
                            string json = JsonConvert.SerializeObject(currentPluginSettings);
                            var    settingsEntityRecord = new EntityRecord();
                            settingsEntityRecord["id"]   = WEBVELLA_CRM_PLUGIN_ID;
                            settingsEntityRecord["name"] = WEBVELLA_CRM_PLUGIN_NAME;
                            settingsEntityRecord["data"] = json;
                            var settingsUpdateReponse = recMan.UpdateRecord("plugin_data", settingsEntityRecord);
                            if (!settingsUpdateReponse.Success)
                            {
                                throw new Exception("plugin 'webvella-project' failed to update its settings in the database due to: " + pluginDataQueryResponse.Message);
                            }
                        }
                        #endregion

                        connection.CommitTransaction();
                    }
                    catch (Exception ex)
                    {
                        connection.RollbackTransaction();
                        throw ex;
                    }
                }
            }
        }
Example #28
0
        public void EnsureCurrencyDataFeedDoesNotMarkIsCurrencyDataFeedForExistantSubscriptions()
        {
            const int quantity = 100;
            const decimal conversionRate = 1 / 100m;
            var cash = new Cash("JPY", quantity, conversionRate);
            var cashBook = new CashBook();
            cashBook.Add("JPY", cash);

            var subscriptions = new SubscriptionManager(TimeKeeper);
            var securities = new SecurityManager(TimeKeeper);
            securities.Add(Symbols.USDJPY, new Security(SecurityExchangeHours, subscriptions.Add(Symbols.USDJPY, Resolution.Minute, TimeZone, TimeZone), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency)));

            cash.EnsureCurrencyDataFeed(securities, subscriptions, MarketHoursDatabase.AlwaysOpen, SymbolPropertiesDatabase.FromDataFolder(), MarketMap, cashBook);
            var config = subscriptions.Subscriptions.Single(x => x.Symbol == Symbols.USDJPY);
            Assert.IsFalse(config.IsInternalFeed);
        }
Example #29
0
        public void UpdateModifiesConversionRate()
        {
            const int quantity = 100;
            const decimal conversionRate = 1 / 100m;
            var cash = new Cash("GBP", quantity, conversionRate);
            var cashBook = new CashBook();
            cashBook.Add("GBP", cash);

            var subscriptions = new SubscriptionManager(TimeKeeper);
            var securities = new SecurityManager(TimeKeeper);
            securities.Add(Symbols.GBPUSD, new Security(SecurityExchangeHours, subscriptions.Add(Symbols.GBPUSD, Resolution.Minute, TimeZone, TimeZone), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency)));

            // we need to get subscription index
            cash.EnsureCurrencyDataFeed(securities, subscriptions, MarketHoursDatabase.AlwaysOpen, SymbolPropertiesDatabase.FromDataFolder(), MarketMap, cashBook);

            var last = 1.5m;
            cash.Update(new Tick(DateTime.Now, Symbols.GBPUSD, last, last * 1.009m, last * 0.009m));

            // jpy is inverted, so compare on the inverse
            Assert.AreEqual(last, cash.ConversionRate);
        }
        public void ForexCashFills()
        {
            // this test asserts the portfolio behaves according to the Test_Cash algo, but for a Forex security, 
            // see TestData\CashTestingStrategy.csv; also "https://www.dropbox.com/s/oiliumoyqqj1ovl/2013-cash.csv?dl=1"

            const string fillsFile = "TestData\\test_forex_fills.xml";
            const string equityFile = "TestData\\test_forex_equity.xml";
            const string mchQuantityFile = "TestData\\test_forex_fills_mch_quantity.xml";
            const string jwbQuantityFile = "TestData\\test_forex_fills_jwb_quantity.xml";

            var fills = XDocument.Load(fillsFile).Descendants("OrderEvent").Select(x => new OrderEvent(
                x.Get<int>("OrderId"),
                SymbolMap[x.Get<string>("Symbol")],
                DateTime.MinValue,
                x.Get<OrderStatus>("Status"),
                x.Get<int>("FillQuantity") < 0 ? OrderDirection.Sell 
              : x.Get<int>("FillQuantity") > 0 ? OrderDirection.Buy 
                                               : OrderDirection.Hold,
                x.Get<decimal>("FillPrice"),
                x.Get<int>("FillQuantity"),
                0)
                ).ToList();

            var equity = XDocument.Load(equityFile).Descendants("decimal")
                .Select(x => decimal.Parse(x.Value, CultureInfo.InvariantCulture))
                .ToList();

            var mchQuantity = XDocument.Load(mchQuantityFile).Descendants("decimal")
                .Select(x => decimal.Parse(x.Value, CultureInfo.InvariantCulture))
                .ToList();

            var jwbQuantity = XDocument.Load(jwbQuantityFile).Descendants("decimal")
                .Select(x => decimal.Parse(x.Value, CultureInfo.InvariantCulture))
                .ToList();

            Assert.AreEqual(fills.Count + 1, equity.Count);

            // we're going to process fills and very our equity after each fill
            var subscriptions = new SubscriptionManager(TimeKeeper);
            var securities = new SecurityManager(TimeKeeper);
            var transactions = new SecurityTransactionManager(securities);
            var portfolio = new SecurityPortfolioManager(securities, transactions);
            portfolio.SetCash(equity[0]);
            portfolio.CashBook.Add("MCH", mchQuantity[0], 0);
            portfolio.CashBook.Add("JWB", jwbQuantity[0], 0);

            var jwbCash = portfolio.CashBook["JWB"];
            var mchCash = portfolio.CashBook["MCH"];
            var usdCash = portfolio.CashBook["USD"];

            var mchJwbSecurity = new QuantConnect.Securities.Forex.Forex(SecurityExchangeHours, jwbCash, subscriptions.Add(MCHJWB, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork), SymbolProperties.GetDefault(jwbCash.Symbol));
            mchJwbSecurity.SetLeverage(10m);
            var mchUsdSecurity = new QuantConnect.Securities.Forex.Forex(SecurityExchangeHours, usdCash, subscriptions.Add(MCHUSD, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork), SymbolProperties.GetDefault(usdCash.Symbol));
            mchUsdSecurity.SetLeverage(10m);
            var usdJwbSecurity = new QuantConnect.Securities.Forex.Forex(SecurityExchangeHours, mchCash, subscriptions.Add(USDJWB, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork), SymbolProperties.GetDefault(mchCash.Symbol));
            usdJwbSecurity.SetLeverage(10m);
            
            // no fee model
            mchJwbSecurity.TransactionModel = new SecurityTransactionModel();
            mchUsdSecurity.TransactionModel = new SecurityTransactionModel();
            usdJwbSecurity.TransactionModel = new SecurityTransactionModel();

            securities.Add(mchJwbSecurity);
            securities.Add(usdJwbSecurity);
            securities.Add(mchUsdSecurity);

            portfolio.CashBook.EnsureCurrencyDataFeeds(securities, subscriptions, MarketHoursDatabase.FromDataFolder(), SymbolPropertiesDatabase.FromDataFolder(), DefaultBrokerageModel.DefaultMarketMap);

            for (int i = 0; i < fills.Count; i++)
            {
                // before processing the fill we must deduct the cost
                var fill = fills[i];
                var time = DateTime.Today.AddDays(i);

                // the value of 'MCJWB' increments for each fill, the original test algo did this monthly
                // the time doesn't really matter though
                decimal mchJwb = i + 1;
                decimal mchUsd = (i + 1)/(i + 2m);
                decimal usdJwb = i + 2;
                Assert.AreEqual((double)mchJwb, (double)(mchUsd*usdJwb), 1e-10);
                //Console.WriteLine("Step: " + i + " -- MCHJWB: " + mchJwb);


                jwbCash.Update(new IndicatorDataPoint(MCHJWB, time, mchJwb));
                usdCash.Update(new IndicatorDataPoint(MCHUSD, time, mchUsd));
                mchCash.Update(new IndicatorDataPoint(JWBUSD, time, usdJwb));

                var updateData = new Dictionary<Security, BaseData>
                {
                    {mchJwbSecurity, new IndicatorDataPoint(MCHJWB, time, mchJwb)},
                    {mchUsdSecurity, new IndicatorDataPoint(MCHUSD, time, mchUsd)},
                    {usdJwbSecurity, new IndicatorDataPoint(JWBUSD, time, usdJwb)}
                };

                foreach (var kvp in updateData)
                {
                    kvp.Key.SetMarketPrice(kvp.Value);
                }

                portfolio.ProcessFill(fill);
                //Console.WriteLine("-----------------------");
                //Console.WriteLine(fill);

                //Console.WriteLine("Post step: " + i);
                //foreach (var cash in portfolio.CashBook)
                //{
                //    Console.WriteLine(cash.Value);
                //}
                //Console.WriteLine("CashValue: " + portfolio.CashBook.TotalValueInAccountCurrency);

                Console.WriteLine(i + 1 + "   " + portfolio.TotalPortfolioValue.ToString("C"));
                //Assert.AreEqual((double) equity[i + 1], (double)portfolio.TotalPortfolioValue, 2e-2);
                Assert.AreEqual((double) mchQuantity[i + 1], (double)portfolio.CashBook["MCH"].Amount);
                Assert.AreEqual((double) jwbQuantity[i + 1], (double)portfolio.CashBook["JWB"].Amount);

                //Console.WriteLine();
                //Console.WriteLine();
            }
        }
        public void MarginComputesProperlyWithMultipleSecurities()
        {
            var securities = new SecurityManager(TimeKeeper);
            var transactions = new SecurityTransactionManager(securities);
            var orderProcessor = new OrderProcessor();
            transactions.SetOrderProcessor(orderProcessor);
            var portfolio = new SecurityPortfolioManager(securities, transactions);
            portfolio.CashBook["USD"].SetAmount(1000);
            portfolio.CashBook.Add("EUR",  1000, 1.1m);
            portfolio.CashBook.Add("GBP", -1000, 2.0m);

            var eurCash = portfolio.CashBook["EUR"];
            var gbpCash = portfolio.CashBook["GBP"];
            var usdCash = portfolio.CashBook["USD"];

            var time = DateTime.Now;
            var config1 = CreateTradeBarDataConfig(SecurityType.Equity, Symbols.AAPL);
            securities.Add(new Security(SecurityExchangeHours, config1, new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency)));
            securities[Symbols.AAPL].SetLeverage(2m);
            securities[Symbols.AAPL].Holdings.SetHoldings(100, 100);
            securities[Symbols.AAPL].SetMarketPrice(new TradeBar{Time = time, Value = 100});
            //Console.WriteLine("AAPL TMU: " + securities[Symbols.AAPL].MarginModel.GetMaintenanceMargin(securities[Symbols.AAPL]));
            //Console.WriteLine("AAPL Value: " + securities[Symbols.AAPL].Holdings.HoldingsValue);

            //Console.WriteLine();

            var config2 = CreateTradeBarDataConfig(SecurityType.Forex, Symbols.EURUSD);
            securities.Add(new QuantConnect.Securities.Forex.Forex(SecurityExchangeHours, usdCash, config2, SymbolProperties.GetDefault(CashBook.AccountCurrency)));
            securities[Symbols.EURUSD].SetLeverage(100m);
            securities[Symbols.EURUSD].Holdings.SetHoldings(1.1m, 1000);
            securities[Symbols.EURUSD].SetMarketPrice(new TradeBar { Time = time, Value = 1.1m });
            //Console.WriteLine("EURUSD TMU: " + securities[Symbols.EURUSD].MarginModel.GetMaintenanceMargin(securities[Symbols.EURUSD]));
            //Console.WriteLine("EURUSD Value: " + securities[Symbols.EURUSD].Holdings.HoldingsValue);

            //Console.WriteLine();

            var config3 = CreateTradeBarDataConfig(SecurityType.Forex, Symbols.EURGBP);
            securities.Add(new QuantConnect.Securities.Forex.Forex(SecurityExchangeHours, gbpCash, config3, SymbolProperties.GetDefault(gbpCash.Symbol)));
            securities[Symbols.EURGBP].SetLeverage(100m);
            securities[Symbols.EURGBP].Holdings.SetHoldings(1m, 1000);
            securities[Symbols.EURGBP].SetMarketPrice(new TradeBar { Time = time, Value = 1m });
            //Console.WriteLine("EURGBP TMU: " + securities[Symbols.EURGBP].MarginModel.GetMaintenanceMargin(securities[Symbols.EURGBP]));
            //Console.WriteLine("EURGBP Value: " + securities[Symbols.EURGBP].Holdings.HoldingsValue);

            //Console.WriteLine();

            //Console.WriteLine(portfolio.CashBook["USD"]);
            //Console.WriteLine(portfolio.CashBook["EUR"]);
            //Console.WriteLine(portfolio.CashBook["GBP"]);
            //Console.WriteLine("CashBook: " + portfolio.CashBook.TotalValueInAccountCurrency);

            //Console.WriteLine();

            //Console.WriteLine("Total Margin Used: " + portfolio.TotalMarginUsed);
            //Console.WriteLine("Total Free Margin: " + portfolio.MarginRemaining);
            //Console.WriteLine("Total Portfolio Value: " + portfolio.TotalPortfolioValue);


            var acceptedOrder = new MarketOrder(Symbols.AAPL, 101, DateTime.Now) { Price = 100 };
            orderProcessor.AddOrder(acceptedOrder);
            var request = new SubmitOrderRequest(OrderType.Market, acceptedOrder.SecurityType, acceptedOrder.Symbol, acceptedOrder.Quantity, 0, 0, acceptedOrder.Time, null);
            request.SetOrderId(0);
            orderProcessor.AddTicket(new OrderTicket(null, request));
            var sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, acceptedOrder);
            Assert.IsTrue(sufficientCapital);

            var rejectedOrder = new MarketOrder(Symbols.AAPL, 102, DateTime.Now) { Price = 100 };
            sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, rejectedOrder);
            Assert.IsFalse(sufficientCapital);
        }
        public void ForexFillUpdatesCashCorrectly()
        {
            var securities = new SecurityManager(TimeKeeper);
            var transactions = new SecurityTransactionManager(securities);
            var portfolio = new SecurityPortfolioManager(securities, transactions);
            portfolio.SetCash(1000);
            portfolio.CashBook.Add("EUR", 0, 1.1000m);

            securities.Add(Symbols.EURUSD, new QuantConnect.Securities.Forex.Forex(SecurityExchangeHours, portfolio.CashBook["USD"], CreateTradeBarDataConfig(SecurityType.Forex, Symbols.EURUSD), SymbolProperties.GetDefault(CashBook.AccountCurrency)));
            var security = securities[Symbols.EURUSD];
            Assert.AreEqual(0, security.Holdings.Quantity);
            Assert.AreEqual(1000, portfolio.Cash);

            var orderFee = security.FeeModel.GetOrderFee(security, new MarketOrder(Symbols.EURUSD, 100, DateTime.MinValue));
            var fill = new OrderEvent(1, Symbols.EURUSD, DateTime.MinValue, OrderStatus.Filled, OrderDirection.Buy, 1.1000m, 100, orderFee);
            portfolio.ProcessFill(fill);
            Assert.AreEqual(100, security.Holdings.Quantity);
            Assert.AreEqual(998, portfolio.Cash);
            Assert.AreEqual(100, portfolio.CashBook["EUR"].Amount);
            Assert.AreEqual(888, portfolio.CashBook["USD"].Amount);
        }
Example #33
0
        static bool ProcessInstruction(string[] args, ref int i)
        {
            for (; i < args.Length; i++)
            {
                switch (args [i])
                {
                case "-q":
                case "-quiet":
                    PolicyChangesConfirmation = false;
                    break;

                case "-f":
                case "-force":
                    forcePolicyChanges = true;
                    break;

                case "-?":
                case "/?":
                case "-h":
                case "-help":
                    Help();
                    break;

                case "-a":
                case "-all":
                    policyLevelDefault = false;
                    Levels.Clear();
                    Levels.Add(Enterprise);
                    Levels.Add(Machine);
                    Levels.Add(User);
                    break;

                case "-ca":
                case "-customall":
                    policyLevelDefault = false;
                    Levels.Clear();
                    Levels.Add(Enterprise);
                    Levels.Add(Machine);
                    Levels.Add(SecurityManager.LoadPolicyLevelFromFile(args [++i], PolicyLevelType.User));
                    break;

                case "-cu":
                case "-customuser":
                    policyLevelDefault = false;
                    Levels.Clear();
                    Levels.Add(SecurityManager.LoadPolicyLevelFromFile(args [++i], PolicyLevelType.User));
                    break;

                case "-en":
                case "-entreprise":
                    policyLevelDefault = false;
                    Levels.Clear();
                    Levels.Add(Enterprise);
                    break;

                case "-m":
                case "-machine":
                    policyLevelDefault = false;
                    Levels.Clear();
                    Levels.Add(Machine);
                    break;

                case "-u":
                case "-user":
                    policyLevelDefault = false;
                    Levels.Clear();
                    Levels.Add(User);
                    break;

                case "-lg":
                case "-listgroups":
                    ListCodeGroups();
                    break;

                case "-ld":
                case "-listdescription":
                    ListDescriptions();
                    break;

                case "-lp":
                case "-listpset":
                    ListPermissionSets();
                    break;

                case "-lf":
                case "-listfulltrust":
                    ListFullTrust();
                    break;

                case "-l":
                case "-list":
                    ListCodeGroups();
                    Console.WriteLine();
                    ListPermissionSets();
                    Console.WriteLine();
                    ListFullTrust();
                    break;

                case "-rsg":
                case "-resolvegroup":
                    if (!ResolveGroup(args [++i]))
                    {
                        return(false);
                    }
                    break;

                case "-rsp":
                case "-resolveperm":
                    if (!ResolvePermissions(args [++i]))
                    {
                        return(false);
                    }
                    break;

                case "-ap":
                case "-addpset":
                    if (!AddPermissionSet(args, ref i))
                    {
                        return(false);
                    }
                    break;

                case "-cp":
                case "-chgpset":
                    if (!ChangePermissionSet(args, ref i))
                    {
                        return(false);
                    }
                    break;

                case "-rp":
                case "-rempset":
                    if (!RemovePermissionSet(args [++i]))
                    {
                        return(false);
                    }
                    break;

                case "-af":
                case "-addfulltrust":
                    if (!AddFullTrust(args [++i]))
                    {
                        return(false);
                    }
                    break;

                case "-rf":
                case "-remfulltrust":
                    if (!RemoveFullTrust(args [++i]))
                    {
                        return(false);
                    }
                    break;

                case "-ag":
                case "-addgroup":
                    if (!AddCodeGroup(args, ref i))
                    {
                        return(false);
                    }
                    break;

                case "-cg":
                case "-chggroup":
                    if (!ChangeCodeGroup(args, ref i))
                    {
                        return(false);
                    }
                    break;

                case "-rg":
                case "-remgroup":
                    if (!RemoveCodeGroup(args [++i]))
                    {
                        return(false);
                    }
                    break;

                case "-r":
                case "-recover":
                    Recover();
                    break;

                case "-rs":
                case "-reset":
                    if (!Reset())
                    {
                        return(false);
                    }
                    break;

                case "-s":
                case "-security":
                    if (!Security(args [++i]))
                    {
                        return(false);
                    }
                    break;

                case "-e":
                case "-execution":
                    if (!Execution(args [++i]))
                    {
                        return(false);
                    }
                    break;

                case "-b":
                case "-buildcache":
                    if (!BuildCache())
                    {
                        return(false);
                    }
                    break;

                case "-pp":
                case "-polchgprompt":
                    if (!PolicyChangePrompt(args [++i]))
                    {
                        return(false);
                    }
                    break;

                default:
                    Console.WriteLine("*** unknown argument {0} ***", args [i]);
                    return(false);
                }
                Console.WriteLine();
            }
            return(true);
        }
Example #34
0
        public void FromXml(SecurityElement element)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }
            if (String.Compare(element.Tag, "ApplicationTrust", StringComparison.Ordinal) != 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML"));
            }

#if FEATURE_CLICKONCE
            m_appTrustedToRun = false;
            string isAppTrustedToRun = element.Attribute("TrustedToRun");
            if (isAppTrustedToRun != null && String.Compare(isAppTrustedToRun, "true", StringComparison.Ordinal) == 0)
            {
                m_appTrustedToRun = true;
            }

            m_persist = false;
            string persist = element.Attribute("Persist");
            if (persist != null && String.Compare(persist, "true", StringComparison.Ordinal) == 0)
            {
                m_persist = true;
            }

            m_appId = null;
            string fullName = element.Attribute("FullName");
            if (fullName != null && fullName.Length > 0)
            {
                m_appId = new ApplicationIdentity(fullName);
            }
#endif // FEATURE_CLICKONCE

            m_psDefaultGrant       = null;
            m_grantSetSpecialFlags = 0;
            SecurityElement elDefaultGrant = element.SearchForChildByTag("DefaultGrant");
            if (elDefaultGrant != null)
            {
                SecurityElement elDefaultGrantPS = elDefaultGrant.SearchForChildByTag("PolicyStatement");
                if (elDefaultGrantPS != null)
                {
                    PolicyStatement ps = new PolicyStatement(null);
                    ps.FromXml(elDefaultGrantPS);
                    m_psDefaultGrant       = ps;
                    m_grantSetSpecialFlags = SecurityManager.GetSpecialFlags(ps.PermissionSet, null);
                }
            }

            List <StrongName> fullTrustAssemblies   = new List <StrongName>();
            SecurityElement   elFullTrustAssemblies = element.SearchForChildByTag("FullTrustAssemblies");
            if (elFullTrustAssemblies != null && elFullTrustAssemblies.InternalChildren != null)
            {
                IEnumerator enumerator = elFullTrustAssemblies.Children.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    StrongName fullTrustAssembly = new StrongName();
                    fullTrustAssembly.FromXml(enumerator.Current as SecurityElement);
                    fullTrustAssemblies.Add(fullTrustAssembly);
                }
            }

            m_fullTrustAssemblies = fullTrustAssemblies.AsReadOnly();

#if FEATURE_CLICKONCE
            m_elExtraInfo = element.SearchForChildByTag("ExtraInfo");
#endif // FEATURE_CLICKONCE
        }
Example #35
0
 public virtual Security CreateSecurity(Symbol symbol, IAlgorithm algorithm, MarketHoursDatabase marketHoursDatabase, SymbolPropertiesDatabase symbolPropertiesDatabase)
 {
     return(SecurityManager.CreateSecurity(algorithm.Portfolio, algorithm.SubscriptionManager, marketHoursDatabase, symbolPropertiesDatabase,
                                           SecurityInitializer, symbol, UniverseSettings.Resolution, UniverseSettings.FillForward, UniverseSettings.Leverage,
                                           UniverseSettings.ExtendedMarketHours, false, false, symbol.ID.SecurityType == SecurityType.Option));
 }
Example #36
0
        public void TestBasicFeaturesWithOptionsFutures()
        {
            var securities = new SecurityManager(TimeKeeper);
            var marketHoursDatabase = MarketHoursDatabase.FromDataFolder();

            securities.Add(
                Symbols.SPY,
                new Security(
                    SecurityExchangeHours,
                    CreateTradeBarDataConfig(SecurityType.Equity, Symbols.SPY),
                    new Cash(Currencies.USD, 0, 1m),
                    SymbolProperties.GetDefault(Currencies.USD),
                    ErrorCurrencyConverter.Instance
                )
            );
            securities[Symbols.SPY].SetMarketPrice(new TradeBar { Time = securities.UtcTime, Symbol = Symbols.SPY, Close = 195 });

            var option1 = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 192m, new DateTime(2016, 02, 16));
            securities.Add(
                option1,
                new Option(
                    SecurityExchangeHours,
                    CreateTradeBarDataConfig(SecurityType.Option, option1),
                    new Cash(Currencies.USD, 0, 1m),
                    new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
                    ErrorCurrencyConverter.Instance
                )
            );

            var option2 = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 193m, new DateTime(2016, 03, 19));
            securities.Add(
                option2,
                new Option(
                    SecurityExchangeHours,
                    CreateTradeBarDataConfig(SecurityType.Option, option2),
                    new Cash(Currencies.USD, 0, 1m),
                    new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
                    ErrorCurrencyConverter.Instance
                )
            );

            var future1= Symbol.CreateFuture("ES", Market.USA, new DateTime(2016, 02, 16));
            securities.Add(
                future1,
                new Future(
                    SecurityExchangeHours,
                    CreateTradeBarDataConfig(SecurityType.Future, future1),
                    new Cash(Currencies.USD, 0, 1m),
                    new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
                    ErrorCurrencyConverter.Instance
                )
            );

            var future2 = Symbol.CreateFuture("ES", Market.USA, new DateTime(2016, 02, 19));
            securities.Add(
                future2,
                new Future(
                    SecurityExchangeHours,
                    CreateTradeBarDataConfig(SecurityType.Future, future2),
                    new Cash(Currencies.USD, 0, 1m),
                    new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
                    ErrorCurrencyConverter.Instance
                )
            );

            var cal = new TradingCalendar(securities, marketHoursDatabase);

            var optionDays = cal.GetDaysByType(TradingDayType.OptionExpiration, new DateTime(2016, 02, 16), new DateTime(2016, 03, 19)).Count();
            Assert.AreEqual(2, optionDays);

            var futureDays = cal.GetDaysByType(TradingDayType.OptionExpiration, new DateTime(2016, 02, 16), new DateTime(2016, 03, 19)).Count();
            Assert.AreEqual(2, futureDays);

            var days = cal.GetTradingDays(new DateTime(2016, 02, 16), new DateTime(2016, 03, 19));

            var optionAndfutureDays = days.Where(x => x.FutureExpirations.Any() || x.OptionExpirations.Any()).Count();
            Assert.AreEqual(3, optionAndfutureDays);

            // why? because option1 and future1 expire in one day 2016-02-16. Lets have a look.
            var day = cal.GetTradingDay(new DateTime(2016, 02, 16));
            Assert.AreEqual(1, day.OptionExpirations.Count());
            Assert.AreEqual(1, day.FutureExpirations.Count());

            var businessDays = days.Where(x => x.BusinessDay).Count();
            Assert.AreEqual(24, businessDays);

            var weekends = days.Where(x => x.Weekend).Count();
            Assert.AreEqual(9, weekends);

            Assert.AreEqual(24 + 9, (new DateTime(2016, 03, 19) - new DateTime(2016, 02, 16)).TotalDays + 1 /*inclusive*/);
        }
Example #37
0
        public string GetToken(string UserName, string PassWrod)
        {
            var request = HttpContext.Current.Request;

            return(SecurityManager.GenerateToken(UserName, PassWrod, CommonManager.GetIP(request), request.UserAgent, Tools.ticks));
        }
Example #38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DateRules"/> helper class
 /// </summary>
 /// <param name="securities">The security manager</param>
 public DateRules(SecurityManager securities)
 {
     _securities = securities;
 }
Example #39
0
        public void cetakLaporan()
        {
            if ((int.Parse(dgHeaderBKK.SelectedCells[0].OwningRow.Cells["NPrint"].Value.ToString()) > 0) && (!SecurityManager.IsManager()))
            {
                if (!SecurityManager.AskPasswordManager())
                {
                    return;
                }
            }
            int i = 0;

            double total = 0, jumlah;
            string _Kepada, _NoBukti, _Tanggal, _Lampiran, _Kasir;
            Guid   _rowID = (Guid)dgHeaderBKK.SelectedCells[0].OwningRow.Cells["RowID"].Value;

            _Kepada   = dgHeaderBKK.SelectedCells[0].OwningRow.Cells["dari"].Value.ToString();
            _NoBukti  = dgHeaderBKK.SelectedCells[0].OwningRow.Cells["noBukti"].Value.ToString();
            _Lampiran = dgHeaderBKK.SelectedCells[0].OwningRow.Cells["Lampiran"].Value.ToString();
            _Tanggal  = String.Format("{0:dd-MMM-yyyy}", dgHeaderBKK.SelectedCells[0].OwningRow.Cells["tglBukti"].Value);
            _Kasir    = dgHeaderBKK.SelectedCells[0].OwningRow.Cells["Kasir"].Value.ToString();
            int rowNo = 0;
            int no    = 0;

            int ttlData = dtBKKDetail.Rows.Count;
            int hal     = 1;
            int ttlHal  = 0;
            int prevHal = hal;

            if (ttlData % 10 > 0)
            {
                ttlHal = (ttlData / 10) + 1;
            }
            else
            {
                ttlHal = ttlData / 10;
            }


            try
            {
                BuildString lap = new BuildString();

                //lap.Initialize();

                //lap.PageLLine(33);
                //lap.LeftMargin(1);
                //lap.FontCPI(12);
                //lap.LineSpacing("1/8");
                //lap.DoubleWidth(true);
                //lap.PROW(true, 1, "[BUKTI KAS KELUAR]");
                //lap.DoubleWidth(false);

                ////lap.FontCondensed(true);
                //lap.PROW(true, 1, lap.PrintTopLeftCorner() + lap.PrintHorizontalLine(46) + lap.PrintTTOp()
                //    + lap.PrintHorizontalLine(46) + lap.PrintTopRightCorner());
                //lap.PROW(true, 1, lap.PrintVerticalLine() + "Kepada  : ".PadRight(46) +
                //    lap.PrintVerticalLine() + ("Nomor   : " + _NoBukti).PadRight(46) + lap.PrintVerticalLine());
                //lap.PROW(true, 1, lap.PrintVerticalLine() + _Kepada.PadRight(46) + lap.PrintVerticalLine() + ("Tanggal : " +
                //    _Tanggal).PadRight(30) +( "Hal    : " + hal.ToString() +"/" + ttlHal.ToString()).PadRight(16) + lap.PrintVerticalLine());
                //lap.PROW(true, 1, lap.PrintTLeft() + lap.PrintHorizontalLine(46) + lap.PrintTBottom()
                //    + lap.PrintHorizontalLine(46) + lap.PrintTRight());
                //lap.PROW(true, 1, lap.PrintVerticalLine() + "No. Prk".PadRight(10) + lap.PadCenter(70, "URAIAN") + lap.SPACE(15) + lap.PrintVerticalLine());
                //lap.PROW(true, 1, lap.PrintTLeft() + lap.PrintHorizontalLine(93) + lap.PrintTRight());

                bool cetak = true;

                foreach (DataRow dr in dtBKKDetail.Rows)
                {
                    #region header
                    if (cetak)
                    {
                        lap.Initialize();

                        lap.PageLLine(33);
                        lap.LeftMargin(1);
                        lap.FontCPI(12);
                        lap.LineSpacing("1/6");
                        lap.DoubleWidth(true);
                        lap.PROW(true, 1, "[BUKTI KAS KELUAR]");
                        lap.DoubleWidth(false);

                        //lap.FontCondensed(true);
                        lap.PROW(true, 1, lap.PrintTopLeftCorner() + lap.PrintHorizontalLine(41) + lap.PrintTTOp()
                                 + lap.PrintHorizontalLine(41) + lap.PrintTopRightCorner());
                        lap.PROW(true, 1, lap.PrintVerticalLine() + "Kepada  : ".PadRight(41) +
                                 lap.PrintVerticalLine() + ("Nomor   : " + _NoBukti).PadRight(41) + lap.PrintVerticalLine());
                        lap.PROW(true, 1, lap.PrintVerticalLine() + _Kepada.PadRight(41) + lap.PrintVerticalLine() + ("Tanggal : " +
                                                                                                                      _Tanggal).PadRight(30) + ("Hal : " + hal.ToString() + "/" + ttlHal.ToString()).PadRight(11) + lap.PrintVerticalLine());
                        lap.PROW(true, 1, lap.PrintTLeft() + lap.PrintHorizontalLine(41) + lap.PrintTBottom()
                                 + lap.PrintHorizontalLine(41) + lap.PrintTRight());
                        lap.PROW(true, 1, lap.PrintVerticalLine() + "No. Prk".PadRight(10) + lap.PadCenter(58, "URAIAN") + lap.SPACE(15) + lap.PrintVerticalLine());
                        lap.PROW(true, 1, lap.PrintTLeft() + lap.PrintHorizontalLine(83) + lap.PrintTRight());
                    }

                    #endregion

                    jumlah = Convert.ToDouble(dr["Jumlah"].ToString());
                    lap.PROW(true, 1, lap.PrintVerticalLine() + "".PadRight(10) + dr["Uraian"].ToString().ToUpper().PadRight(58).Substring(0, 58) + jumlah.ToString("#,###").PadLeft(15) + lap.PrintVerticalLine());
                    total += Convert.ToDouble(dr["Jumlah"].ToString());
                    i++;

                    no++;
                    rowNo++;
                    cetak = false;

                    if (hal == ttlHal && 10 - no > 0 && rowNo == ttlData)
                    {
                        for (int j = 0; j < 10 - no; j++)
                        {
                            lap.PROW(true, 1, lap.PrintVerticalLine() + lap.SPACE(83) + lap.PrintVerticalLine());
                        }
                    }


                    #region footer
                    if (ttlData == rowNo || no == 10)
                    {
                        prevHal = hal;
                        hal++;
                        no    = 0;
                        cetak = true;

                        lap.PROW(true, 1, lap.PrintTLeft() + lap.PrintHorizontalLine(83) + lap.PrintTRight());
                        lap.PROW(true, 1, lap.PrintVerticalLine() + "Terbilang".PadRight(58) + "Jumlah Rp.".PadRight(10) +
                                 total.ToString("#,###").PadLeft(15) + lap.PrintVerticalLine());
                        lap.PROW(true, 1, lap.PrintTLeft() + lap.PrintHorizontalLine(83) + lap.PrintTRight());
                        lap.PROW(true, 1, lap.PrintVerticalLine() + ISA.Common.Tools.Terbilang(total).PadRight(83) + lap.PrintVerticalLine());
                        lap.PROW(true, 1, lap.PrintTLeft() + lap.PrintHorizontalLine(20) + lap.PrintTTOp() + lap.PrintHorizontalLine(20) + lap.PrintTTOp()
                                 + lap.PrintHorizontalLine(20) + lap.PrintTTOp() + lap.PrintHorizontalLine(20) + lap.PrintTRight());
                        lap.PROW(true, 1, lap.PrintVerticalLine() + lap.PadCenter(20, "Pembukuan") + lap.PrintVerticalLine() + lap.PadCenter(20, "Mengetahui")
                                 + lap.PrintVerticalLine() + lap.PadCenter(20, "Kasir") + lap.PrintVerticalLine() + lap.PadCenter(20, "Penerima") + lap.PrintVerticalLine());
                        lap.PROW(true, 1, lap.PrintVerticalLine() + lap.PadCenter(20, "") + lap.PrintVerticalLine() + lap.PadCenter(20, "")
                                 + lap.PrintVerticalLine() + lap.PadCenter(20, "") + lap.PrintVerticalLine() + lap.PadCenter(20, "") + lap.PrintVerticalLine());
                        lap.PROW(true, 1, lap.PrintVerticalLine() + lap.PadCenter(20, "") + lap.PrintVerticalLine() + lap.PadCenter(20, "")
                                 + lap.PrintVerticalLine() + lap.PadCenter(20, "") + lap.PrintVerticalLine() + lap.PadCenter(20, "") + lap.PrintVerticalLine());
                        lap.PROW(true, 1, lap.PrintVerticalLine() + lap.PadCenter(20, "") + lap.PrintVerticalLine() + lap.PadCenter(20, "")
                                 + lap.PrintVerticalLine() + lap.PadCenter(20, "") + lap.PrintVerticalLine() + lap.PadCenter(20, "") + lap.PrintVerticalLine());
                        lap.PROW(true, 1, lap.PrintVerticalLine() + "(" + lap.PadCenter(18, "") + ")" + lap.PrintVerticalLine() + "(" + lap.PadCenter(18, "")
                                 + ")" + lap.PrintVerticalLine() + "(" + lap.PadCenter(18, _Kasir.Trim()) + ")" + lap.PrintVerticalLine() + "(" + lap.PadCenter(18, _Kepada.Trim()) + ")" +
                                 lap.PrintVerticalLine());
                        lap.PROW(true, 1, lap.PrintBottomLeftCorner() + lap.PrintHorizontalLine(20) + lap.PrintTBottom() + lap.PrintHorizontalLine(20) + lap.PrintTBottom()
                                 + lap.PrintHorizontalLine(20) + lap.PrintTBottom() + lap.PrintHorizontalLine(20) + lap.PrintBottomRightCorner());
                        lap.PROW(true, 1, String.Format("{0:yyyyMMddhhmmss}", DateTime.Now) + " " + SecurityManager.UserName);
                        lap.Eject();
                    }

                    #endregion
                }

                using (Database db = new Database(GlobalVar.DBName))
                {
                    db.Commands.Add(db.CreateCommand("rsp_CetakBukti"));
                    db.Commands[0].Parameters.Add(new Parameter("@rowID", SqlDbType.UniqueIdentifier, _rowID));
                    db.Commands[0].ExecuteNonQuery();
                }
                HeaderRowRefresh(_rowID);

                lap.SendToPrinter("laporanPS.txt", lap.GenerateString());
                //lap.SendToFile("laporanPS.txt");
            }
            catch (Exception ex)
            {
                Error.LogError(ex);
            }
        }
Example #40
0
        // -rsp assemblyname
        // -resolveperm assemblyname
        static bool ResolvePermissions(string assemblyname)
        {
            Evidence ev = GetAssemblyEvidences(assemblyname);

            if (ev == null)
            {
                return(false);
            }

            PermissionSet ps = null;

            Console.WriteLine();
            if (policyLevelDefault)
            {
                // different "default" here
                IEnumerator e = SecurityManager.PolicyHierarchy();
                while (e.MoveNext())
                {
                    PolicyLevel pl = (PolicyLevel)e.Current;
                    Console.WriteLine("Resolving {0} level", pl.Label);
                    if (ps == null)
                    {
                        ps = pl.Resolve(ev).PermissionSet;
                    }
                    else
                    {
                        ps = ps.Intersect(pl.Resolve(ev).PermissionSet);
                    }
                }
            }
            else
            {
                // use the user specified levels
                foreach (PolicyLevel pl in Levels)
                {
                    Console.WriteLine("Resolving {0} level", pl.Label);
                    if (ps == null)
                    {
                        ps = pl.Resolve(ev).PermissionSet;
                    }
                    else
                    {
                        ps = ps.Intersect(pl.Resolve(ev).PermissionSet);
                    }
                }
            }
            if (ps == null)
            {
                return(false);
            }

            IEnumerator ee = ev.GetHostEnumerator();

            while (ee.MoveNext())
            {
                IIdentityPermissionFactory ipf = (ee.Current as IIdentityPermissionFactory);
                if (ipf != null)
                {
                    IPermission p = ipf.CreateIdentityPermission(ev);
                    ps.AddPermission(p);
                }
            }

            Console.WriteLine("{0}Grant:{0}{1}", Environment.NewLine, ps.ToXml().ToString());
            return(true);
        }
Example #41
0
        public string GetToken(string UserName, string PassWrod, string ip)
        {
            var request = HttpContext.Current.Request;

            return(SecurityManager.GenerateToken(UserName, PassWrod, "", request.UserAgent, 1));
        }
Example #42
0
        internal FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool anonymous, FileOptions options)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            if (path.Length == 0)
            {
                throw new ArgumentException("Path is empty");
            }

            this.anonymous = anonymous;
            // ignore the Inheritable flag
            share &= ~FileShare.Inheritable;

            if (bufferSize <= 0)
            {
                throw new ArgumentOutOfRangeException("bufferSize", "Positive number required.");
            }

            if (mode < FileMode.CreateNew || mode > FileMode.Append)
            {
#if NET_2_1
                if (anonymous)
                {
                    throw new ArgumentException("mode", "Enum value was out of legal range.");
                }
                else
#endif
                throw new ArgumentOutOfRangeException("mode", "Enum value was out of legal range.");
            }

            if (access < FileAccess.Read || access > FileAccess.ReadWrite)
            {
#if NET_2_1
                if (anonymous)
                {
                    throw new IsolatedStorageException("Enum value for FileAccess was out of legal range.");
                }
                else
#endif
                throw new ArgumentOutOfRangeException("access", "Enum value was out of legal range.");
            }

            if (share < FileShare.None || share > (FileShare.ReadWrite | FileShare.Delete))
            {
#if NET_2_1
                if (anonymous)
                {
                    throw new IsolatedStorageException("Enum value for FileShare was out of legal range.");
                }
                else
#endif
                throw new ArgumentOutOfRangeException("share", "Enum value was out of legal range.");
            }

            if (path.IndexOfAny(Path.InvalidPathChars) != -1)
            {
                throw new ArgumentException("Name has invalid chars");
            }

            if (Directory.Exists(path))
            {
                // don't leak the path information for isolated storage
                string msg = Locale.GetText("Access to the path '{0}' is denied.");
                throw new UnauthorizedAccessException(String.Format(msg, GetSecureFileName(path, false)));
            }

            /* Append streams can't be read (see FileMode
             * docs)
             */
            if (mode == FileMode.Append &&
                (access & FileAccess.Read) == FileAccess.Read)
            {
                throw new ArgumentException("Append access can be requested only in write-only mode.");
            }

            if ((access & FileAccess.Write) == 0 &&
                (mode != FileMode.Open && mode != FileMode.OpenOrCreate))
            {
                string msg = Locale.GetText("Combining FileMode: {0} with " +
                                            "FileAccess: {1} is invalid.");
                throw new ArgumentException(string.Format(msg, access, mode));
            }

            SecurityManager.EnsureElevatedPermissions();              // this is a no-op outside moonlight

            string dname;
            if (Path.DirectorySeparatorChar != '/' && path.IndexOf('/') >= 0)
            {
                dname = Path.GetDirectoryName(Path.GetFullPath(path));
            }
            else
            {
                dname = Path.GetDirectoryName(path);
            }
            if (dname.Length > 0)
            {
                string fp = Path.GetFullPath(dname);
                if (!Directory.Exists(fp))
                {
                    // don't leak the path information for isolated storage
                    string msg   = Locale.GetText("Could not find a part of the path \"{0}\".");
                    string fname = (anonymous) ? dname : Path.GetFullPath(path);
#if NET_2_1
                    // don't use GetSecureFileName for the directory name
                    throw new IsolatedStorageException(String.Format(msg, fname));
#else
                    throw new DirectoryNotFoundException(String.Format(msg, fname));
#endif
                }
            }

            if (access == FileAccess.Read && mode != FileMode.Create && mode != FileMode.OpenOrCreate &&
                mode != FileMode.CreateNew && !File.Exists(path))
            {
                // don't leak the path information for isolated storage
                string msg   = Locale.GetText("Could not find file \"{0}\".");
                string fname = GetSecureFileName(path);
#if NET_2_1
                throw new IsolatedStorageException(String.Format(msg, fname));
#else
                throw new FileNotFoundException(String.Format(msg, fname), fname);
#endif
            }

            // IsolatedStorage needs to keep the Name property to the default "[Unknown]"
            if (!anonymous)
            {
                this.name = path;
            }

            // TODO: demand permissions

            MonoIOError error;

            this.handle = MonoIO.Open(path, mode, access, share, options, out error);
            if (handle == MonoIO.InvalidHandle)
            {
                // don't leak the path information for isolated storage
                throw MonoIO.GetException(GetSecureFileName(path), error);
            }

            this.access = access;
            this.owner  = true;

            /* Can we open non-files by name? */

            if (MonoIO.GetFileType(handle, out error) == MonoFileType.Disk)
            {
                this.canseek = true;
                this.async   = (options & FileOptions.Asynchronous) != 0;
            }
            else
            {
                this.canseek = false;
                this.async   = false;
            }


            if (access == FileAccess.Read && canseek && (bufferSize == DefaultBufferSize))
            {
                /* Avoid allocating a large buffer for small files */
                long len = Length;
                if (bufferSize > len)
                {
                    bufferSize = (int)(len < 1000 ? 1000 : len);
                }
            }

            InitBuffer(bufferSize, false);

            if (mode == FileMode.Append)
            {
                this.Seek(0, SeekOrigin.End);
                this.append_startpos = this.Position;
            }
            else
            {
                this.append_startpos = 0;
            }
        }
        public void ComputeMarginProperlyAsSecurityPriceFluctuates()
        {
            const decimal leverage = 1m;
            const int quantity = (int) (1000*leverage);
            var securities = new SecurityManager(TimeKeeper);
            var transactions = new SecurityTransactionManager(securities);
            var orderProcessor = new OrderProcessor();
            transactions.SetOrderProcessor(orderProcessor);
            var portfolio = new SecurityPortfolioManager(securities, transactions);
            portfolio.CashBook["USD"].SetAmount(quantity);

            var config = CreateTradeBarDataConfig(SecurityType.Equity, Symbols.AAPL);
            securities.Add(new Security(SecurityExchangeHours, config, new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency)));
            var security = securities[Symbols.AAPL];
            security.SetLeverage(leverage);

            var time = DateTime.Now;
            const decimal buyPrice = 1m;
            security.SetMarketPrice(new TradeBar(time, Symbols.AAPL, buyPrice, buyPrice, buyPrice, buyPrice, 1));

            var order = new MarketOrder(Symbols.AAPL, quantity, time) {Price = buyPrice};
            var fill = new OrderEvent(order, DateTime.UtcNow, 0) { FillPrice = buyPrice, FillQuantity = quantity };
            orderProcessor.AddOrder(order);
            var request = new SubmitOrderRequest(OrderType.Market, security.Type, security.Symbol, order.Quantity, 0, 0, order.Time, null);
            request.SetOrderId(0);
            orderProcessor.AddTicket(new OrderTicket(null, request));
            Assert.AreEqual(portfolio.CashBook["USD"].Amount, fill.FillPrice*fill.FillQuantity);

            portfolio.ProcessFill(fill);

            Assert.AreEqual(0, portfolio.MarginRemaining);
            Assert.AreEqual(quantity, portfolio.TotalMarginUsed);
            Assert.AreEqual(quantity, portfolio.TotalPortfolioValue);

            // we shouldn't be able to place a trader
            var newOrder = new MarketOrder(Symbols.AAPL, 1, time.AddSeconds(1)) {Price = buyPrice};
            bool sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, newOrder);
            Assert.IsFalse(sufficientCapital);

            // now the stock doubles, so we should have margin remaining

            time = time.AddDays(1);
            const decimal highPrice = buyPrice * 2;
            security.SetMarketPrice(new TradeBar(time, Symbols.AAPL, highPrice, highPrice, highPrice, highPrice, 1));

            Assert.AreEqual(quantity, portfolio.MarginRemaining);
            Assert.AreEqual(quantity, portfolio.TotalMarginUsed);
            Assert.AreEqual(quantity * 2, portfolio.TotalPortfolioValue);

            // we shouldn't be able to place a trader
            var anotherOrder = new MarketOrder(Symbols.AAPL, 1, time.AddSeconds(1)) { Price = highPrice };
            sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, anotherOrder);
            Assert.IsTrue(sufficientCapital);

            // now the stock plummets, so we should have negative margin remaining

            time = time.AddDays(1);
            const decimal lowPrice = buyPrice/2;
            security.SetMarketPrice(new TradeBar(time, Symbols.AAPL, lowPrice, lowPrice, lowPrice, lowPrice, 1));

            Assert.AreEqual(-quantity/2m, portfolio.MarginRemaining);
            Assert.AreEqual(quantity, portfolio.TotalMarginUsed);
            Assert.AreEqual(quantity/2m, portfolio.TotalPortfolioValue);


            // this would not cause a margin call due to leverage = 1
            bool issueMarginCallWarning;
            var marginCallOrders = portfolio.ScanForMarginCall(out issueMarginCallWarning);
            Assert.AreEqual(0, marginCallOrders.Count);

            // now change the leverage and buy more and we'll get a margin call
            security.SetLeverage(leverage * 2);

            order = new MarketOrder(Symbols.AAPL, quantity, time) { Price = buyPrice };
            fill = new OrderEvent(order, DateTime.UtcNow, 0) { FillPrice = buyPrice, FillQuantity = quantity };

            portfolio.ProcessFill(fill);

            Assert.AreEqual(0, portfolio.TotalPortfolioValue);

            marginCallOrders = portfolio.ScanForMarginCall(out issueMarginCallWarning);
            Assert.AreNotEqual(0, marginCallOrders.Count);
            Assert.AreEqual(-security.Holdings.Quantity, marginCallOrders[0].Quantity); // we bought twice
            Assert.GreaterOrEqual(-portfolio.MarginRemaining, security.Price * marginCallOrders[0].Quantity);
        }
Example #44
0
 public EntityInfoController(SecurityManager securityManager,
                             IFilterService filterService)
 {
     _securityManager = securityManager;
     _filterService   = filterService;
 }
        public void SellingShortFromShortAddsToCash()
        {
            var securities = new SecurityManager(TimeKeeper);
            var transactions = new SecurityTransactionManager(securities);
            var portfolio = new SecurityPortfolioManager(securities, transactions);
            portfolio.SetCash(0);

            securities.Add(Symbols.AAPL, new Security(SecurityExchangeHours, CreateTradeBarDataConfig(SecurityType.Equity, Symbols.AAPL), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency)));
            securities[Symbols.AAPL].Holdings.SetHoldings(100, -100);

            var fill = new OrderEvent(1, Symbols.AAPL, DateTime.MinValue,  OrderStatus.Filled, OrderDirection.Sell,  100, -100, 0);
            Assert.AreEqual(-100, securities[Symbols.AAPL].Holdings.Quantity);
            portfolio.ProcessFill(fill);

            Assert.AreEqual(100 * 100, portfolio.Cash);
            Assert.AreEqual(-200, securities[Symbols.AAPL].Holdings.Quantity);
        }
Example #46
0
        protected virtual void ExpandTree(IYZDbProvider provider, IDbConnection cn, BPMConnection bpmcn, JArray items, int folderid, bool withfolder, bool withfile, bool expand, bool iconFromExt, bool checkpermision, SecurityModel securitymodel, bool listfilecheckpermision)
        {
            FolderCollection folders = DirectoryManager.GetFolders(provider, cn, folderid, null, null);

            if (withfolder)
            {
                foreach (Folder folder in folders)
                {
                    if (checkpermision && securitymodel == SecurityModel.RBAC && !SecurityManager.CheckPermision(bpmcn, folder.RSID, BPMPermision.Read))
                    {
                        continue;
                    }

                    JObject item = this.Serialize(folder, expand);
                    items.Add(item);

                    JArray children = new JArray();
                    item[YZJsonProperty.children] = children;
                    this.ExpandTree(provider, cn, bpmcn, children, folder.FolderID, withfolder, withfile, expand, iconFromExt, checkpermision, securitymodel, false);
                }
            }

            if (withfile)
            {
                if (checkpermision && listfilecheckpermision && securitymodel == SecurityModel.RBAC && !SecurityManager.CheckPermision(bpmcn, Folder.GetRSID(folderid), BPMPermision.Read))
                {
                }
                else
                {
                    FileCollection files = DirectoryManager.GetFiles(provider, cn, folderid, null, null, -1);
                    foreach (File file in files)
                    {
                        AttachmentInfo attachmentInfo = AttachmentManager.TryGetAttachmentInfo(provider, cn, file.FileID);
                        if (attachmentInfo == null)
                        {
                            continue;
                        }

                        JObject item = this.Serialize(file, attachmentInfo, iconFromExt);
                        items.Add(item);
                    }
                }
            }
        }
        public void EquitySellAppliesSettlementCorrectly()
        {
            var securityExchangeHours = SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours();
            var securities = new SecurityManager(TimeKeeper);
            var transactions = new SecurityTransactionManager(securities);
            var portfolio = new SecurityPortfolioManager(securities, transactions);
            portfolio.SetCash(1000);
            securities.Add(Symbols.AAPL, new QuantConnect.Securities.Equity.Equity(securityExchangeHours, CreateTradeBarDataConfig(SecurityType.Equity, Symbols.AAPL), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency)));
            var security = securities[Symbols.AAPL];
            security.SettlementModel = new DelayedSettlementModel(3, TimeSpan.FromHours(8));
            Assert.AreEqual(0, security.Holdings.Quantity);
            Assert.AreEqual(1000, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);

            // Buy on Monday
            var timeUtc = new DateTime(2015, 10, 26, 15, 30, 0);
            var orderFee = security.FeeModel.GetOrderFee(security,new MarketOrder(Symbols.AAPL, 10, timeUtc));
            var fill = new OrderEvent(1, Symbols.AAPL, timeUtc, OrderStatus.Filled, OrderDirection.Buy, 100, 10, orderFee);
            portfolio.ProcessFill(fill);
            Assert.AreEqual(10, security.Holdings.Quantity);
            Assert.AreEqual(-1, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);

            // Sell on Tuesday, cash unsettled
            timeUtc = timeUtc.AddDays(1);
            orderFee = security.FeeModel.GetOrderFee(security, new MarketOrder(Symbols.AAPL, 10, timeUtc));
            fill = new OrderEvent(2, Symbols.AAPL, timeUtc, OrderStatus.Filled, OrderDirection.Sell, 100, -10, orderFee);
            portfolio.ProcessFill(fill);
            Assert.AreEqual(0, security.Holdings.Quantity);
            Assert.AreEqual(-2, portfolio.Cash);
            Assert.AreEqual(1000, portfolio.UnsettledCash);

            // Thursday, still cash unsettled
            timeUtc = timeUtc.AddDays(2);
            portfolio.ScanForCashSettlement(timeUtc);
            Assert.AreEqual(-2, portfolio.Cash);
            Assert.AreEqual(1000, portfolio.UnsettledCash);

            // Friday at open, cash settled
            var marketOpen = securityExchangeHours.MarketHours[timeUtc.DayOfWeek].GetMarketOpen(TimeSpan.Zero, false);
            Assert.IsTrue(marketOpen.HasValue);
            timeUtc = timeUtc.AddDays(1).Date.Add(marketOpen.Value).ConvertToUtc(securityExchangeHours.TimeZone);
            portfolio.ScanForCashSettlement(timeUtc);
            Assert.AreEqual(998, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);
        }
Example #48
0
        public virtual object GetFolderObjects(HttpContext context)
        {
            YZRequest     request        = new YZRequest(context);
            int           parentFolderID = request.GetInt32("folderid");
            bool          checkpermision = request.GetBool("checkpermision", false);
            SecurityModel securitymodel  = request.GetEnum <SecurityModel>("securitymodel", SecurityModel.RBAC);
            string        ext            = request.GetString("ext", null);
            bool          withfolder     = request.GetBool("folder");
            bool          withfile       = request.GetBool("file");
            bool          userName       = request.GetBool("username", false);

            Folder        folder = new Folder();
            List <object> rv     = new List <object>();

            bool haspermision = true;

            using (BPMConnection bpmcn = new BPMConnection())
            {
                if (checkpermision && securitymodel == SecurityModel.RBAC)
                {
                    bpmcn.WebOpen();
                    haspermision = SecurityManager.CheckPermision(bpmcn, Folder.GetRSID(parentFolderID), BPMPermision.Read);
                }
            }

            using (IYZDbProvider provider = YZDbProviderManager.DefaultProvider)
            {
                using (IDbConnection cn = provider.OpenConnection())
                {
                    folder             = DirectoryManager.GetFolderByID(provider, cn, parentFolderID);
                    folder["children"] = rv;

                    if (haspermision)
                    {
                        if (withfile)
                        {
                            FileCollection files = DirectoryManager.GetFiles(provider, cn, parentFolderID, null, null, -1);
                            foreach (File file in files)
                            {
                                AttachmentInfo attachmentInfo = AttachmentManager.TryGetAttachmentInfo(provider, cn, file.FileID);
                                if (attachmentInfo == null)
                                {
                                    continue;
                                }

                                if (!String.IsNullOrEmpty(ext) && !NameCompare.EquName(attachmentInfo.Ext, ext))
                                {
                                    continue;
                                }

                                JObject jFile = JObject.FromObject(file);
                                rv.Add(jFile);

                                jFile["Name"]         = attachmentInfo.Name;
                                jFile["Size"]         = attachmentInfo.Size;
                                jFile["LastUpdate"]   = attachmentInfo.LastUpdate;
                                jFile["OwnerAccount"] = attachmentInfo.OwnerAccount;
                            }
                        }

                        if (withfolder)
                        {
                            rv.AddRange(DirectoryManager.GetFolders(provider, cn, parentFolderID, null, null));
                        }
                    }
                }
            }

            if (userName)
            {
                using (BPMConnection cn = new BPMConnection())
                {
                    cn.WebOpen();

                    foreach (object item in rv)
                    {
                        JObject jFile = item as JObject;
                        if (jFile != null)
                        {
                            User user = User.TryGetUser(cn, (string)jFile["OwnerAccount"]);
                            jFile["OwnerDisplayName"] = user != null ? user.ShortName : jFile["OwnerAccount"];
                        }
                    }
                }
            }

            return(folder);
        }
        public void ComputeMarginProperlyShortCoverZeroLong()
        {
            const decimal leverage = 2m;
            const int amount = 1000;
            const int quantity = (int)(amount * leverage);
            var securities = new SecurityManager(TimeKeeper);
            var transactions = new SecurityTransactionManager(securities);
            var orderProcessor = new OrderProcessor();
            transactions.SetOrderProcessor(orderProcessor);
            var portfolio = new SecurityPortfolioManager(securities, transactions);
            portfolio.CashBook["USD"].SetAmount(amount);

            var config = CreateTradeBarDataConfig(SecurityType.Equity, Symbols.AAPL);
            securities.Add(new Security(SecurityExchangeHours, config, new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency)));
            var security = securities[Symbols.AAPL];
            security.SetLeverage(leverage);

            var time = DateTime.Now;
            const decimal sellPrice = 1m;
            security.SetMarketPrice(new TradeBar(time, Symbols.AAPL, sellPrice, sellPrice, sellPrice, sellPrice, 1));

            var order = new MarketOrder(Symbols.AAPL, -quantity, time) { Price = sellPrice };
            var fill = new OrderEvent(order, DateTime.UtcNow, 0) { FillPrice = sellPrice, FillQuantity = -quantity };
            orderProcessor.AddOrder(order);
            var request = new SubmitOrderRequest(OrderType.Market, security.Type, security.Symbol, order.Quantity, 0, 0, order.Time, null);
            request.SetOrderId(0);
            orderProcessor.AddTicket(new OrderTicket(null, request));

            portfolio.ProcessFill(fill);

            // we shouldn't be able to place a new short order
            var newOrder = new MarketOrder(Symbols.AAPL, -1, time.AddSeconds(1)) { Price = sellPrice };
            var sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, newOrder);
            Assert.IsFalse(sufficientCapital);

            // we should be able to place cover to zero
            newOrder = new MarketOrder(Symbols.AAPL, quantity, time.AddSeconds(1)) { Price = sellPrice };
            sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, newOrder);
            Assert.IsTrue(sufficientCapital);

            // now the stock doubles, so we should have negative margin remaining
            time = time.AddDays(1);
            const decimal highPrice = sellPrice * 2;
            security.SetMarketPrice(new TradeBar(time, Symbols.AAPL, highPrice, highPrice, highPrice, highPrice, 1));

            // we still shouldn be able to place cover to zero
            newOrder = new MarketOrder(Symbols.AAPL, quantity, time.AddSeconds(1)) { Price = highPrice };
            sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, newOrder);
            Assert.IsTrue(sufficientCapital);

            // we shouldn't be able to place cover to long
            newOrder = new MarketOrder(Symbols.AAPL, quantity + 1, time.AddSeconds(1)) { Price = highPrice };
            sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, newOrder);
            Assert.IsFalse(sufficientCapital);
        }
 protected bool IsAuthorized(string dashboardDirectory, string dashboardName, ZOperationResult operationResult)
 {
     return(SecurityManager.IsAuthorized(ActivityHelper.DashboardActivity(Domain, dashboardDirectory, dashboardName), ZSecurityOperations.Execute, operationResult));
 }
Example #51
0
        /// <summary>
        /// Ensures that we have a data feed to conver this currency into the base currency.
        /// This will add a subscription at the lowest resolution if one is not found.
        /// </summary>
        /// <param name="securities">The security manager</param>
        /// <param name="subscriptions">The subscription manager used for searching and adding subscriptions</param>
        /// <param name="exchangeHoursProvider">A security exchange hours provider instance used to resolve exchange hours for new subscriptions</param>
        public void EnsureCurrencyDataFeed(SecurityManager securities, SubscriptionManager subscriptions, SecurityExchangeHoursProvider exchangeHoursProvider)
        {
            if (Symbol == CashBook.AccountCurrency)
            {
                SecuritySymbol = string.Empty;
                _isBaseCurrency = true;
                ConversionRate = 1.0m;
                return;
            }

            if (subscriptions.Count == 0)
            {
                throw new InvalidOperationException("Unable to add cash when no subscriptions are present. Please add subscriptions in the Initialize() method.");
            }

            // we require a subscription that converts this into the base currency
            string normal = Symbol + CashBook.AccountCurrency;
            string invert = CashBook.AccountCurrency + Symbol;
            foreach (var config in subscriptions.Subscriptions.Where(config => config.SecurityType == SecurityType.Forex))
            {
                if (config.Symbol == normal)
                {
                    SecuritySymbol = config.Symbol;
                    return;
                }
                if (config.Symbol == invert)
                {
                    SecuritySymbol = config.Symbol;
                    _invertRealTimePrice = true;
                    return;
                }
            }

            // get the market from the first Forex subscription
            string market = (from config in subscriptions.Subscriptions
                             where config.SecurityType == SecurityType.Forex
                             select config.Market).FirstOrDefault() ?? "fxcm";

            // if we've made it here we didn't find a subscription, so we'll need to add one
            var currencyPairs = Forex.Forex.CurrencyPairs;
            var minimumResolution = subscriptions.Subscriptions.Min(x => x.Resolution);
            var objectType = minimumResolution == Resolution.Tick ? typeof (Tick) : typeof (TradeBar);
            foreach (var symbol in currencyPairs)
            {
                if (symbol == normal || symbol == invert)
                {
                    _invertRealTimePrice = symbol == invert;
                    var exchangeHours = exchangeHoursProvider.GetExchangeHours(market, symbol, SecurityType.Forex);
                    // set this as an internal feed so that the data doesn't get sent into the algorithm's OnData events
                    var config = subscriptions.Add(objectType, SecurityType.Forex, symbol, minimumResolution, market, exchangeHours.TimeZone, true, false, true);
                    var security = new Forex.Forex(this, config, 1m);
                    SecuritySymbol = config.Symbol;
                    securities.Add(symbol, security);
                    Log.Trace("Cash.EnsureCurrencyDataFeed(): Adding " + symbol + " for cash " + Symbol + " currency feed");
                    return;
                }
            }

            // if this still hasn't been set then it's an error condition
            throw new ArgumentException(string.Format("In order to maintain cash in {0} you are required to add a subscription for Forex pair {0}{1} or {1}{0}", Symbol, CashBook.AccountCurrency));
        }
Example #52
0
        public virtual void Configure(IApplicationBuilder app
                                      , IApplicationLifetime applicationLifetime
                                      , IHostingEnvironment env
                                      , IOptions <StartupOptions> startupOptions
                                      , ILogger <Startup> logger
                                      , LifetimeManager lifetimeManager
                                      , InterpreterManager interpreterManager
                                      , SecurityManager securityManager)
        {
            _logger = logger;
            var    serverAddresses = app.ServerFeatures.Get <IServerAddressesFeature>();
            string pipeName        = startupOptions.Value.WriteServerUrlsToPipe;

            if (pipeName != null)
            {
                NamedPipeClientStream pipe;
                try {
                    pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.Out);
                    pipe.Connect(10000);
                } catch (IOException ex) {
                    logger.LogCritical(0, ex, Resources.Critical_InvalidPipeHandle, pipeName);
                    throw;
                } catch (TimeoutException ex) {
                    logger.LogCritical(0, ex, Resources.Critical_PipeConnectTimeOut, pipeName);
                    throw;
                }

                applicationLifetime.ApplicationStarted.Register(() => Task.Run(() => {
                    using (pipe) {
                        string serverUriStr = JsonConvert.SerializeObject(serverAddresses.Addresses);
                        logger.LogTrace(Resources.Trace_ServerUrlsToPipeBegin, pipeName, Environment.NewLine, serverUriStr);

                        var serverUriData = Encoding.UTF8.GetBytes(serverUriStr);
                        pipe.Write(serverUriData, 0, serverUriData.Length);
                        pipe.Flush();
                    }

                    logger.LogTrace(Resources.Trace_ServerUrlsToPipeDone, pipeName);
                }));
            }

            lifetimeManager.Initialize();
            interpreterManager.Initialize();

            app.UseWebSockets(new WebSocketOptions {
                ReplaceFeature    = true,
                KeepAliveInterval = TimeSpan.FromMilliseconds(1000000000),
                ReceiveBufferSize = 0x10000
            });

            var routeBuilder = new RouteBuilder(app, new RouteHandler(RemoteUriHelper.HandlerAsync));

            routeBuilder.MapRoute("help_and_shiny", "remoteuri");
            app.UseRouter(routeBuilder.Build());

            app.UseBasicAuthentication(options => options.Events = new BasicEvents {
                OnSignIn = securityManager.SignInAsync
            });

            app.Use((context, next) => context.User.Identity.IsAuthenticated
                ? next()
                : context.Authentication.ChallengeAsync());

            app.UseMvc();

            if (!startupOptions.Value.IsService)
            {
                applicationLifetime.ApplicationStopping.Register(ExitAfterTimeout);
            }
        }
Example #53
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TimeRules"/> helper class
 /// </summary>
 /// <param name="securities">The security manager</param>
 /// <param name="timeZone">The algorithm's default time zone</param>
 public TimeRules(SecurityManager securities, DateTimeZone timeZone)
 {
     _securities = securities;
     _timeZone = timeZone;
 }
        public void SellOnThursdaySettleOnTuesday()
        {
            var securities   = new SecurityManager(TimeKeeper);
            var transactions = new SecurityTransactionManager(null, securities);
            var portfolio    = new SecurityPortfolioManager(securities, transactions);
            // settlement at T+3, 8:00 AM
            var model    = new DelayedSettlementModel(3, TimeSpan.FromHours(8));
            var config   = CreateTradeBarConfig(Symbols.SPY);
            var security = new Security(
                SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(),
                config,
                new Cash(CashBook.AccountCurrency, 0, 1m),
                SymbolProperties.GetDefault(CashBook.AccountCurrency),
                ErrorCurrencyConverter.Instance
                );

            portfolio.SetCash(3000);
            Assert.AreEqual(3000, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);

            // Sell on Thursday
            var timeUtc = Noon.AddDays(3).ConvertToUtc(TimeZones.NewYork);

            model.ApplyFunds(portfolio, security, timeUtc, "USD", 1000);
            portfolio.ScanForCashSettlement(timeUtc);
            Assert.AreEqual(3000, portfolio.Cash);
            Assert.AreEqual(1000, portfolio.UnsettledCash);

            // Friday, still unsettled
            timeUtc = timeUtc.AddDays(1);
            portfolio.ScanForCashSettlement(timeUtc);
            Assert.AreEqual(3000, portfolio.Cash);
            Assert.AreEqual(1000, portfolio.UnsettledCash);

            // Saturday, still unsettled
            timeUtc = timeUtc.AddDays(1);
            portfolio.ScanForCashSettlement(timeUtc);
            Assert.AreEqual(3000, portfolio.Cash);
            Assert.AreEqual(1000, portfolio.UnsettledCash);

            // Sunday, still unsettled
            timeUtc = timeUtc.AddDays(1);
            portfolio.ScanForCashSettlement(timeUtc);
            Assert.AreEqual(3000, portfolio.Cash);
            Assert.AreEqual(1000, portfolio.UnsettledCash);

            // Monday, still unsettled
            timeUtc = timeUtc.AddDays(1);
            portfolio.ScanForCashSettlement(timeUtc);
            Assert.AreEqual(3000, portfolio.Cash);
            Assert.AreEqual(1000, portfolio.UnsettledCash);

            // Tuesday at 7:55 AM, still unsettled
            timeUtc = timeUtc.AddDays(1).AddHours(-4).AddMinutes(-5);
            portfolio.ScanForCashSettlement(timeUtc);
            Assert.AreEqual(3000, portfolio.Cash);
            Assert.AreEqual(1000, portfolio.UnsettledCash);

            // Tuesday at 8 AM, now settled
            timeUtc = timeUtc.AddMinutes(5);
            portfolio.ScanForCashSettlement(timeUtc);
            Assert.AreEqual(4000, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);
        }
Example #55
0
        public void EnsureCurrencyDataFeedsAddsSubscriptionAtMinimumResolution()
        {
            const int quantity = 100;
            const decimal conversionRate = 1 / 100m;
            const Resolution minimumResolution = Resolution.Second;
            var cash = new Cash("JPY", quantity, conversionRate);
            var cashBook = new CashBook();
            cashBook.Add("JPY", cash);

            var subscriptions = new SubscriptionManager(TimeKeeper);
            var securities = new SecurityManager(TimeKeeper);
            securities.Add(Symbols.SPY, new Security(SecurityExchangeHours, subscriptions.Add(Symbols.SPY, Resolution.Minute, TimeZone, TimeZone), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency)));
            securities.Add(Symbols.EURUSD, new Security(SecurityExchangeHours, subscriptions.Add(Symbols.EURUSD, minimumResolution, TimeZone, TimeZone), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency)));

            cash.EnsureCurrencyDataFeed(securities, subscriptions, MarketHoursDatabase.AlwaysOpen, SymbolPropertiesDatabase.FromDataFolder(), MarketMap, cashBook);
            Assert.AreEqual(minimumResolution, subscriptions.Subscriptions.Single(x => x.Symbol == Symbols.USDJPY).Resolution);
        }
 public FunctionController(SecurityManager securityManager)
 {
     _securityManager = securityManager;
 }
Example #57
0
        public void EnsureInternalCurrencyDataFeedsForNonUsdQuoteCurrencyGetAdded()
        {
            const int quantity = 100;
            const decimal conversionRate = 1 / 100m;
            var cashJPY = new Cash("JPY", quantity, conversionRate);
            var cashGBP = new Cash("GBP", quantity, conversionRate);
            var cashBook = new CashBook();
            cashBook.Add("JPY", cashJPY);
            cashBook.Add("GBP", cashGBP);

            var symbol = Symbol.Create("GBPJPY", SecurityType.Forex, Market.FXCM);

            var subscriptions = new SubscriptionManager(TimeKeeper);
            var securities = new SecurityManager(TimeKeeper);
            securities.Add(symbol, new Security(SecurityExchangeHours, subscriptions.Add(symbol, Resolution.Minute, TimeZone, TimeZone), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency)));

            cashJPY.EnsureCurrencyDataFeed(securities, subscriptions, MarketHoursDatabase.AlwaysOpen, SymbolPropertiesDatabase.FromDataFolder(), MarketMap, cashBook);
            var config1 = subscriptions.Subscriptions.Single(x => x.Symbol == Symbols.USDJPY);
            Assert.IsTrue(config1.IsInternalFeed);

            cashGBP.EnsureCurrencyDataFeed(securities, subscriptions, MarketHoursDatabase.AlwaysOpen, SymbolPropertiesDatabase.FromDataFolder(), MarketMap, cashBook);
            var config2 = subscriptions.Subscriptions.Single(x => x.Symbol == Symbols.GBPUSD);
            Assert.IsTrue(config2.IsInternalFeed);
        }
Example #58
0
        private void cmdSave_Click(object sender, System.EventArgs e)
        {
            DataTable tb = Config.GetMain();
            DataRow   r  = tb.Rows[0];

            r[Keys.KeyMainConnectionString]    = this.txtConStr.Text.Trim();
            r[Keys.KeyMainRedirectAll]         = this.txtRedirectAll.Text.Trim();
            r[Keys.KeyMainEnableAuthorization] = this.chkEnableAuth.Checked ? "1" : "0";
            r[Keys.KeyMainTimeZone]            = int.Parse(Request.Form[this.cmbTimeZone.UniqueID]);
            r[Keys.KeyMainExtension]           = this.txtExt.Text;
            r[Keys.KeyMainPageCache]           = int.Parse(this.txtPageCache.Text);
            r[Keys.KeyMainOnlineTimeOut]       = int.Parse(this.txtOnline.Text);
            r[Keys.KeyMainTitleSeparator]      = this.txtSeparator.Text;
            if (!Util.IsBlank(this.txtNewAdminPass.Text))
            {
                r[Keys.KeyMainAdminPassword] = SecurityManager.EncryptPassword(this.txtNewAdminPass.Text);
            }
            else
            {
                r[Keys.KeyMainAdminPassword] = this.txtAdminPass.Text;
            }
            if (!Util.IsBlank(this.txtNewManagerPass.Text))
            {
                r[Keys.KeyMainManagerPassword] = SecurityManager.EncryptPassword(this.txtNewManagerPass.Text);
            }
            else
            {
                r[Keys.KeyMainManagerPassword] = this.txtManagerPass.Text;
            }
            r[Keys.KeyMainLoginPage]   = this.txtLoginPath.Text.Trim();
            r[Keys.KeyMainImages]      = this.txtImg.Text.Trim();
            r[Keys.KeyMainCss]         = this.txtCss.Text.Trim();
            r[Keys.KeyMainScript]      = this.txtScript.Text.Trim();
            r[Keys.KeyMainFiles]       = this.txtFiles.Text.Trim();
            r[Keys.KeyMainLogError]    = this.chkLogError.Checked ? "1" : "0";
            r[Keys.KeyMainOff]         = this.chkOff.Checked ? "1" : "0";
            r[Keys.KeyMainLogRedirect] = this.chkLogRedirect.Checked ? "1" : "0";
            r[Keys.KeyMainLogDownload] = this.chkLogDownload.Checked ? "1" : "0";
            r[Keys.KeyMainSeoError]    = this.chkSeoError.Checked ? "1" : "0";
            r[Keys.KeyEncryptionKey]   = this.txtEncKey.Text;
            r[Keys.KeyEncryptionVI]    = this.txtEncVI.Text;
            r[Keys.KeyEncryptionLevel] = int.Parse(Request.Form[this.cmbEncLevel.UniqueID]);

            StringBuilder settings = new StringBuilder();

            foreach (string key in Request.Form.AllKeys)
            {
                if (key.StartsWith("custom_"))
                {
                    if (settings.Length > 0)
                    {
                        settings.Append("&");
                    }

                    settings.Append(key.Substring("custom_".Length));
                    settings.Append("=");
                    settings.Append(Request.Form[key]);
                }
            }
            r[Keys.KeyMainCustom] = settings.ToString();

            Config.WriteConfigTable("main.config", tb, "main");

            Response.Redirect(Path.Full);
        }
Example #59
0
        public void EnsureCurrencyDataFeedAddsSubscriptionThrowsWhenZeroSubscriptionsPresent()
        {
            const int quantity = 100;
            const decimal conversionRate = 1 / 100m;
            var cash = new Cash("JPY", quantity, conversionRate);
            var cashBook = new CashBook();
            cashBook.Add("JPY", cash);

            var securities = new SecurityManager(TimeKeeper);
            var subscriptions = new SubscriptionManager(TimeKeeper);
            cash.EnsureCurrencyDataFeed(securities, subscriptions, MarketHoursDatabase.AlwaysOpen, SymbolPropertiesDatabase.FromDataFolder(), MarketMap, cashBook);
        }
Example #60
0
        // Arguments: Codebase, flags, zone, uniqueid
        // If the flags indicate zone then a zone must be provided.
        // If the flags indicate a site then a uniqueid must be provided
        internal static int Main(string[] args)
        {
            if (args.Length != 1)
            {
                throw new ArgumentException();
            }

            int index = 0;

            string file = args[index++];

            if ((file.Length == 0) || (file[0] == '\0'))
            {
                throw new ArgumentException();
            }

            string hashString = null;

            byte[] hash = null;

            int r = file.LastIndexOf("#");

            if (r != -1 & r != (file.Length - 1))
            {
                hashString = file.Substring(r + 1);
                file       = file.Substring(0, r);
                hash       = DecodeHex(hashString);
            }


            // Find the URL of the executable. For now we assume the
            // form to be http://blah/... with forward slashes. This
            // need to be update.
            string URL;
            string ConfigurationFile = null;
            int    k = file.LastIndexOf('/');

            if (k == -1)
            {
                URL = file;
                ConfigurationFile = file;
            }
            else
            {
                URL = file.Substring(0, k + 1);
                if (k + 1 < file.Length)
                {
                    ConfigurationFile = file.Substring(k + 1);
                }
            }

            // Build up the configuration File name
            if (ConfigurationFile != null)
            {
                StringBuilder bld = new StringBuilder();
                bld.Append(ConfigurationFile);
                bld.Append(".config");
                ConfigurationFile = bld.ToString();
            }

            string   friendlyName     = GetSiteName(file);
            Evidence documentSecurity = null;

            documentSecurity = new Evidence();
            Zone zone = Zone.CreateFromUrl(file);

            if (zone.SecurityZone == SecurityZone.MyComputer)
            {
                throw new ArgumentException();
            }
            documentSecurity.AddHost(zone);
            if (file.Length < 7 || String.Compare(file.Substring(0, 7), "file://", true, CultureInfo.InvariantCulture) != 0)
            {
                documentSecurity.AddHost(System.Security.Policy.Site.CreateFromUrl(file));
            }
            else
            {
                throw new ArgumentException();
            }
            documentSecurity.AddHost(new Url(file));

            AppDomainSetup properties = new AppDomainSetup();
            PermissionSet  ps         = SecurityManager.ResolvePolicy(documentSecurity);

            if (FailRebinds(ps))
            {
                properties.DisallowBindingRedirects = true;
            }
            else
            {
                properties.DisallowBindingRedirects = false;
            }
            properties.ApplicationBase = URL;
            properties.PrivateBinPath  = "bin";
            if (ConfigurationFile != null)
            {
                properties.ConfigurationFile = ConfigurationFile;
            }

            AppDomain proxy = AppDomain.CreateDomain(friendlyName,
                                                     documentSecurity,
                                                     properties);

            if (proxy != null)
            {
                AssemblyName caller = Assembly.GetExecutingAssembly().GetName();
                AssemblyName remote = new AssemblyName();
                remote.Name = "IEExecRemote";
                remote.SetPublicKey(caller.GetPublicKey());
                remote.Version     = caller.Version;
                remote.CultureInfo = CultureInfo.InvariantCulture;
                proxy.SetData("APP_LAUNCH_URL", file);
                ObjectHandle handle = proxy.CreateInstance(remote.FullName, "IEHost.Execute.IEExecuteRemote");
                if (handle != null)
                {
                    IEExecuteRemote execproxy = (IEExecuteRemote)handle.Unwrap();
                    if (execproxy != null)
                    {
                        int    res = execproxy.ExecuteAsAssembly(file, documentSecurity, hash, AssemblyHashAlgorithm.SHA1);
                        Stream streamedexception = execproxy.Exception;
                        if (streamedexception != null)
                        {
                            BinaryFormatter formatter = new BinaryFormatter();
                            Exception       e         = (Exception)formatter.Deserialize(streamedexception);
                            throw e;
                        }
                        return(res);
                    }
                }
            }
            return(-1);
        }