Пример #1
0
        /// <summary>
        /// Gets the amount of buying power reserved to maintain the specified position
        /// </summary>
        /// <param name="model">The <see cref="IBuyingPowerModel"/></param>
        /// <param name="security">The security</param>
        /// <returns>The reserved buying power in account currency</returns>
        public static decimal GetReservedBuyingPowerForPosition(this IBuyingPowerModel model, Security security)
        {
            var context             = new ReservedBuyingPowerForPositionParameters(security);
            var reservedBuyingPower = model.GetReservedBuyingPowerForPosition(context);

            return(reservedBuyingPower.AbsoluteUsedBuyingPower);
        }
Пример #2
0
        /// <summary>
        /// Gets the amount of buying power reserved to maintain the specified position
        /// </summary>
        /// <param name="model">The <see cref="IBuyingPowerModel"/></param>
        /// <param name="security">The security</param>
        /// <returns>The reserved buying power in account currency</returns>
        public static decimal GetReservedBuyingPowerForPosition(this IBuyingPowerModel model, Security security)
        {
            var context             = new ReservedBuyingPowerForPositionContext(security);
            var reservedBuyingPower = model.GetReservedBuyingPowerForPosition(context);

            return(reservedBuyingPower.Value);
        }
Пример #3
0
 /// <summary>
 /// Temporary convenience constructor
 /// </summary>
 protected Security(SubscriptionDataConfig config,
                    Cash quoteCurrency,
                    SymbolProperties symbolProperties,
                    SecurityExchange exchange,
                    SecurityCache cache,
                    ISecurityPortfolioModel portfolioModel,
                    IFillModel fillModel,
                    IFeeModel feeModel,
                    ISlippageModel slippageModel,
                    ISettlementModel settlementModel,
                    IVolatilityModel volatilityModel,
                    IBuyingPowerModel buyingPowerModel,
                    ISecurityDataFilter dataFilter,
                    IPriceVariationModel priceVariationModel
                    )
     : this(config.Symbol,
            quoteCurrency,
            symbolProperties,
            exchange,
            cache,
            portfolioModel,
            fillModel,
            feeModel,
            slippageModel,
            settlementModel,
            volatilityModel,
            buyingPowerModel,
            dataFilter,
            priceVariationModel
            )
 {
     SubscriptionsBag.Add(config);
     UpdateSubscriptionProperties();
 }
Пример #4
0
        /// <summary>
        /// Check if there is sufficient buying power to execute this order.
        /// </summary>
        /// <param name="model">The <see cref="IBuyingPowerModel"/></param>
        /// <param name="portfolio">The algorithm's portfolio</param>
        /// <param name="security">The security to be traded</param>
        /// <param name="order">The order</param>
        /// <returns>Returns buying power information for an order</returns>
        public static HasSufficientBuyingPowerForOrderResult HasSufficientBuyingPowerForOrder(
            this IBuyingPowerModel model,
            SecurityPortfolioManager portfolio,
            Security security,
            Order order
            )
        {
            var parameters = new HasSufficientBuyingPowerForOrderParameters(portfolio, security, order);

            return(model.HasSufficientBuyingPowerForOrder(parameters));
        }
Пример #5
0
        /// <summary>
        /// Get the maximum market order quantity to obtain a position with a given value in account currency
        /// </summary>
        /// <param name="model">The <see cref="IBuyingPowerModel"/></param>
        /// <param name="portfolio">The algorithm's portfolio</param>
        /// <param name="security">The security to be traded</param>
        /// <param name="target">The target percent holdings</param>
        /// <returns>Returns the maximum allowed market order quantity and if zero, also the reason</returns>
        public static GetMaximumOrderQuantityForTargetValueResult GetMaximumOrderQuantityForTargetValue(
            this IBuyingPowerModel model,
            SecurityPortfolioManager portfolio,
            Security security,
            decimal target
            )
        {
            var parameters = new GetMaximumOrderQuantityForTargetValueParameters(portfolio, security, target);

            return(model.GetMaximumOrderQuantityForTargetValue(parameters));
        }
 /// <summary>
 /// Gets the total margin required to execute the specified order in units of the account currency including fees
 /// </summary>
 /// <param name="model">The buying power model</param>
 /// <param name="currencyConverter">The currency converter used for converting asset values into the algorithm's
 /// account currency. Common value is the portfolio's cashbook property: <see cref="SecurityPortfolioManager.CashBook"/></param>
 /// <param name="security">The security</param>
 /// <param name="order">The order being contemplated</param>
 /// <returns>The total margin in terms of the currency quoted in the order</returns>
 public static decimal GetInitialMarginRequiredForOrder(
     this IBuyingPowerModel model,
     ICurrencyConverter currencyConverter,
     Security security,
     Order order
     )
 {
     return(model.GetInitialMarginRequiredForOrder(new InitialMarginRequiredForOrderParameters(
                                                       currencyConverter, security, order
                                                       )));
 }
