public BollingerBandsInRange(Equity equity, int periodCount, int sdCount)
     : base(equity, periodCount, sdCount)
 {
     _bbIndicator = new BollingerBands(equity, periodCount, sdCount);
 }
Exemple #2
0
 public Harami(Equity equity) : base(equity)
 {
 }
Exemple #3
0
 public InvertedHammer(Equity equity) : base(equity)
 {
 }
        public async Task <string[]> PrepareTweetsFromTranscriptAsync(Transcript trans, int include_highlight_count)
        {
            //Sentence Value Pairs
            TextValuePair[] SVPs = null;
            try
            {
                SVPs = trans.RankSentences();
            }
            catch (Exception e)
            {
                throw new Exception("Fatal error while ranking transcript sentences. Internal error message: " + e.Message);
            }

            List <string> ToTweet = new List <string>();

            #region "First Tweet (Intro)"

            string Tweet1Text = "Earnings Call Highlights"; //The value here should be replaced anyway.

            //Get company symbol
            if (trans.Title.Contains("(") && trans.Title.Contains(")"))
            {
                int    loc1   = trans.Title.LastIndexOf("(");
                int    loc2   = trans.Title.IndexOf(")", loc1 + 1);
                string symbol = trans.Title.Substring(loc1 + 1, loc2 - loc1 - 1);
                Equity eq     = Equity.Create(symbol);
                await eq.DownloadSummaryAsync();

                Tweet1Text = eq.Summary.Name + " $" + symbol.ToUpper().Trim() + " held an earnings call on " + trans.CallDateTimeStamp.ToShortDateString() + ". Here are the highlights:";
            }
            else
            {
                Tweet1Text = trans.Title.Replace(" Transcript", "") + " highlights: ";
            }

            ToTweet.Add(Tweet1Text);

            #endregion

            #region "Highlights"

            int t = 0;

            for (t = 0; t < include_highlight_count; t++)
            {
                if (SVPs.Length >= (t + 1))
                {
                    try
                    {
                        //Find the speaker
                        CallParticipant speaker = trans.WhoSaid(SVPs[t].Text);

                        //Get the sentence
                        string sen = SVPs[t].Text;

                        //write the tweet
                        string ThisTweet = speaker.Name + ": \"" + sen + "\"";

                        //Trim it down (if it goes past 280 characters)
                        if (ThisTweet.Length > 280)
                        {
                            ThisTweet = ThisTweet.Substring(0, 276);
                            ThisTweet = ThisTweet + "...\"";
                        }

                        //Add it
                        ToTweet.Add(ThisTweet);
                    }
                    catch
                    {
                    }
                }
            }

            #endregion


            return(ToTweet.ToArray());
        }
Exemple #5
0
 public UpsideTasukiGap(Equity equity) : base(equity)
 {
 }
Exemple #6
0
 public Doji(Equity equity) : base(equity)
 {
 }
        public async Task TradeEquityAsync(string symbol, int quantity, TransactionType order_type)
        {
            Equity e = Equity.Create(symbol);

            try
            {
                await e.DownloadSummaryAsync();
            }
            catch
            {
                throw new Exception("Critical error while fetching equity '" + symbol + "'.  Does this equity exist?");
            }


            if (order_type == TransactionType.Buy)
            {
                //Be sure we have enough cash to buy
                float cash_needed = e.Summary.Price * quantity;
                if (Cash < cash_needed)
                {
                    throw new Exception("You do not have enough cash to execute this buy order of " + symbol.ToUpper() + ".  Cash needed: $" + cash_needed.ToString("#,##0.00") + ".  Cash balance: $" + Cash.ToString("#,##0.00"));
                }


                AddSharesAndCalculateNewAverageCostBasis(symbol.ToUpper().Trim(), quantity, e.Summary.Price, DateTimeOffset.Now);

                //Edit cash and add the shares we are buying to the balane
                Cash = Cash - cash_needed;
            }
            else if (order_type == TransactionType.Sell)
            {
                //Find our holding
                EquityHolding eh = null;
                foreach (EquityHolding ceh in EquityHoldings)
                {
                    if (ceh.Symbol.ToUpper() == symbol.ToUpper())
                    {
                        eh = ceh;
                    }
                }

                //Throw an error if we do not have any of those shares.
                if (eh == null)
                {
                    throw new Exception("You do not have any shares of " + symbol.ToUpper() + " to sell.");
                }

                //Throw an error if we do not have enough shares
                if (eh.Quantity < quantity)
                {
                    throw new Exception("You do not have " + quantity.ToString() + " shares to sell!  You only have " + eh.Quantity.ToString() + " shares.");
                }

                //Execute the transaction
                Cash        = Cash + (quantity * e.Summary.Price);
                eh.Quantity = eh.Quantity - quantity;

                //Save the transaction log
                EquityTransaction et = new EquityTransaction();
                et.UpdateTransactionTime();
                et.StockSymbol     = symbol.ToUpper().Trim();
                et.OrderType       = TransactionType.Sell;
                et.Quantity        = quantity;
                et.PriceExecutedAt = e.Summary.Price;
                EquityTransactionLog.Add(et);

                //Remove the holding if it now 0
                if (eh.Quantity == 0)
                {
                    EquityHoldings.Remove(eh);
                }
            }

            //Take out the commission (if any)
            if (TradeCost > 0)
            {
                EditCash(TradeCost * -1, CashTransactionType.TradingRelatedCharge);
            }
        }