Пример #7
0
        /// <summary>
        /// Get the maximum market order quantity to obtain a position with a given value in account currency
        /// </summary>
        /// <param name="model">The <see cref="IBuyingPowerModel"/></param>
        /// <param name="portfolio">The algorithm's portfolio</param>
        /// <param name="security">The security to be traded</param>
        /// <param name="target">The target percent holdings</param>
        /// <param name="minimumOrderMarginPortfolioPercentage">Configurable minimum order margin portfolio percentage to ignore orders with unrealistic small sizes</param>
        /// <returns>Returns the maximum allowed market order quantity and if zero, also the reason</returns>
        public static GetMaximumOrderQuantityResult GetMaximumOrderQuantityForTargetBuyingPower(
            this IBuyingPowerModel model,
            SecurityPortfolioManager portfolio,
            Security security,
            decimal target,
            decimal minimumOrderMarginPortfolioPercentage
            )
        {
            var parameters = new GetMaximumOrderQuantityForTargetBuyingPowerParameters(portfolio, security, target, minimumOrderMarginPortfolioPercentage);

            return(model.GetMaximumOrderQuantityForTargetBuyingPower(parameters));
        }
Пример #8
0
        /// <summary>
        /// Helper method to determine if the requested quantity is above the algorithm minimum order margin portfolio percentage
        /// </summary>
        /// <param name="model">The buying power model</param>
        /// <param name="security">The security</param>
        /// <param name="quantity">The quantity of shares</param>
        /// <param name="portfolioManager">The algorithm's portfolio</param>
        /// <param name="minimumOrderMarginPortfolioPercentage">Minimum order margin portfolio percentage to ignore bad orders, orders with unrealistic small sizes</param>
        /// <remarks>If we are trading with negative margin remaining this method will return true always</remarks>
        /// <returns>True if this order quantity is above the minimum requested</returns>
        public static bool AboveMinimumOrderMarginPortfolioPercentage(this IBuyingPowerModel model, Security security,
                                                                      decimal quantity, SecurityPortfolioManager portfolioManager, decimal minimumOrderMarginPortfolioPercentage)
        {
            if (minimumOrderMarginPortfolioPercentage == 0)
            {
                return(true);
            }
            var absFinalOrderMargin = Math.Abs(model.GetInitialMarginRequirement(new InitialMarginParameters(
                                                                                     security, quantity)).Value);

            return(AboveMinimumOrderMarginPortfolioPercentage(portfolioManager, minimumOrderMarginPortfolioPercentage, absFinalOrderMargin));
        }
Пример #9
0
        /// <summary>
        /// Construct a new security vehicle based on the user options.
        /// </summary>
        protected Security(Symbol symbol,
                           Cash quoteCurrency,
                           SymbolProperties symbolProperties,
                           SecurityExchange exchange,
                           SecurityCache cache,
                           ISecurityPortfolioModel portfolioModel,
                           IFillModel fillModel,
                           IFeeModel feeModel,
                           ISlippageModel slippageModel,
                           ISettlementModel settlementModel,
                           IVolatilityModel volatilityModel,
                           IBuyingPowerModel buyingPowerModel,
                           ISecurityDataFilter dataFilter,
                           IPriceVariationModel priceVariationModel,
                           ICurrencyConverter currencyConverter,
                           IRegisteredSecurityDataTypesProvider registeredTypesProvider
                           )
        {
            if (symbolProperties == null)
            {
                throw new ArgumentNullException(nameof(symbolProperties), "Security requires a valid SymbolProperties instance.");
            }

            if (symbolProperties.QuoteCurrency != quoteCurrency.Symbol)
            {
                throw new ArgumentException("symbolProperties.QuoteCurrency must match the quoteCurrency.Symbol");
            }

            this._currencyConverter = currencyConverter;

            Symbol              = symbol;
            SubscriptionsBag    = new ConcurrentBag <SubscriptionDataConfig>();
            QuoteCurrency       = quoteCurrency;
            SymbolProperties    = symbolProperties;
            IsTradable          = true;
            Cache               = cache;
            Exchange            = exchange;
            DataFilter          = dataFilter;
            PriceVariationModel = priceVariationModel;
            PortfolioModel      = portfolioModel;
            BuyingPowerModel    = buyingPowerModel;
            FillModel           = fillModel;
            FeeModel            = feeModel;
            SlippageModel       = slippageModel;
            SettlementModel     = settlementModel;
            VolatilityModel     = volatilityModel;
            Holdings            = new SecurityHolding(this, currencyConverter);
            Data              = new DynamicSecurityData(registeredTypesProvider);
            Cache.DataStored += (sender, args) => Data.StoreData(args.DataType, args.Data);

            UpdateSubscriptionProperties();
        }
Пример #10
0
        /// <summary>
        /// Gets the buying power available for a trade
        /// </summary>
        /// <param name="model">The <see cref="IBuyingPowerModel"/></param>
        /// <param name="portfolio">The algorithm's portfolio</param>
        /// <param name="security">The security to be traded</param>
        /// <param name="direction">The direction of the trade</param>
        /// <returns>The buying power available for the trade</returns>
        public static decimal GetBuyingPower(
            this IBuyingPowerModel model,
            SecurityPortfolioManager portfolio,
            Security security,
            OrderDirection direction
            )
        {
            var context     = new BuyingPowerContext(portfolio, security, direction);
            var buyingPower = model.GetBuyingPower(context);

            // existing implementations assume certain non-account currency units, so return raw value
            return(buyingPower.Value);
        }
Пример #11
0
        /// <summary>
        /// Construct a new security vehicle based on the user options.
        /// </summary>
        protected Security(Symbol symbol,
                           Cash quoteCurrency,
                           SymbolProperties symbolProperties,
                           SecurityExchange exchange,
                           SecurityCache cache,
                           ISecurityPortfolioModel portfolioModel,
                           IFillModel fillModel,
                           IFeeModel feeModel,
                           ISlippageModel slippageModel,
                           ISettlementModel settlementModel,
                           IVolatilityModel volatilityModel,
                           IBuyingPowerModel buyingPowerModel,
                           ISecurityDataFilter dataFilter,
                           IPriceVariationModel priceVariationModel
                           )
        {
            if (symbolProperties == null)
            {
                throw new ArgumentNullException("symbolProperties", "Security requires a valid SymbolProperties instance.");
            }

            if (symbolProperties.QuoteCurrency != quoteCurrency.Symbol)
            {
                throw new ArgumentException("symbolProperties.QuoteCurrency must match the quoteCurrency.Symbol");
            }

            Symbol              = symbol;
            SubscriptionsBag    = new ConcurrentBag <SubscriptionDataConfig>();
            QuoteCurrency       = quoteCurrency;
            SymbolProperties    = symbolProperties;
            IsTradable          = true;
            Cache               = cache;
            Exchange            = exchange;
            DataFilter          = dataFilter;
            PriceVariationModel = priceVariationModel;
            PortfolioModel      = portfolioModel;
            BuyingPowerModel    = buyingPowerModel;
            FillModel           = fillModel;
            FeeModel            = feeModel;
            SlippageModel       = slippageModel;
            SettlementModel     = settlementModel;
            VolatilityModel     = volatilityModel;
            Holdings            = new SecurityHolding(this);

            UpdateSubscriptionProperties();
        }