Exemple #8
0
 public FallingThreeMethods(Equity equity) : base(equity)
 {
 }
        public void GreekApproximationTest()
        {
            const decimal price           = 20.00m;
            const decimal underlyingPrice = 190m;
            const decimal underlyingVol   = 0.15m;
            var           tz             = TimeZones.NewYork;
            var           evaluationDate = new DateTime(2016, 1, 19);

            var equity = new Equity(
                SecurityExchangeHours.AlwaysOpen(tz),
                new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false),
                new Cash(CashBook.AccountCurrency, 0, 1m),
                SymbolProperties.GetDefault(CashBook.AccountCurrency),
                ErrorCurrencyConverter.Instance
                );

            equity.SetMarketPrice(new Tick {
                Value = underlyingPrice
            });
            equity.VolatilityModel = new DummyVolatilityModel(underlyingVol);

            var contract = new OptionContract(Symbols.SPY_P_192_Feb19_2016, Symbols.SPY)
            {
                Time = evaluationDate
            };
            var optionPut = new Option(
                SecurityExchangeHours.AlwaysOpen(tz),
                new SubscriptionDataConfig(
                    typeof(TradeBar),
                    Symbols.SPY_P_192_Feb19_2016,
                    Resolution.Minute,
                    tz,
                    tz,
                    true,
                    false,
                    false
                    ),
                new Cash(CashBook.AccountCurrency, 0, 1m),
                new OptionSymbolProperties(SymbolProperties.GetDefault(CashBook.AccountCurrency)),
                ErrorCurrencyConverter.Instance
                );

            optionPut.SetMarketPrice(new Tick {
                Value = price
            });
            optionPut.Underlying = equity;

            var priceModel = (QLOptionPriceModel)OptionPriceModels.CrankNicolsonFD();

            priceModel.EnableGreekApproximation = false;

            var results = priceModel.Evaluate(optionPut, null, contract);
            var greeks  = results.Greeks;

            Assert.AreEqual(greeks.Theta, 0);
            Assert.AreEqual(greeks.Rho, 0);
            Assert.AreEqual(greeks.Vega, 0);

            priceModel = (QLOptionPriceModel)OptionPriceModels.CrankNicolsonFD();
            priceModel.EnableGreekApproximation = true;

            results = priceModel.Evaluate(optionPut, null, contract);
            greeks  = results.Greeks;

            Assert.LessOrEqual(greeks.Theta, 0);
            Assert.AreNotEqual(greeks.Rho, 0);
            Assert.Greater(greeks.Vega, 0);
        }
        public void PutCallParityTest()
        {
            const decimal underlyingPrice = 200m;
            const decimal underlyingVol   = 0.15m;
            const decimal riskFreeRate    = 0.01m;
            var           tz                    = TimeZones.NewYork;
            var           evaluationDate        = new DateTime(2015, 2, 19);
            var           SPY_C_192_Feb19_2016E = Symbol.CreateOption("SPY", Market.USA, OptionStyle.European, OptionRight.Call, 192m, new DateTime(2016, 02, 19));
            var           SPY_P_192_Feb19_2016E = Symbol.CreateOption("SPY", Market.USA, OptionStyle.European, OptionRight.Put, 192m, new DateTime(2016, 02, 19));

            // setting up underlying
            var equity = new Equity(
                SecurityExchangeHours.AlwaysOpen(tz),
                new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false),
                new Cash(CashBook.AccountCurrency, 0, 1m),
                SymbolProperties.GetDefault(CashBook.AccountCurrency),
                ErrorCurrencyConverter.Instance
                );

            equity.SetMarketPrice(new Tick {
                Value = underlyingPrice
            });
            equity.VolatilityModel = new DummyVolatilityModel(underlyingVol);

            // setting up European style call option
            var contractCall = new OptionContract(SPY_C_192_Feb19_2016E, Symbols.SPY)
            {
                Time = evaluationDate
            };
            var optionCall = new Option(
                SecurityExchangeHours.AlwaysOpen(tz),
                new SubscriptionDataConfig(typeof(TradeBar), SPY_C_192_Feb19_2016E, Resolution.Minute, tz, tz, true, false, false),
                new Cash(CashBook.AccountCurrency, 0, 1m),
                new OptionSymbolProperties(SymbolProperties.GetDefault(CashBook.AccountCurrency)),
                ErrorCurrencyConverter.Instance
                );

            optionCall.Underlying = equity;

            // setting up European style put option
            var contractPut = new OptionContract(SPY_P_192_Feb19_2016E, Symbols.SPY)
            {
                Time = evaluationDate
            };
            var optionPut = new Option(
                SecurityExchangeHours.AlwaysOpen(tz),
                new SubscriptionDataConfig(typeof(TradeBar), SPY_P_192_Feb19_2016E, Resolution.Minute, tz, tz, true, false, false),
                new Cash(CashBook.AccountCurrency, 0, 1m),
                new OptionSymbolProperties(SymbolProperties.GetDefault(CashBook.AccountCurrency)),
                ErrorCurrencyConverter.Instance
                );

            optionPut.Underlying = equity;

            // running evaluation
            var priceModel  = OptionPriceModels.BlackScholes();
            var resultsCall = priceModel.Evaluate(optionCall, null, contractCall);
            var resultsPut  = priceModel.Evaluate(optionPut, null, contractPut);
            var callPrice   = resultsCall.TheoreticalPrice;
            var putPrice    = resultsPut.TheoreticalPrice;

            // Put-call parity equation
            var rightPart = putPrice + underlyingPrice; // no yield
            var leftPart  = callPrice + contractCall.Strike * (decimal)Math.Exp((double)-riskFreeRate);

            Assert.AreEqual((double)leftPart, (double)rightPart, 0.0001);
        }
        public void EvaluationDateWorksInPortfolioTest()
        {
            const decimal price           = 30.00m;
            const decimal underlyingPrice = 200m;
            const decimal underlyingVol   = 0.25m;
            const decimal riskFreeRate    = 0.01m;
            var           tz = TimeZones.NewYork;
            var           evaluationDate1 = new DateTime(2015, 2, 19);
            var           evaluationDate2 = new DateTime(2015, 2, 20);

            var equity = new Equity(
                SecurityExchangeHours.AlwaysOpen(tz),
                new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false),
                new Cash(CashBook.AccountCurrency, 0, 1m),
                SymbolProperties.GetDefault(CashBook.AccountCurrency),
                ErrorCurrencyConverter.Instance
                );

            equity.SetMarketPrice(new Tick {
                Value = underlyingPrice
            });
            equity.VolatilityModel = new DummyVolatilityModel(underlyingVol);

            var contract = new OptionContract(Symbols.SPY_C_192_Feb19_2016, Symbols.SPY)
            {
                Time = evaluationDate1
            };
            var optionCall = new Option(
                SecurityExchangeHours.AlwaysOpen(tz),
                new SubscriptionDataConfig(
                    typeof(TradeBar),
                    Symbols.SPY_C_192_Feb19_2016,
                    Resolution.Minute,
                    tz,
                    tz,
                    true,
                    false,
                    false
                    ),
                new Cash(CashBook.AccountCurrency, 0, 1m),
                new OptionSymbolProperties(SymbolProperties.GetDefault(CashBook.AccountCurrency)),
                ErrorCurrencyConverter.Instance
                );

            optionCall.SetMarketPrice(new Tick {
                Value = price
            });
            optionCall.Underlying = equity;

            var priceModel = OptionPriceModels.BaroneAdesiWhaley();
            var results    = priceModel.Evaluate(optionCall, null, contract);

            var callPrice1 = results.TheoreticalPrice;

            contract.Time = evaluationDate2;
            results       = priceModel.Evaluate(optionCall, null, contract);

            var callPrice2 = results.TheoreticalPrice;

            Assert.Greater(callPrice1, callPrice2);
        }
        public void BaroneAdesiWhaleyPortfolioTest()
        {
            const decimal price           = 30.00m;
            const decimal underlyingPrice = 200m;
            const decimal underlyingVol   = 0.25m;
            const decimal riskFreeRate    = 0.01m;
            var           tz             = TimeZones.NewYork;
            var           evaluationDate = new DateTime(2015, 2, 19);

            var equity = new Equity(
                SecurityExchangeHours.AlwaysOpen(tz),
                new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false),
                new Cash(CashBook.AccountCurrency, 0, 1m),
                SymbolProperties.GetDefault(CashBook.AccountCurrency),
                ErrorCurrencyConverter.Instance
                );

            equity.SetMarketPrice(new Tick {
                Value = underlyingPrice
            });
            equity.VolatilityModel = new DummyVolatilityModel(underlyingVol);

            var contract = new OptionContract(Symbols.SPY_C_192_Feb19_2016, Symbols.SPY)
            {
                Time = evaluationDate
            };
            var optionCall = new Option(
                SecurityExchangeHours.AlwaysOpen(tz),
                new SubscriptionDataConfig(
                    typeof(TradeBar),
                    Symbols.SPY_C_192_Feb19_2016,
                    Resolution.Minute,
                    tz,
                    tz,
                    true,
                    false,
                    false
                    ),
                new Cash(CashBook.AccountCurrency, 0, 1m),
                new OptionSymbolProperties(SymbolProperties.GetDefault(CashBook.AccountCurrency)),
                ErrorCurrencyConverter.Instance
                );

            optionCall.SetMarketPrice(new Tick {
                Value = price
            });
            optionCall.Underlying = equity;

            var priceModel = OptionPriceModels.BaroneAdesiWhaley();
            var results    = priceModel.Evaluate(optionCall, null, contract);

            var callPrice         = results.TheoreticalPrice;
            var impliedVolatility = results.ImpliedVolatility;
            var greeks            = results.Greeks;

            Assert.Greater(price, callPrice);
            Assert.Greater(impliedVolatility, underlyingVol);

            // BS equation (inequality)
            var rightPart = greeks.Theta + riskFreeRate * underlyingPrice * greeks.Delta + 0.5m * underlyingVol * underlyingVol * underlyingPrice * underlyingPrice * greeks.Gamma;
            var leftPart  = riskFreeRate * callPrice;

            Assert.GreaterOrEqual(Math.Round(leftPart, 4), Math.Round(rightPart, 4));
        }
Exemple #13
0
 public AccumulationDistributionLine(Equity equity) : base(equity)
 {
 }
Exemple #14
0
        /// <summary>
        /// Set a required SecurityType-symbol and resolution for algorithm
        /// </summary>
        /// <param name="securityType">SecurityType Enum: Equity, Commodity, FOREX or Future</param>
        /// <param name="symbol">Symbol Representation of the MarketType, e.g. AAPL</param>
        /// <param name="resolution">Resolution of the MarketType required: MarketData, Second or Minute</param>
        /// <param name="market">The market the requested security belongs to, such as 'usa' or 'fxcm'</param>
        /// <param name="fillDataForward">If true, returns the last available data even if none in that timeslice.</param>
        /// <param name="leverage">leverage for this security</param>
        /// <param name="extendedMarketHours">ExtendedMarketHours send in data from 4am - 8pm, not used for FOREX</param>
        public void AddSecurity(SecurityType securityType, string symbol, Resolution resolution, string market, bool fillDataForward, decimal leverage, bool extendedMarketHours)
        {
            try
            {
                if (_locked)
                {
                    throw new Exception("Algorithm.AddSecurity(): Cannot add another security after algorithm running.");
                }

                symbol = symbol.ToUpper();
                //If it hasn't been set, use some defaults based on the portfolio type:
                if (leverage <= 0)
                {
                    switch (securityType)
                    {
                    case SecurityType.Equity:
                        leverage = 2;     //Cash Ac. = 1, RegT Std = 2 or PDT = 4.
                        break;

                    case SecurityType.Forex:
                        leverage = 50;
                        break;
                    }
                }

                if (market == null)
                {
                    // set default values
                    if (securityType == SecurityType.Forex)
                    {
                        market = "fxcm";
                    }
                    else if (securityType == SecurityType.Equity)
                    {
                        market = "usa";
                    }
                    else
                    {
                        market = "usa";
                    }
                }

                //Add the symbol to Data Manager -- generate unified data streams for algorithm events
                var exchangeHours = _exchangeHoursProvider.GetExchangeHours(market, symbol, securityType);
                var config        = SubscriptionManager.Add(securityType, symbol, resolution, market, exchangeHours.TimeZone, fillDataForward, extendedMarketHours);

                Security security;
                switch (config.SecurityType)
                {
                case SecurityType.Equity:
                    security = new Equity(exchangeHours, config, leverage, false);
                    break;

                case SecurityType.Forex:
                    // decompose the symbol into each currency pair
                    string baseCurrency, quoteCurrency;
                    QuantConnect.Securities.Forex.Forex.DecomposeCurrencyPair(symbol, out baseCurrency, out quoteCurrency);

                    if (!Portfolio.CashBook.ContainsKey(baseCurrency))
                    {
                        // since we have none it's safe to say the conversion is zero
                        Portfolio.CashBook.Add(baseCurrency, 0, 0);
                    }
                    if (!Portfolio.CashBook.ContainsKey(quoteCurrency))
                    {
                        // since we have none it's safe to say the conversion is zero
                        Portfolio.CashBook.Add(quoteCurrency, 0, 0);
                    }
                    security = new Forex(exchangeHours, Portfolio.CashBook[quoteCurrency], config, leverage, false);
                    break;

                default:
                case SecurityType.Base:
                    security = new Security(exchangeHours, config, leverage, false);
                    break;
                }

                //Add the symbol to Securities Manager -- manage collection of portfolio entities for easy access.
                Securities.Add(config.Symbol, security);
            }
            catch (Exception err)
            {
                Error("Algorithm.AddSecurity(): " + err.Message);
            }
        }
 public async Task <IActionResult> Put(int id, [FromBody] Equity value)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// Saves an equity account to the data store.
 /// </summary>
 /// <param name="equity">The equity account to save.</param>
 public override void PersistEquity(Equity equity)
 {
     SaveAccount(equity);
 }
Exemple #17
0
        protected override IndicatorResult ComputeByIndexImpl(int index)
        {
            decimal?highestHigh = index >= PeriodCount - 1 ? Equity.Skip(index - PeriodCount + 1).Take(PeriodCount).Max(c => c.High) : (decimal?)null;

            return(new IndicatorResult(Equity[index].DateTime, highestHigh));
        }
 public RelativeStrengthIndex(Equity equity, int periodCount) : base(equity, periodCount)
 {
     _rsIndicator = new RelativeStrength(equity, periodCount);
 }
Exemple #19
0
 public HighestHigh(Equity equity, int periodCount) : base(equity, periodCount)
 {
 }
Exemple #20
0
 public SimpleMovingAverageTrend(Equity equity, int periodCount)
     : base(equity, periodCount)
 {
     _smaIndicator = new SimpleMovingAverage(equity, periodCount);
 }
 public ClosePriceChangeTrend(Equity equity) : base(equity)
 {
     _closePriceChangeIndicator = new ClosePriceChange(equity);
 }
Exemple #22
0
        public static Equity LookupEquity(FGAContext db, String Isin, CountryCode exchange)
        {
            Equity eq = db.Equities.Include("Identification").Where <Equity>(t => t.Identification.SecurityIdentification.ISINCode == Isin && t.Identification.DomesticIdentificationSource.Code2chars.Equals(exchange.Code2chars)).FirstOrDefault <Equity>();

            return(eq);
        }
 public ClosePricePercentageChange(Equity equity) : base(equity)
 {
 }
        public async Task <string> PrepareNewForm4TweetAsync(StatementOfBeneficialOwnership form4)
        {
            string ToReturn = null;

            foreach (NonDerivativeTransaction ndt in form4.NonDerivativeTransactions)
            {
                if (ndt.AcquiredOrDisposed == AcquiredDisposed.Acquired)                        //They acquired
                {
                    if (ndt.TransactionCode != null)                                            //It is indeed a transaction, not just a holding report
                    {
                        if (ndt.TransactionCode == TransactionType.OpenMarketOrPrivatePurchase) //Open market purchase
                        {
                            //Get the equity cost
                            Equity e = Equity.Create(form4.IssuerTradingSymbol);
                            await e.DownloadSummaryAsync();

                            //Get the name to use
                            string TraderNameToUse = form4.OwnerName;
                            try
                            {
                                TraderNameToUse = Aletheia.AletheiaToolkit.NormalizeAndRearrangeForm4Name(form4.OwnerName);
                            }
                            catch
                            {
                            }

                            //Start
                            ToReturn = "*INSIDER BUY ALERT*" + Environment.NewLine;
                            ToReturn = ToReturn + form4.OwnerName;

                            //Is there an officer title? If so, loop it in
                            if (form4.OwnerOfficerTitle != null && form4.OwnerOfficerTitle != "")
                            {
                                ToReturn = ToReturn + ", " + form4.OwnerOfficerTitle + ", ";
                            }
                            else
                            {
                                ToReturn = ToReturn + " ";
                            }

                            //Continue
                            ToReturn = ToReturn + "purchased " + ndt.TransactionQuantity.Value.ToString("#,##0") + " shares of $" + form4.IssuerTradingSymbol.Trim().ToUpper();

                            //Was a transaction price supplied?
                            if (ndt.TransactionPricePerSecurity.HasValue)
                            {
                                ToReturn = ToReturn + " at $" + ndt.TransactionPricePerSecurity.Value.ToString("#,##0.00");
                            }

                            //Add a period
                            ToReturn = ToReturn + "." + Environment.NewLine;

                            //How much they own following transaction
                            float worth = e.Summary.Price * ndt.SecuritiesOwnedFollowingTransaction;
                            ToReturn = ToReturn + form4.OwnerName + " now owns " + ndt.SecuritiesOwnedFollowingTransaction.ToString("#,##0") + " shares worth $" + worth.ToString("#,##0") + " of " + form4.IssuerName + " stock.";
                        }
                    }
                }
            }

            //Throw an error if ToReturn is still null (the above process did not satisfy anything)
            if (ToReturn == null)
            {
                throw new Exception("The Form 4 type is not supported for tweeting.");
            }

            return(ToReturn);
        }