Пример #12
0
 /// <summary>
 /// Creates instance of the Option class.
 /// </summary>
 /// <remarks>
 /// Allows for the forwarding of the security configuration to the
 /// base Security constructor
 /// </remarks>
 protected Option(Symbol symbol,
                  Cash quoteCurrency,
                  SymbolProperties symbolProperties,
                  SecurityExchange exchange,
                  SecurityCache cache,
                  ISecurityPortfolioModel portfolioModel,
                  IFillModel fillModel,
                  IFeeModel feeModel,
                  ISlippageModel slippageModel,
                  ISettlementModel settlementModel,
                  IVolatilityModel volatilityModel,
                  IBuyingPowerModel buyingPowerModel,
                  ISecurityDataFilter dataFilter,
                  IPriceVariationModel priceVariationModel,
                  ICurrencyConverter currencyConverter,
                  IRegisteredSecurityDataTypesProvider registeredTypesProvider,
                  Security underlying
                  ) : base(
         symbol,
         quoteCurrency,
         symbolProperties,
         exchange,
         cache,
         portfolioModel,
         fillModel,
         feeModel,
         slippageModel,
         settlementModel,
         volatilityModel,
         buyingPowerModel,
         dataFilter,
         priceVariationModel,
         currencyConverter,
         registeredTypesProvider
         )
 {
     ExerciseSettlement = SettlementType.PhysicalDelivery;
     SetDataNormalizationMode(DataNormalizationMode.Raw);
     OptionExerciseModel = new DefaultExerciseModel();
     PriceModel          = new CurrentPriceOptionPriceModel();
     Holdings            = new OptionHolding(this, currencyConverter);
     _symbolProperties   = (OptionSymbolProperties)symbolProperties;
     SetFilter(-1, 1, TimeSpan.Zero, TimeSpan.FromDays(35));
     Underlying = underlying;
 }
        private static Security CreateSecurity(IBuyingPowerModel buyingPowerModel, DateTime newLocalTime)
        {
            var security = new Security(
                CreateUsEquitySecurityExchangeHours(),
                CreateTradeBarConfig(),
                new Cash(Currencies.USD, 0, 1m),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null,
                new SecurityCache()
                );

            TimeKeeper.SetUtcDateTime(newLocalTime.ConvertToUtc(security.Exchange.TimeZone));
            security.BuyingPowerModel = buyingPowerModel;
            security.Exchange.SetLocalDateTimeFrontier(newLocalTime);
            security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
            security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, newLocalTime, 100m));
            return(security);
        }
        public BuyingPowerModelComparator(
            IBuyingPowerModel securityModel,
            IPositionGroupBuyingPowerModel positionGroupModel,
            SecurityPortfolioManager portfolio = null,
            ITimeKeeper timeKeeper             = null,
            IOrderProcessor orderProcessor     = null
            )
        {
            Portfolio          = portfolio;
            SecurityModel      = securityModel;
            PositionGroupModel = positionGroupModel;

            if (portfolio == null)
            {
                var securities = new SecurityManager(timeKeeper ?? new TimeKeeper(DateTime.UtcNow));
                Portfolio = new SecurityPortfolioManager(securities, new SecurityTransactionManager(null, securities));
            }
            if (orderProcessor != null)
            {
                Portfolio.Transactions.SetOrderProcessor(orderProcessor);
            }
        }
Пример #15
0
 /// <summary>
 /// Sets the margin model
 /// </summary>
 /// <param name="marginModel">Model that represents a security's model of buying power</param>
 public void SetMarginModel(IBuyingPowerModel marginModel)
 {
     MarginModel = marginModel;
 }
Пример #16
0
 /// <summary>
 /// Sets the buying power model
 /// </summary>
 /// <param name="buyingPowerModel">Model that represents a security's model of buying power</param>
 public void SetBuyingPowerModel(IBuyingPowerModel buyingPowerModel)
 {
     BuyingPowerModel = buyingPowerModel;
 }