Exemple #25
0
        public RebalanceModel GetRebalanceModel(List <AssetBase> allAssets, Domain.Portfolio.Rebalance.RebalanceModel savedModel, ClientGroup clientGroup = null, Client client = null)
        {
            var weightings       = allAssets.OfType <Equity>().Cast <AssetBase>().ToList().GetAssetWeightings();
            var totalMarketValue = allAssets.GetTotalMarketValue();

            List <TemplateDetailsItemParameter> parameters                 = new List <TemplateDetailsItemParameter>();
            List <DiversificationDatas>         diversificationDatas       = new List <DiversificationDatas>();
            List <RebalanceDataAnalysisModel>   rebalanceDataAnalysisModel = new List <RebalanceDataAnalysisModel>();
            BalanceSheetAgainstModel            balanceSeetAgainsModel     = new BalanceSheetAgainstModel()
            {
                data = new List <BalanceSheetAgainstModelData>()
            };
            RegionalComparisonModel regionalComparisonModel = new RegionalComparisonModel()
            {
                data = new List <RegionalComparisonData>()
            };
            SectorialComparisonModel sectorialComparisonModel = new SectorialComparisonModel()
            {
                data = new List <SectorialComparisonData>()
            };
            MonthlyCashflowComparison monthlyCashflowComparison = new MonthlyCashflowComparison()
            {
                data = new List <MonthlyCashflowComparisonData>()
            };
            List <TransactionCostData> transactionCostData = new List <TransactionCostData>();

            foreach (var parameter in savedModel.TemplateDetailsItemParameters)
            {
                //DiversificationDatas
                string[] metaKeys = parameter.identityMetaKey.Split('#');

                List <Equity> equitiesForGroup = new List <Equity>();
                if (metaKeys[0] == edisRepo.GetEnumDescription(RebalanceClassificationType.Sectors))
                {
                    equitiesForGroup = edisRepo.GetAllEquitiesBySectorName(metaKeys[1]);
                }
                else if (metaKeys[0] == edisRepo.GetEnumDescription(RebalanceClassificationType.Countries))
                {
                    equitiesForGroup = edisRepo.GetAllEquitiesByResearchStringValue(metaKeys[1]);
                }

                double currentWeighting = 0;
                if (metaKeys.Length == 2)
                {
                    currentWeighting = getCurrentWeightingForEquityGroup(equitiesForGroup, weightings);

                    //multiple equities
                }
                else
                {
                    currentWeighting = getCurrentWeightingForEquity(parameter.EquityId, weightings);

                    //RebalanceDataAnalysisModel
                    List <Equity> currentEquities = null;
                    if (clientGroup != null)
                    {
                        currentEquities = edisRepo.GetEquityForGroupAccountSync(parameter.EquityId, clientGroup);
                    }
                    else
                    {
                        currentEquities = edisRepo.GetEquityForClientAccountSync(parameter.EquityId, client);
                    }

                    int    numberOfUnit = 0;
                    double value        = 0;
                    double totalCost    = 0;
                    double rating       = 0;

                    foreach (var currentEquity in currentEquities)
                    {
                        numberOfUnit += (int)currentEquity.TotalNumberOfUnits;
                        value        += currentEquity.GetTotalMarketValue();
                        totalCost    += currentEquity.GetCost().Total;

                        switch (currentEquity.EquityType)
                        {
                        case EquityTypes.AustralianEquity:
                            rating += ((AustralianEquity)currentEquity).GetRating().TotalScore;
                            break;

                        case EquityTypes.InternationalEquity:
                            rating += ((InternationalEquity)currentEquity).GetRating().TotalScore;
                            break;
                        }
                    }

                    Equity selectedEquity = edisRepo.getEquityById(parameter.EquityId);

                    double reValue         = currentWeighting * parameter.CurrentWeighting == 0 ? (double)(totalMarketValue * parameter.CurrentWeighting) : (double)(value / currentWeighting * parameter.CurrentWeighting);//(totalMarketValue * parameter.CurrentWeighting) == null ? 0 : (double)(totalMarketValue * parameter.CurrentWeighting);
                    int    reUnit          = reValue == 0 ? 0 : (int)(reValue / selectedEquity.LatestPrice);
                    double reProfitAndLoss = reValue - totalCost;
                    double differences     = (reValue - value) / value;

                    var analysisGroup = rebalanceDataAnalysisModel.SingleOrDefault(a => a.groupName == metaKeys[1]);
                    if (analysisGroup == null)
                    {
                        analysisGroup = new RebalanceDataAnalysisModel {
                            groupName = metaKeys[1],
                            data      = new List <RebalanceDataAnalysisData>(),
                        };
                        rebalanceDataAnalysisModel.Add(analysisGroup);
                    }
                    var index = rebalanceDataAnalysisModel.IndexOf(analysisGroup);
                    rebalanceDataAnalysisModel[index].data.Add(new RebalanceDataAnalysisData {
                        ticker          = selectedEquity.Ticker,
                        name            = selectedEquity.Name,
                        currentPrice    = selectedEquity.LatestPrice,
                        currentExposure = new RebalanceDataAnalysisDataItem {
                            units         = numberOfUnit,
                            value         = value,
                            profitAndLoss = value - totalCost
                        },
                        rebalance = new RebalanceDataAnalysisDataItem {
                            value         = reValue,
                            units         = reUnit,
                            profitAndLoss = reProfitAndLoss
                        },
                        advantageousAndDisadvantageous = new RebalanceDataAnalysisAdvantageDisadvantage {
                            suitability = currentWeighting * rating,
                            differences = differences
                                          //differenceToTarget = ?,
                                          //target = ?
                        }
                    });


                    //BalanceSheetAgainstModel

                    var balanceSheet = balanceSeetAgainsModel.data.SingleOrDefault(a => a.groupName == metaKeys[1]);
                    if (balanceSheet == null)
                    {
                        balanceSheet = new BalanceSheetAgainstModelData {
                            groupName = metaKeys[1],
                            items     = new List <BalanceSheetAgainstModelItem>()
                        };
                        balanceSeetAgainsModel.data.Add(balanceSheet);
                    }
                    var balanSheetIndex = balanceSeetAgainsModel.data.IndexOf(balanceSheet);
                    balanceSeetAgainsModel.data[balanSheetIndex].items.Add(new BalanceSheetAgainstModelItem {
                        current           = value,
                        currentWeighting  = currentWeighting,
                        proposed          = reValue,
                        proposedWeighting = parameter.CurrentWeighting == null ? 0 : (double)parameter.CurrentWeighting,
                        difference        = differences,
                        itemName          = selectedEquity.Name
                    });


                    if (metaKeys[0] == edisRepo.GetEnumDescription(RebalanceClassificationType.Countries))
                    {
                        //RegionalComparisonModel
                        var regionModel = regionalComparisonModel.data.SingleOrDefault(a => a.groupName == metaKeys[1]);
                        if (regionModel == null)
                        {
                            regionModel = new RegionalComparisonData {
                                groupName = metaKeys[1],
                                items     = new List <RegionalComparisonItem>()
                            };
                            regionalComparisonModel.data.Add(regionModel);
                        }

                        var regionModelIndex = regionalComparisonModel.data.IndexOf(regionModel);
                        regionalComparisonModel.data[regionModelIndex].items.Add(new RegionalComparisonItem {
                            current           = value,
                            currentWeighting  = currentWeighting,
                            proposed          = reValue,
                            proposedWeighting = parameter.CurrentWeighting == null ? 0 : (double)parameter.CurrentWeighting,
                            difference        = differences,
                            itemName          = selectedEquity.Name
                        });
                    }
                    else if (metaKeys[0] == edisRepo.GetEnumDescription(RebalanceClassificationType.Sectors))
                    {
                        //SectoralComparisonModel
                        var sectorModel = sectorialComparisonModel.data.SingleOrDefault(a => a.groupName == metaKeys[1]);
                        if (sectorModel == null)
                        {
                            sectorModel = new SectorialComparisonData {
                                groupName = metaKeys[1],
                                items     = new List <SectorialComparisonItem>()
                            };
                            sectorialComparisonModel.data.Add(sectorModel);
                        }

                        var sectorModelIndex = sectorialComparisonModel.data.IndexOf(sectorModel);
                        sectorialComparisonModel.data[sectorModelIndex].items.Add(new SectorialComparisonItem {
                            current           = value,
                            currentWeighting  = currentWeighting,
                            proposed          = reValue,
                            proposedWeighting = parameter.CurrentWeighting == null ? 0 : (double)parameter.CurrentWeighting,
                            difference        = differences,
                            itemName          = selectedEquity.Name
                        });
                    }


                    //TransactionCostData
                    var transactionData = transactionCostData.SingleOrDefault(t => t.assetClass == metaKeys[1]);
                    if (transactionData == null)
                    {
                        transactionData = new TransactionCostData {
                            assetClass = metaKeys[1],
                            items      = new List <TransactionCostDataItem>()
                        };
                        transactionCostData.Add(transactionData);
                    }
                    var transactionIndex = transactionCostData.IndexOf(transactionData);
                    transactionCostData[transactionIndex].items.Add(new TransactionCostDataItem {
                        buySell    = reValue - value,
                        name       = selectedEquity.Name,
                        profitLoss = reProfitAndLoss,
                        //transactionCost = ?,
                        netValue = reValue - value //- transactionCost
                    });
                }

                var sameGroup = diversificationDatas.FirstOrDefault(d => d.group == metaKeys[1]);
                if (sameGroup != null)
                {
                    sameGroup.modelWeighting     += parameter.CurrentWeighting == null ? 0 : (double)parameter.CurrentWeighting;
                    sameGroup.portfolioWeighting += currentWeighting;
                }
                else
                {
                    diversificationDatas.Add(new DiversificationDatas {
                        group              = metaKeys[1],
                        modelWeighting     = parameter.CurrentWeighting == null ? 0 : (double)parameter.CurrentWeighting,
                        portfolioWeighting = currentWeighting
                    });
                }


                //TemplateDetailsItemParameter
                parameters.Add(new TemplateDetailsItemParameter {
                    id               = parameter.EquityId,
                    itemName         = parameter.ItemName,
                    identityMetaKey  = parameter.identityMetaKey,
                    currentWeighting = parameter.CurrentWeighting == null ? 0 : (double)parameter.CurrentWeighting,
                });
            }


            for (int i = 0; i < balanceSeetAgainsModel.data.Count; i++)
            {
                for (int j = 0; j < balanceSeetAgainsModel.data[i].items.Count; j++)
                {
                    balanceSeetAgainsModel.data[i].current           += balanceSeetAgainsModel.data[i].items[j].current;
                    balanceSeetAgainsModel.data[i].currentWeighting  += balanceSeetAgainsModel.data[i].items[j].currentWeighting;
                    balanceSeetAgainsModel.data[i].proposed          += balanceSeetAgainsModel.data[i].items[j].proposed;
                    balanceSeetAgainsModel.data[i].proposedWeighting += balanceSeetAgainsModel.data[i].items[j].proposedWeighting;
                }
                balanceSeetAgainsModel.data[i].difference = (balanceSeetAgainsModel.data[i].proposed - balanceSeetAgainsModel.data[i].current) / balanceSeetAgainsModel.data[i].current;

                balanceSeetAgainsModel.current           += balanceSeetAgainsModel.data[i].current;
                balanceSeetAgainsModel.currentWeighting  += balanceSeetAgainsModel.data[i].currentWeighting;
                balanceSeetAgainsModel.proposed          += balanceSeetAgainsModel.data[i].proposed;
                balanceSeetAgainsModel.proposedWeighting += balanceSeetAgainsModel.data[i].proposedWeighting;
            }
            balanceSeetAgainsModel.difference = (balanceSeetAgainsModel.proposed - balanceSeetAgainsModel.current) / balanceSeetAgainsModel.current;


            for (int i = 0; i < regionalComparisonModel.data.Count; i++)
            {
                for (int j = 0; j < regionalComparisonModel.data[i].items.Count; j++)
                {
                    regionalComparisonModel.data[i].current           += regionalComparisonModel.data[i].items[j].current;
                    regionalComparisonModel.data[i].currentWeighting  += regionalComparisonModel.data[i].items[j].currentWeighting;
                    regionalComparisonModel.data[i].proposed          += regionalComparisonModel.data[i].items[j].proposed;
                    regionalComparisonModel.data[i].proposedWeighting += regionalComparisonModel.data[i].items[j].proposedWeighting;
                }

                regionalComparisonModel.data[i].difference = (regionalComparisonModel.data[i].proposed - regionalComparisonModel.data[i].current) / regionalComparisonModel.data[i].current;

                regionalComparisonModel.current           += regionalComparisonModel.data[i].current;
                regionalComparisonModel.currentWeighting  += regionalComparisonModel.data[i].currentWeighting;
                regionalComparisonModel.proposed          += regionalComparisonModel.data[i].proposed;
                regionalComparisonModel.proposedWeighting += regionalComparisonModel.data[i].proposedWeighting;
            }


            for (int i = 0; i < sectorialComparisonModel.data.Count; i++)
            {
                for (int j = 0; j < sectorialComparisonModel.data[i].items.Count; j++)
                {
                    sectorialComparisonModel.data[i].current           += sectorialComparisonModel.data[i].items[j].current;
                    sectorialComparisonModel.data[i].currentWeighting  += sectorialComparisonModel.data[i].items[j].currentWeighting;
                    sectorialComparisonModel.data[i].proposed          += sectorialComparisonModel.data[i].items[j].proposed;
                    sectorialComparisonModel.data[i].proposedWeighting += sectorialComparisonModel.data[i].items[j].proposedWeighting;
                }

                sectorialComparisonModel.data[i].difference = (sectorialComparisonModel.data[i].proposed - sectorialComparisonModel.data[i].current) / sectorialComparisonModel.data[i].current;

                sectorialComparisonModel.current           += sectorialComparisonModel.data[i].current;
                sectorialComparisonModel.currentWeighting  += sectorialComparisonModel.data[i].currentWeighting;
                sectorialComparisonModel.proposed          += sectorialComparisonModel.data[i].proposed;
                sectorialComparisonModel.proposedWeighting += sectorialComparisonModel.data[i].proposedWeighting;
            }

            for (int i = 0; i < transactionCostData.Count; i++)
            {
                for (int j = 0; j < transactionCostData[i].items.Count; j++)
                {
                    transactionCostData[i].buySell         += transactionCostData[i].items[j].buySell;
                    transactionCostData[i].profitLoss      += transactionCostData[i].items[j].profitLoss;
                    transactionCostData[i].transactionCost += transactionCostData[i].items[j].transactionCost;
                    transactionCostData[i].netValue        += transactionCostData[i].items[j].netValue;
                    transactionCostData[i].extraDividend   += transactionCostData[i].items[j].extraDividend;
                    transactionCostData[i].extraMER        += transactionCostData[i].items[j].extraMER;
                }
                //transactionCostData[i].netValue += (transactionCostData[i].buySell + transactionCostData[i].transactionCost);
            }


            return(new RebalanceModel {
                modelId = savedModel.ModelId,
                profile = new ModelProfile {
                    profileId = savedModel.ProfileId.ToString(), profileName = edisRepo.GetEnumDescription((RebalanceModelProfile)savedModel.ProfileId)
                },
                modelName = savedModel.ModelName,
                itemParameters = parameters,
                diversificationData = diversificationDatas,
                rebalancedDataAnalysis = rebalanceDataAnalysisModel,
                balanceSheet = balanceSeetAgainsModel,
                sectorialData = sectorialComparisonModel,
                regionalData = regionalComparisonModel,
                transactionCost = transactionCostData
            });
        }
Exemple #26
0
        public void EnumerationWhileUpdatingDoesNotThrow()
        {
            var cts           = new CancellationTokenSource();
            var subscriptions = new SubscriptionCollection();
            var start         = DateTime.UtcNow;
            var end           = start.AddSeconds(10);
            var config        = new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, DateTimeZone.Utc, DateTimeZone.Utc, true, false, false);
            var security      = new Equity(
                Symbols.SPY,
                SecurityExchangeHours.AlwaysOpen(DateTimeZone.Utc),
                new Cash(Currencies.USD, 0, 1),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance
                );
            var timeZoneOffsetProvider     = new TimeZoneOffsetProvider(DateTimeZone.Utc, start, end);
            var enumerator                 = new EnqueueableEnumerator <BaseData>();
            var subscriptionDataEnumerator = SubscriptionData.Enumerator(config, security, timeZoneOffsetProvider, enumerator);
            var subscriptionRequest        = new SubscriptionRequest(false, null, security, config, start, end);
            var subscription               = new Subscription(subscriptionRequest, subscriptionDataEnumerator, timeZoneOffsetProvider);

            var addTask = new TaskFactory().StartNew(() =>
            {
                Console.WriteLine("Add task started");

                while (DateTime.UtcNow < end)
                {
                    if (!subscriptions.Contains(config))
                    {
                        subscriptions.TryAdd(subscription);
                    }

                    Thread.Sleep(1);
                }

                Console.WriteLine("Add task ended");
            }, cts.Token);

            var removeTask = new TaskFactory().StartNew(() =>
            {
                Console.WriteLine("Remove task started");

                while (DateTime.UtcNow < end)
                {
                    Subscription removed;
                    subscriptions.TryRemove(config, out removed);

                    Thread.Sleep(1);
                }

                Console.WriteLine("Remove task ended");
            }, cts.Token);

            var readTask = new TaskFactory().StartNew(() =>
            {
                Console.WriteLine("Read task started");

                while (DateTime.UtcNow < end)
                {
                    foreach (var sub in subscriptions)
                    {
                    }

                    Thread.Sleep(1);
                }

                Console.WriteLine("Read task ended");
            }, cts.Token);

            Task.WaitAll(addTask, removeTask, readTask);
        }