Пример #17
0
        public void Initialize()
        {
            _algorithm = new QCAlgorithm();
            _algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(_algorithm));
            _portfolio = _algorithm.Portfolio;
            _portfolio.CashBook.Add("EUR", 0, 1.20m);
            _portfolio.CashBook.Add("BTC", 0, 15000m);
            _portfolio.CashBook.Add("ETH", 0, 1000m);

            _algorithm.SetBrokerageModel(BrokerageName.GDAX, AccountType.Cash);

            _transactionHandler = new BacktestingTransactionHandler();
            _brokerage          = new BacktestingBrokerage(_algorithm);
            _resultHandler      = new TestResultHandler();
            _transactionHandler.Initialize(_algorithm, _brokerage, _resultHandler);

            _algorithm.Transactions.SetOrderProcessor(_transactionHandler);

            var tz = TimeZones.NewYork;

            _btcusd = new Crypto(
                SecurityExchangeHours.AlwaysOpen(tz),
                _portfolio.CashBook[Currencies.USD],
                new SubscriptionDataConfig(typeof(TradeBar), Symbols.BTCUSD, Resolution.Minute, tz, tz, true, false, false),
                new SymbolProperties("BTCUSD", Currencies.USD, 1, 0.01m, 0.00000001m, string.Empty),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
                );

            _ethusd = new Crypto(
                SecurityExchangeHours.AlwaysOpen(tz),
                _portfolio.CashBook[Currencies.USD],
                new SubscriptionDataConfig(typeof(TradeBar), Symbols.ETHUSD, Resolution.Minute, tz, tz, true, false, false),
                new SymbolProperties("ETHUSD", Currencies.USD, 1, 0.01m, 0.00000001m, string.Empty),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
                );

            _btceur = new Crypto(
                SecurityExchangeHours.AlwaysOpen(tz),
                _portfolio.CashBook["EUR"],
                new SubscriptionDataConfig(typeof(TradeBar), Symbols.BTCEUR, Resolution.Minute, tz, tz, true, false, false),
                new SymbolProperties("BTCEUR", "EUR", 1, 0.01m, 0.00000001m, string.Empty),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
                );

            _ethbtc = new Crypto(
                SecurityExchangeHours.AlwaysOpen(tz),
                _portfolio.CashBook["BTC"],
                new SubscriptionDataConfig(typeof(TradeBar), Symbols.ETHBTC, Resolution.Minute, tz, tz, true, false, false),
                new SymbolProperties("ETHBTC", "BTC", 1, 0.00001m, 0.00000001m, string.Empty),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
                );

            _globalTimeKeeper = new TimeKeeper(new DateTime(2019, 4, 22));
            _timeKeeper       = _globalTimeKeeper.GetLocalTimeKeeper(tz);
            _buyingPowerModel = new BuyingPowerModelComparator(
                new CashBuyingPowerModel(),
                new SecurityPositionGroupBuyingPowerModel(),
                _portfolio,
                _globalTimeKeeper
                );

            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _ethusd.SetLocalTimeKeeper(_timeKeeper);
            _btceur.SetLocalTimeKeeper(_timeKeeper);
            _ethbtc.SetLocalTimeKeeper(_timeKeeper);
        }
Пример #18
0
 /// <summary>
 /// Gets the margin currently allocated to the specified holding
 /// </summary>
 /// <param name="model">The buying power model</param>
 /// <param name="security">The security</param>
 /// <param name="quantity">The quantity of shares</param>
 /// <returns>The initial margin required for the provided security and quantity</returns>
 public static decimal GetInitialMarginRequirement(this IBuyingPowerModel model, Security security, decimal quantity)
 {
     return(model.GetInitialMarginRequirement(new InitialMarginParameters(security, quantity)));
 }
Пример #19
0
 /// <summary>
 /// Gets the margin currently allocated to the specified holding
 /// </summary>
 /// <param name="model">The buying power model</param>
 /// <param name="security">The security</param>
 /// <returns>The maintenance margin required for the provided holdings quantity/cost/value</returns>
 public static decimal GetMaintenanceMargin(this IBuyingPowerModel model, Security security)
 {
     return(model.GetMaintenanceMargin(MaintenanceMarginParameters.ForCurrentHoldings(security)));
 }