Exemple #27
0
 public MorningDojiStar(Equity equity) : base(equity)
 {
 }
Exemple #28
0
 public StandardDeviation(Equity equity, int periodCount) : base(equity, periodCount)
 {
 }
Exemple #29
0
 public ClosePriceChange(Equity equity) : base(equity)
 {
 }
Exemple #30
0
        /// <summary>
        /// Applies universe selection the the data feed and algorithm
        /// </summary>
        /// <param name="universe">The universe to perform selection on</param>
        /// <param name="dateTimeUtc">The current date time in utc</param>
        /// <param name="universeData">The data provided to perform selection with</param>
        public SecurityChanges ApplyUniverseSelection(Universe universe, DateTime dateTimeUtc, BaseDataCollection universeData)
        {
            var algorithmEndDateUtc = _algorithm.EndDate.ConvertToUtc(_algorithm.TimeZone);

            if (dateTimeUtc > algorithmEndDateUtc)
            {
                return(SecurityChanges.None);
            }

            IEnumerable <Symbol> selectSymbolsResult;

            // check if this universe must be filtered with fine fundamental data
            var fineFiltered = universe as FineFundamentalFilteredUniverse;

            if (fineFiltered != null)
            {
                // perform initial filtering and limit the result
                selectSymbolsResult = universe.SelectSymbols(dateTimeUtc, universeData);

                // prepare a BaseDataCollection of FineFundamental instances
                var fineCollection = new BaseDataCollection();
                var dataProvider   = new DefaultDataProvider();

                foreach (var symbol in selectSymbolsResult)
                {
                    var factory = new FineFundamentalSubscriptionEnumeratorFactory(_algorithm.LiveMode, x => new[] { dateTimeUtc });
                    var config  = FineFundamentalUniverse.CreateConfiguration(symbol);

                    var exchangeHours    = _marketHoursDatabase.GetEntry(symbol.ID.Market, symbol, symbol.ID.SecurityType).ExchangeHours;
                    var symbolProperties = _symbolPropertiesDatabase.GetSymbolProperties(symbol.ID.Market, symbol, symbol.ID.SecurityType, CashBook.AccountCurrency);
                    var quoteCash        = _algorithm.Portfolio.CashBook[symbolProperties.QuoteCurrency];

                    var security = new Equity(symbol, exchangeHours, quoteCash, symbolProperties);

                    var request = new SubscriptionRequest(true, universe, security, new SubscriptionDataConfig(config), dateTimeUtc, dateTimeUtc);
                    using (var enumerator = factory.CreateEnumerator(request, dataProvider))
                    {
                        if (enumerator.MoveNext())
                        {
                            fineCollection.Data.Add(enumerator.Current);
                        }
                    }
                }

                // perform the fine fundamental universe selection
                selectSymbolsResult = fineFiltered.FineFundamentalUniverse.PerformSelection(dateTimeUtc, fineCollection);
            }
            else
            {
                // perform initial filtering and limit the result
                selectSymbolsResult = universe.PerformSelection(dateTimeUtc, universeData);
            }

            // check for no changes first
            if (ReferenceEquals(selectSymbolsResult, Universe.Unchanged))
            {
                return(SecurityChanges.None);
            }

            // materialize the enumerable into a set for processing
            var selections = selectSymbolsResult.ToHashSet();

            var additions = new List <Security>();
            var removals  = new List <Security>();

            // remove previously deselected members which were kept in the universe because of holdings or open orders
            foreach (var member in _pendingRemovals.ToList())
            {
                var openOrders = _algorithm.Transactions.GetOrders(x => x.Status.IsOpen() && x.Symbol == member.Symbol);
                if (!member.HoldStock && !openOrders.Any())
                {
                    RemoveSecurityFromUniverse(universe, member, removals, dateTimeUtc, algorithmEndDateUtc);

                    _pendingRemovals.Remove(member);
                }
            }

            // determine which data subscriptions need to be removed from this universe
            foreach (var member in universe.Members.Values)
            {
                // if we've selected this subscription again, keep it
                if (selections.Contains(member.Symbol))
                {
                    continue;
                }

                // don't remove if the universe wants to keep him in
                if (!universe.CanRemoveMember(dateTimeUtc, member))
                {
                    continue;
                }

                // remove the member - this marks this member as not being
                // selected by the universe, but it may remain in the universe
                // until open orders are closed and the security is liquidated
                removals.Add(member);

                // but don't physically remove it from the algorithm if we hold stock or have open orders against it
                var openOrders = _algorithm.Transactions.GetOrders(x => x.Status.IsOpen() && x.Symbol == member.Symbol);
                if (!member.HoldStock && !openOrders.Any())
                {
                    RemoveSecurityFromUniverse(universe, member, removals, dateTimeUtc, algorithmEndDateUtc);
                }
                else
                {
                    _pendingRemovals.Add(member);
                }
            }

            var keys = _pendingSecurityAdditions.Keys;

            if (keys.Any() && keys.Single() != dateTimeUtc)
            {
                // if the frontier moved forward then we've added these securities to the algorithm
                _pendingSecurityAdditions.Clear();
            }

            Dictionary <Symbol, Security> pendingAdditions;

            if (!_pendingSecurityAdditions.TryGetValue(dateTimeUtc, out pendingAdditions))
            {
                // keep track of created securities so we don't create the same security twice, leads to bad things :)
                pendingAdditions = new Dictionary <Symbol, Security>();
                _pendingSecurityAdditions[dateTimeUtc] = pendingAdditions;
            }

            // find new selections and add them to the algorithm
            foreach (var symbol in selections)
            {
                // create the new security, the algorithm thread will add this at the appropriate time
                Security security;
                if (!pendingAdditions.TryGetValue(symbol, out security) && !_algorithm.Securities.TryGetValue(symbol, out security))
                {
                    security = universe.CreateSecurity(symbol, _algorithm, _marketHoursDatabase, _symbolPropertiesDatabase);
                    pendingAdditions.Add(symbol, security);
                }

                var addedSubscription = false;

                foreach (var request in universe.GetSubscriptionRequests(security, dateTimeUtc, algorithmEndDateUtc))
                {
                    // add the new subscriptions to the data feed
                    _dataFeed.AddSubscription(request);

                    // only update our security changes if we actually added data
                    if (!request.IsUniverseSubscription)
                    {
                        addedSubscription = true;
                    }
                }

                if (addedSubscription)
                {
                    var addedMember = universe.AddMember(dateTimeUtc, security);

                    if (addedMember)
                    {
                        additions.Add(security);
                    }
                }
            }

            // return None if there's no changes, otherwise return what we've modified
            var securityChanges = additions.Count + removals.Count != 0
                ? new SecurityChanges(additions, removals)
                : SecurityChanges.None;

            // Add currency data feeds that weren't explicitly added in Initialize
            if (additions.Count > 0)
            {
                var addedSecurities = _algorithm.Portfolio.CashBook.EnsureCurrencyDataFeeds(_algorithm.Securities, _algorithm.SubscriptionManager, _marketHoursDatabase, _symbolPropertiesDatabase, _algorithm.BrokerageModel.DefaultMarkets, securityChanges);
                foreach (var security in addedSecurities)
                {
                    // assume currency feeds are always one subscription per, these are typically quote subscriptions
                    _dataFeed.AddSubscription(new SubscriptionRequest(false, universe, security, new SubscriptionDataConfig(security.Subscriptions.First()), dateTimeUtc, algorithmEndDateUtc));
                }
            }

            if (securityChanges != SecurityChanges.None)
            {
                Log.Debug("UniverseSelection.ApplyUniverseSelection(): " + dateTimeUtc + ": " + securityChanges);
            }

            return(securityChanges);
        }
Exemple #31
0
 public LongLeggedDoji(Equity equity)
     : base(equity)
 {
 }
        public IList<Trade> Import(Market market, Feed feed, StringBuilder sb, FilterData filterData)
        {
            var trades = new List<Trade>();
            var infos = filterData.Data ?? TradeImportHelper.ReadData(FilterInfo, filterData, sb);
            var dict = new Dictionary<TradeInfo, Trade>();
            var symbols = new Dictionary<string, Product>();
            if (filterData.Progress != null) filterData.Progress.AnalysisInit(infos.Count, "Building Products");
            int count = 0;

            foreach (var info in infos)
            {
                count++;
                if (filterData.Progress != null) filterData.Progress.AnalysisProgress(count, "");
                if (filterData.Progress != null && filterData.Progress.IsCanceled) return new List<Trade>();
                if (FilterInfo(info)) continue;
                var trade = new Trade();
                if (!TradeImportHelper.InitTrade(trade, info, filterData, sb)) continue;
                dict[info] = trade;
                var symbol = info.Symbol;       // symbol is cusip/isin/sedol
                if (symbol != null) symbol = symbol.Trim();
                if (!string.IsNullOrEmpty(symbol))
                {
                    var p = Env.Current.Trade.GetProductByCode(Product.CusipProductCode, symbol) ??
                        Env.Current.Trade.GetProductByCode(Product.IsinProductCode, symbol) ??
                        Env.Current.Trade.GetProductByCode(Product.SedolProductCode, symbol);
                    if (p == null)
                    {
                        if (symbols.Count < MaxEqs)
                        {
                            symbols[symbol] = null;
                        }
                        else dict[info] = null; //Remove it
                    }
                    else info.Security = p;
                }
                else
                    sb.Append(TradeImportHelper.FormatErrorMessage("Symbol is null", info.HoldingID, info.TradeID, info.Instrument));
            }
            if (filterData.Progress != null && filterData.Progress.IsCanceled) return new List<Trade>();
            if (filterData.Progress != null) filterData.Progress.AnalysisDone();

            // snapping equities by cusip, isin or sedol
            var snapped = new List<Product>();
            var exceptions = new List<Exception>();
            if (symbols.Count > 0 && feed != null)
            {
                var prodcs = new List<Product>();
                foreach (var s in symbols.Keys)
                {
                    var eq = new Equity();
                    eq.SetProperty(Product.DefaultTicker, s);
                    prodcs.Add(eq);
                }
                sb.Append("Snapping Equities By Symbol " + symbols.Count + " " + Utilities.ToString(new List<string>(symbols.Keys)) + "\n");
                try
                {
                    FeedImportSecurityTaskExecutor.SnapProducts("Equity.FeedMapping.xml", prodcs, feed, exceptions, true, snapped);
                    // might need other equity type snapping
                }
                catch (Exception x)
                {
                    sb.Append(x.ToString());
                }
            }
            foreach (var p in snapped)
            {
                var isin = p.Isin;
                var cusip = p.Cusip;
                var sedol = p.Sedol;
                if (p.Id > 0)
                {
                    if (symbols.ContainsKey(cusip))
                        symbols[cusip] = p;
                    else if (symbols.ContainsKey(isin))
                        symbols[isin] = p;
                    else if (symbols.ContainsKey(sedol))
                        symbols[sedol] = p;
                }
            }
            if (snapped.Count > 0) sb.Append("Snapped " + snapped.Count + " equities by Symbol\n");
            var tempEquityProvider = new EquityTemplateProvider();

            if (filterData.Progress != null) filterData.Progress.AnalysisInit(dict.Count, "Initializing Trades");
            count = 0;
            foreach (var kvp in dict)
            {
                if (filterData.Progress != null && filterData.Progress.IsCanceled) return new List<Trade>();
                count++;
                if (filterData.Progress != null) filterData.Progress.AnalysisProgress(count, "");
                var info = kvp.Key;
                var trade = kvp.Value;
                if (trade == null) continue;
                if (info.Security == null)
                {
                    if (!string.IsNullOrEmpty(info.Symbol) && symbols.ContainsKey(info.Symbol))
                        info.Security = symbols[info.Symbol];
                }
                if (info.Security != null)
                {
                    if (info.Security.Currency == null)
                    {
                        sb.Append(TradeImportHelper.FormatErrorMessage("Bad Security currency is NULL", info.HoldingID, info.TradeID, info.Instrument));
                        continue;
                    }
                    if (filterData.Currencies != null && filterData.Currencies.Count > 0 && !filterData.Currencies.Contains(info.Security.Currency))
                    {
                        continue;
                    }

                    var equity = info.Security as Equity;
                    if (CreateEquity(trade, info, market, sb, tempEquityProvider))
                    {
                        trades.Add(trade);
                    }
                }
                else
                    sb.Append(TradeImportHelper.FormatErrorMessage("Security not found", info.HoldingID, info.TradeID, info.Symbol));

            }
            if (exceptions.Count > 0)
            {
                sb.Append("Exceptions snapping equities:\n");
                foreach (var ex in exceptions) sb.Append(ex.Message + " " + ex + "\n");
            }
            if (filterData.Progress != null) filterData.Progress.AnalysisDone();
            sb.Append("Imported " + trades.Count + " Equities\n");

            return trades;

        }
Exemple #33
0
        private static TestCaseData[] GetValueTestParameters()
        {
            const decimal delta = 1m;
            const decimal price = 1.2345m;
            const int quantity = 100;
            const decimal pricePlusDelta = price + delta;
            const decimal priceMinusDelta = price - delta;
            var tz = TimeZones.NewYork;

            var time = new DateTime(2016, 2, 4, 16, 0, 0).ConvertToUtc(tz);

            var equity = new Equity(SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency));
            equity.SetMarketPrice(new Tick {Value = price});

            var gbpCash = new Cash("GBP", 0, 1.46m);
            var properties = SymbolProperties.GetDefault(gbpCash.Symbol);
            var forex = new Forex(SecurityExchangeHours.AlwaysOpen(tz), gbpCash, new SubscriptionDataConfig(typeof(TradeBar), Symbols.EURGBP, Resolution.Minute, tz, tz, true, false, false), properties);
            forex.SetMarketPrice(new Tick {Value= price});

            var eurCash = new Cash("EUR", 0, 1.12m);
            properties = new SymbolProperties("Euro-Bund", eurCash.Symbol, 10, 0.1m, 1);
            var cfd = new Cfd(SecurityExchangeHours.AlwaysOpen(tz), eurCash, new SubscriptionDataConfig(typeof(TradeBar), Symbols.DE10YBEUR, Resolution.Minute, tz, tz, true, false, false), properties);
            cfd.SetMarketPrice(new Tick { Value = price });
            var multiplierTimesConversionRate = properties.ContractMultiplier*eurCash.ConversionRate;

            return new List<ValueTestParameters>
            {
                // equity orders
                new ValueTestParameters("EquityLongMarketOrder", equity, new MarketOrder(Symbols.SPY, quantity, time), quantity*price),
                new ValueTestParameters("EquityShortMarketOrder", equity, new MarketOrder(Symbols.SPY, -quantity, time), -quantity*price),
                new ValueTestParameters("EquityLongLimitOrder", equity, new LimitOrder(Symbols.SPY, quantity, priceMinusDelta, time), quantity*priceMinusDelta),
                new ValueTestParameters("EquityShortLimit Order", equity, new LimitOrder(Symbols.SPY, -quantity, pricePlusDelta, time), -quantity*pricePlusDelta),
                new ValueTestParameters("EquityLongStopLimitOrder", equity, new StopLimitOrder(Symbols.SPY, quantity,.5m*priceMinusDelta, priceMinusDelta, time), quantity*priceMinusDelta),
                new ValueTestParameters("EquityShortStopLimitOrder", equity, new StopLimitOrder(Symbols.SPY, -quantity, 1.5m*pricePlusDelta, pricePlusDelta, time), -quantity*pricePlusDelta),
                new ValueTestParameters("EquityLongStopMarketOrder", equity, new StopMarketOrder(Symbols.SPY, quantity, priceMinusDelta, time), quantity*priceMinusDelta),
                new ValueTestParameters("EquityLongStopMarketOrder", equity, new StopMarketOrder(Symbols.SPY, quantity, pricePlusDelta, time), quantity*price),
                new ValueTestParameters("EquityShortStopMarketOrder", equity, new StopMarketOrder(Symbols.SPY, -quantity, pricePlusDelta, time), -quantity*pricePlusDelta),
                new ValueTestParameters("EquityShortStopMarketOrder", equity, new StopMarketOrder(Symbols.SPY, -quantity, priceMinusDelta, time), -quantity*price),

                // forex orders
                new ValueTestParameters("ForexLongMarketOrder", forex, new MarketOrder(Symbols.EURGBP, quantity, time), quantity*price*forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexShortMarketOrder", forex, new MarketOrder(Symbols.EURGBP, -quantity, time), -quantity*price*forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexLongLimitOrder", forex, new LimitOrder(Symbols.EURGBP, quantity, priceMinusDelta, time), quantity*priceMinusDelta*forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexShortLimit Order", forex, new LimitOrder(Symbols.EURGBP, -quantity, pricePlusDelta, time), -quantity*pricePlusDelta*forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexLongStopLimitOrder", forex, new StopLimitOrder(Symbols.EURGBP, quantity,.5m*priceMinusDelta, priceMinusDelta, time), quantity*priceMinusDelta*forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexShortStopLimitOrder", forex, new StopLimitOrder(Symbols.EURGBP, -quantity, 1.5m*pricePlusDelta, pricePlusDelta, time), -quantity*pricePlusDelta*forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexLongStopMarketOrder", forex, new StopMarketOrder(Symbols.EURGBP, quantity, priceMinusDelta, time), quantity*priceMinusDelta*forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexLongStopMarketOrder", forex, new StopMarketOrder(Symbols.EURGBP, quantity, pricePlusDelta, time), quantity*price*forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexShortStopMarketOrder", forex, new StopMarketOrder(Symbols.EURGBP, -quantity, pricePlusDelta, time), -quantity*pricePlusDelta*forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexShortStopMarketOrder", forex, new StopMarketOrder(Symbols.EURGBP, -quantity, priceMinusDelta, time), -quantity*price*forex.QuoteCurrency.ConversionRate),
                
                // cfd orders
                new ValueTestParameters("CfdLongMarketOrder", cfd, new MarketOrder(Symbols.DE10YBEUR, quantity, time), quantity*price*multiplierTimesConversionRate),
                new ValueTestParameters("CfdShortMarketOrder", cfd, new MarketOrder(Symbols.DE10YBEUR, -quantity, time), -quantity*price*multiplierTimesConversionRate),
                new ValueTestParameters("CfdLongLimitOrder", cfd, new LimitOrder(Symbols.DE10YBEUR, quantity, priceMinusDelta, time), quantity*priceMinusDelta*multiplierTimesConversionRate),
                new ValueTestParameters("CfdShortLimit Order", cfd, new LimitOrder(Symbols.DE10YBEUR, -quantity, pricePlusDelta, time), -quantity*pricePlusDelta*multiplierTimesConversionRate),
                new ValueTestParameters("CfdLongStopLimitOrder", cfd, new StopLimitOrder(Symbols.DE10YBEUR, quantity,.5m*priceMinusDelta, priceMinusDelta, time), quantity*priceMinusDelta*multiplierTimesConversionRate),
                new ValueTestParameters("CfdShortStopLimitOrder", cfd, new StopLimitOrder(Symbols.DE10YBEUR, -quantity, 1.5m*pricePlusDelta, pricePlusDelta, time), -quantity*pricePlusDelta*multiplierTimesConversionRate),
                new ValueTestParameters("CfdLongStopMarketOrder", cfd, new StopMarketOrder(Symbols.DE10YBEUR, quantity, priceMinusDelta, time), quantity*priceMinusDelta*multiplierTimesConversionRate),
                new ValueTestParameters("CfdLongStopMarketOrder", cfd, new StopMarketOrder(Symbols.DE10YBEUR, quantity, pricePlusDelta, time), quantity*price*multiplierTimesConversionRate),
                new ValueTestParameters("CfdShortStopMarketOrder", cfd, new StopMarketOrder(Symbols.DE10YBEUR, -quantity, pricePlusDelta, time), -quantity*pricePlusDelta*multiplierTimesConversionRate),
                new ValueTestParameters("CfdShortStopMarketOrder", cfd, new StopMarketOrder(Symbols.DE10YBEUR, -quantity, priceMinusDelta, time), -quantity*price*multiplierTimesConversionRate),

            }.Select(x => new TestCaseData(x).SetName(x.Name)).ToArray();
        }