public void Test_ManyTrades_Limit()
        {
            var trades = new List <LimitQueueItem.LimitTradeInfo>()
            {
                new LimitQueueItem.LimitTradeInfo
                {
                    Volume         = 0.9,
                    OppositeVolume = 8100,
                    Price          = 9000,
                    Asset          = "BTC",
                    OppositeAsset  = "USD"
                },
                new LimitQueueItem.LimitTradeInfo
                {
                    Volume         = 0.3,
                    OppositeVolume = 2745,
                    Price          = 9150,
                    Asset          = "BTC",
                    OppositeAsset  = "USD"
                },
                new LimitQueueItem.LimitTradeInfo
                {
                    Volume         = 0.1,
                    OppositeVolume = 920,
                    Price          = 9200,
                    Asset          = "BTC",
                    OppositeAsset  = "USD"
                }
            };

            Assert.Equal(9050, ConvertExtensions.CalcEffectivePrice(trades, GetDefaultPair(), false));
        }
示例#2
0
 private object GetValue(Type type, object value)
 {
     if (type.IsPrimitive)
     {
         return(GetPrimitiveValue(type, value));
     }
     else if (Nullable.GetUnderlyingType(type) != null) //if we're nullable, id say call the getvalue method again on the underlying type
     {
         var t = Nullable.GetUnderlyingType(type);
         return(GetValue(t, value));
     }
     else if (type == typeof(string))
     {
         return(value.ToString());
     }
     else if (type.IsEnum)
     {
         return(ConvertExtensions.ToEnum <XmlEnumAttribute>(value.ToString(), type));
     }
     else if (type == typeof(DateTime))
     {
         return(DateTime.Parse(value.ToString()));
     }
     else if (type == typeof(TimeSpan))
     {
         return(ConvertExtensions.ToTimeSpan(value.ToString()));
     }
     return(null);
 }
示例#3
0
        protected override int DoCompareValues(int index1, int index2)
        {
            object obj1 = _values [index1];
            object obj2 = _values [index2];

            if (obj1 == obj2)
            {
                return(0);
            }

            if (obj1 is IComparable)
            {
                try {
                    return(((IComparable)obj1).CompareTo(obj2));
                } catch {
                    if (obj2 is IComparable)
                    {
                        obj2 = ConvertExtensions.ChangeType(obj2, Type.GetTypeCode(obj1.GetType()));
                        return(((IComparable)obj1).CompareTo(obj2));
                    }
                }
            }

            return(String.Compare(obj1.ToString(), obj2.ToString()));
        }
示例#4
0
        private IConvertible CalcStatisticalFunction(object[] values)
        {
            if (count < 2)
            {
                return(DBNull.Value);
            }

            double average = (double)ConvertExtensions.ChangeType(result, TypeCode.Double) / count;
            double res     = 0.0;

            foreach (object val in values)
            {
                if (val == null)
                {
                    continue;
                }

                double diff = average - (double)ConvertExtensions.ChangeType(val, TypeCode.Double);
                res += System.Math.Pow(diff, 2);
            }
            res /= (count - 1);

            if (function == AggregationFunction.StDev)
            {
                res = System.Math.Sqrt(res);
            }

            return(res);
        }
        public void Test_Trade_Price_Rounding()
        {
            var pair = GetDefaultPair();

            var trades = new List <TradeQueueItem.TradeInfo>()
            {
                new TradeQueueItem.TradeInfo
                {
                    MarketVolume = 1,
                    LimitVolume  = 10000,
                    Price        = 10000,
                    MarketAsset  = "BTC",
                    LimitAsset   = "USD"
                },
                new TradeQueueItem.TradeInfo
                {
                    MarketVolume = 2,
                    LimitVolume  = 22000,
                    Price        = 11000,
                    MarketAsset  = "BTC",
                    LimitAsset   = "USD"
                }
            };

            Assert.Equal(10666.666, ConvertExtensions.CalcEffectivePrice(trades, pair, false), pair.Accuracy);
            Assert.Equal(10666.667, ConvertExtensions.CalcEffectivePrice(trades, pair, true), pair.Accuracy);
        }
示例#6
0
        //(note: o1 and o2 must both be of type Int32/Int64/Decimal/Double)
        internal static TypeCode ToSameType(ref IConvertible o1, ref IConvertible o2)
        {
            TypeCode tc1 = o1.GetTypeCode();
            TypeCode tc2 = o2.GetTypeCode();

            if (tc1 == tc2)
            {
                return(tc1);
            }

            if (tc1 == TypeCode.DBNull || tc2 == TypeCode.DBNull)
            {
                return(TypeCode.DBNull);
            }


            // is it ok to make such assumptions about the order of an enum?
            if (tc1 < tc2)
            {
                o1 = (IConvertible)ConvertExtensions.ChangeType(o1, tc2);
                return(tc2);
            }
            else
            {
                o2 = (IConvertible)ConvertExtensions.ChangeType(o2, tc1);
                return(tc1);
            }
        }
示例#7
0
        void SetDefaultValue(object value, bool forcedTypeCheck)
        {
            if (forcedTypeCheck || !this._defaultValue.Equals(value))
            {
                if (value == null || value == DBNull.Value)
                {
                    _defaultValue = GetDefaultValueForType(DataType);
                }
                else if (DataType.IsInstanceOfType(value))
                {
                    _defaultValue = value;
                }
                else
                {
                    try {
                        _defaultValue = ConvertExtensions.ChangeType(value, DataType);
                    } catch (InvalidCastException) {
                        string msg = String.Format("Default Value of type '{0}' is not compatible with column type '{1}'", value.GetType(), DataType);
                        throw new DataException(msg);
                    }
                }
            }

            // store default value in the table if already belongs to
            if (Table != null && Table.DefaultValuesRowIndex != -1)
            {
                DataContainer [Table.DefaultValuesRowIndex] = _defaultValue;
            }
        }
        public IList <ForeignExchangeRateModel> ToForeignExchangeRateModels(ForeignExchangeRateDto foreignExchangeRateDto, string date)
        {
            if (foreignExchangeRateDto == null || ListExtensions.IsNullOrEmpty(foreignExchangeRateDto.TargetCurrencies))
            {
                return(new List <ForeignExchangeRateModel>());
            }

            var dateAsInt = GetDateAsInt(foreignExchangeRateDto.PublicationDate);

            if (dateAsInt.ToString() != date)
            {
                return(new List <ForeignExchangeRateModel>());
            }

            var rates = new List <ForeignExchangeRateDto> {
                foreignExchangeRateDto
            };

            return(rates.SelectMany(rate => rate.TargetCurrencies, (r, c) => new ForeignExchangeRateModel {
                Id = Guid.NewGuid(),
                Date = dateAsInt,
                BaseCurrency = TextExtensions.ToEnglishUpper(r.BaseCurrency),
                TargetCurrency = TextExtensions.ToEnglishUpper(c.TargetCurrency),
                InverseRate = ConvertExtensions.ToDecimal(c.InverseRate),
                PublicationDate = r.PublicationDate
            }).ToList());
        }
        private TResult GetParameterValueOrDefault <TResult>(CommandParameter parameter, TResult defaultValue = default(TResult))
        {
            if (parameter == null)
            {
                return(defaultValue);
            }

            var value = parameter.GetEvaluatedValue(this.ToDictionary());

            if (value == null)
            {
                return(defaultValue);
            }

            if (string.IsNullOrEmpty(value.ToStringOrEmpty()))
            {
                return(defaultValue);
            }

            if (value is IConvertible)
            {
                return((TResult)ConvertExtensions.ChangeType(value, typeof(TResult)));
            }

            return((TResult)value);
        }
示例#10
0
        internal static int Compare(IComparable o1, IComparable o2, bool caseSensitive)
        {
            //TODO: turn this "conversion pipeline" into something nicer

            try {
                if (o1 is string && Numeric.IsNumeric(o2))
                {
                    o1 = (IComparable)ConvertExtensions.ChangeType(o1, o2.GetType());
                }
                else if (o2 is string && Numeric.IsNumeric(o1))
                {
                    o2 = (IComparable)ConvertExtensions.ChangeType(o2, o1.GetType());
                }
                else if (o1 is string && o2 is Guid)
                {
                    o2 = o2.ToString();
                }
                else if (o2 is string && o1 is Guid)
                {
                    o1 = o1.ToString();
                }
            } catch (FormatException) {
                throw new EvaluateException(String.Format("Cannot perform compare operation on {0} and {1}.", o1.GetType(), o2.GetType()));
            }

            if (o1 is string && o2 is string)
            {
                o1 = ((string)o1).TrimEnd(IgnoredTrailingChars);
                o2 = ((string)o2).TrimEnd(IgnoredTrailingChars);
                if (!caseSensitive)
                {
                    o1 = ((string)o1).ToLower();
                    o2 = ((string)o2).ToLower();
                }
            }

            if (o1 is DateTime && o2 is string && Thread.CurrentThread.CurrentCulture != CultureInfo.InvariantCulture)
            {
                // DateTime is always CultureInfo.InvariantCulture
                o2 = (IComparable)DateTime.Parse((string)o2, CultureInfo.InvariantCulture);
            }
            else if (o2 is DateTime && o1 is string &&
                     Thread.CurrentThread.CurrentCulture != CultureInfo.InvariantCulture)
            {
                // DateTime is always CultureInfo.InvariantCulture
                o1 = (IComparable)DateTime.Parse((string)o1, CultureInfo.InvariantCulture);
            }
            else if (o2 is DateTime && o1 is string && Thread.CurrentThread.CurrentCulture != CultureInfo.InvariantCulture)
            {
                // DateTime is always CultureInfo.InvariantCulture
                o1 = (IComparable)DateTime.Parse((string)o1, CultureInfo.InvariantCulture);
            }

            if (o1.GetType() != o2.GetType())
            {
                o2 = (IComparable)ConvertExtensions.ChangeType(o2, o1.GetType());
            }

            return(o1.CompareTo(o2));
        }
        public static T AskInput <T>(string message)
        {
            Console.WriteLine();
            Console.WriteLine(message);

            string input = Console.ReadLine();

            return(ConvertExtensions.ChangeType <T>(input));
        }
示例#12
0
        public CustomMessage ActivationUser(string activationCode)
        {
            var message = new CustomMessage();

            try
            {
                var dbContext = DbContainer.GetDbContext();
                dbContext.Configuration.ValidateOnSaveEnabled = false;

                // 查询激活码的有效性
                var activationInfo = dbContext.Sys_Activation.Where(c => c.ActivationCode == activationCode).FirstOrDefault();
                if (activationInfo == null)
                {
                    throw new Exception("激活码不存在或已过期!");
                }

                string source = DESHelper.Decrypt(activationCode, Global.__KEY);
                if (string.IsNullOrEmpty(source))
                {
                    throw new Exception("激活码有误!请重新输入");
                }

                // 解码后的信息,包含用户名还有激活等级
                dynamic info            = JsonConvert.DeserializeObject <dynamic>(source);
                string  userName        = info.UserName;
                int     activationLevel = info.ActivationLevel;

                // 修改用户激活数据
                var userItem = (from u in dbContext.UserInfo
                                where u.UserName == userName
                                select u).FirstOrDefault();
                userItem.IsActivation    = true;
                userItem.ActivationLevel = activationLevel;
                userItem.ActivationDate  = DateTime.Now;

                // 删除掉临时保存的激活码
                dbContext.Sys_Activation.Remove(activationInfo);

                if (dbContext.SaveChanges() == 0)
                {
                    message.Status  = HttpStatus.Error;
                    message.Message = "修改错误";
                }

                message.Status  = HttpStatus.OK;
                message.Message = $"账号激活成功!到期日期为{ConvertExtensions.ToActivationDate(activationLevel)}后";
            }
            catch (Exception objException)
            {
                LogHelper.Error(objException);
                message.Status  = HttpStatus.Error;
                message.Message = objException.Message;
            }

            return(message);
        }
示例#13
0
        public static Bitmap EmbedInformation(this Bitmap image, int wordLength, int significantBitsLength,
                                              AreaEmbeddingModel areaEmbedding, Matrix matrix, int bitsLength)
        {
            var bitsSequance = ConvertExtensions.GenerateBitsSequence(bitsLength).ToCompleteStringEmptyBits(significantBitsLength);

            if (string.IsNullOrEmpty(bitsSequance))
            {
                Logger.Fatal("Embedding information failed! Embedding information is null or empty!");
                return(null);
            }

            return(Modifier.Embed(image, wordLength, significantBitsLength, areaEmbedding, matrix, bitsSequance));
        }
示例#14
0
        /// <summary>
        /// Reads a collection of <see cref="double"/> values from XML.
        /// </summary>
        /// <param name="collection">Collection to be filled with values read from XML.</param>
        /// <param name="collectionElementName">Name of the collection parent XML element.</param>
        /// <param name="valueElementName">Name of the XML element that represents collection item.</param>
        /// <param name="parentElement"><see cref="XElement"/> instance that is parent to the collection element.</param>
        private static void ReadValueCollection(IDictionary <TId, double> collection, XName collectionElementName, XName valueElementName, XElement parentElement)
        {
            XElement valueCollectionElement      = ReadCollectionElement(collectionElementName, parentElement);
            IEnumerable <XElement> valueElements = valueCollectionElement.Descendants(valueElementName);

            foreach (XElement valueElement in valueElements)
            {
                TId    id    = TId.Parse(valueElement.Attribute(Attributes.Id).Value);
                double value = ConvertExtensions.ToDoubleInvariant(valueElement.Attribute(Attributes.Value).Value);

                collection.Add(id, value);
            }
        }
示例#15
0
        public CustomMessage UserLogin(string userName, string userPwd)
        {
            var message = new CustomMessage();

            try
            {
                var dbContext = DbContainer.GetDbContext();

                userPwd = MD5Helper.Encry(userPwd);
                var query = (from u in dbContext.UserInfo
                             where u.UserName == userName && u.UserPwd == userPwd
                             select u).ToList();

                if (query.Count() == 0)
                {
                    message.Status  = HttpStatus.Error;
                    message.Message = "用户名或密码错误!";
                }
                else
                {
                    Data.UserInfo user = query[0];

                    if (user.IsActivation == null)
                    {
                        message.Status  = HttpStatus.Error;
                        message.Message = "当前账户还未激活!";
                    }
                    else
                    {
                        // 计算剩余时间
                        var remainingSeconds = (DateTime.Now - ConvertExtensions.ToTimeSpan((int)user.ActivationLevel, (DateTime)user.ActivationDate)).TotalSeconds;

                        message.Status  = HttpStatus.OK;
                        message.Message = new
                        {
                            RemainingSeconds = remainingSeconds,
                            Info             = "登陆成功!"
                        };
                    }
                }
            }
            catch (Exception objException)
            {
                LogHelper.Error(objException);
                message.Status  = HttpStatus.Error;
                message.Message = objException.Message;
            }

            return(message);
        }
        public void Test_ConvertExtensions_Convert()
        {
            object intValue  = 3;
            object strValue  = "112";
            object timeValue = DateTime.Now.ToString();

            object r0 = ConvertExtensions.Convert(null, typeof(int));

            Assert.IsNull(r0);

            object r1 = ConvertExtensions.Convert(intValue, typeof(int));

            Assert.IsTrue(r1.GetType() == typeof(int));
            Assert.AreEqual(3, (int)r1);


            object r2 = ConvertExtensions.Convert(intValue, typeof(string));

            Assert.IsTrue(r2.GetType() == typeof(string));
            Assert.AreEqual("3", (string)r2);

            object r3 = ConvertExtensions.Convert(strValue, typeof(string));

            Assert.IsTrue(r3.GetType() == typeof(string));
            Assert.AreEqual("112", (string)r3);

            object r4 = ConvertExtensions.Convert(strValue, typeof(int));

            Assert.IsTrue(r4.GetType() == typeof(int));
            Assert.AreEqual(112, (int)r4);


            object guidString = Guid.NewGuid().ToString();
            object r5         = ConvertExtensions.Convert(guidString, typeof(Guid));

            Assert.IsTrue(r5.GetType() == typeof(Guid));
            Assert.AreEqual((string)guidString, r5.ToString());

            object r6 = ConvertExtensions.Convert(timeValue, typeof(DateTime));

            Assert.IsTrue(r6.GetType() == typeof(DateTime));
            Assert.AreEqual(timeValue, r6.ToString());

            object enumvalue = 5;
            object r7        = ConvertExtensions.Convert(enumvalue, typeof(DayOfWeek));

            Assert.IsTrue(r7.GetType() == typeof(int));
            Assert.AreEqual(5, (int)r7);
        }
示例#17
0
        public async Task <ClientTrade[]> Create(TradeQueueItem.MarketOrder order, List <TradeQueueItem.TradeInfo> trades, string clientId)
        {
            var assetPair = await _assetsServiceWithCache.TryGetAssetPairAsync(order.AssetPairId);

            var trade        = trades[0];
            var price        = ConvertExtensions.CalcEffectivePrice(trades, assetPair, order.Volume > 0);
            var marketVolume = trades.Sum(x => x.MarketVolume);
            var limitVolume  = trades.Sum(x => x.LimitVolume);

            var marketAssetRecord = CreateCommonPartForTradeRecord(trade, order.Id, price, order.AssetPairId);
            var limitAssetRecord  = CreateCommonPartForTradeRecord(trade, order.Id, price, order.AssetPairId);

            marketAssetRecord.ClientId = limitAssetRecord.ClientId = clientId;

            marketAssetRecord.Amount = marketVolume;
            if (Math.Sign(marketVolume) == Math.Sign(limitVolume))
            {
                marketAssetRecord.Amount *= -1;
            }
            marketAssetRecord.AssetId = trade.MarketAsset;

            limitAssetRecord.Amount  = limitVolume;
            limitAssetRecord.AssetId = trade.LimitAsset;

            foreach (var t in trades)
            {
                var transfer = t.Fees?.FirstOrDefault()?.Transfer;

                if (transfer != null)
                {
                    if (marketAssetRecord.AssetId == transfer.Asset)
                    {
                        marketAssetRecord.FeeSize += (double)transfer.Volume;
                        marketAssetRecord.FeeType  = FeeType.Absolute;
                    }
                    else
                    {
                        limitAssetRecord.FeeSize += (double)transfer.Volume;
                        limitAssetRecord.FeeType  = FeeType.Absolute;
                    }
                }
            }

            marketAssetRecord.Id = Core.Domain.CashOperations.Utils.GenerateRecordId(marketAssetRecord.DateTime);
            limitAssetRecord.Id  = Core.Domain.CashOperations.Utils.GenerateRecordId(limitAssetRecord.DateTime);

            return(new[] { marketAssetRecord, limitAssetRecord });
        }
        public void Test_OneTrade_Limit()
        {
            var trades = new List <LimitQueueItem.LimitTradeInfo>()
            {
                new LimitQueueItem.LimitTradeInfo
                {
                    Volume         = 1,
                    OppositeVolume = 8000,
                    Price          = 9000,
                    Asset          = "BTC",
                    OppositeAsset  = "USD"
                }
            };

            Assert.Equal(9000, ConvertExtensions.CalcEffectivePrice(trades, GetDefaultPair(), false));
        }
        public void Test_OneTrade_Market()
        {
            var trades = new List <TradeQueueItem.TradeInfo>()
            {
                new TradeQueueItem.TradeInfo
                {
                    MarketVolume = 1,
                    LimitVolume  = 8000,
                    Price        = 9000,
                    MarketAsset  = "BTC",
                    LimitAsset   = "USD"
                }
            };

            Assert.Equal(9000, ConvertExtensions.CalcEffectivePrice(trades, GetDefaultPair(), false));
        }
示例#20
0
        /// <summary>
        /// Reads a collection of <see cref="Parameter"/> from XML.
        /// </summary>
        /// <param name="model"><see cref="Model"/> instance to be read from XML.</param>
        /// <param name="parametersCollectionElement"><see cref="XElement"/> to read a collection from.</param>
        private static void ReadParameters(Model model, XElement parametersCollectionElement)
        {
            IEnumerable <XElement> parameterElements = parametersCollectionElement.Descendants(Elements.Parameter);

            foreach (XElement parameterElement in parameterElements)
            {
                TId    id   = TId.Parse(parameterElement.Attribute(Attributes.Id).Value);
                string name = parameterElement.Attribute(Attributes.Name).Value;
                string variableIdentifier = parameterElement.Attribute(Attributes.VariableIdentifier).Value;
                double minValue           = ConvertExtensions.ToDoubleInvariant(parameterElement.Attribute(Attributes.MinValue).Value);
                double maxValue           = ConvertExtensions.ToDoubleInvariant(parameterElement.Attribute(Attributes.MaxValue).Value);

                Parameter parameter = new Parameter(id, name, variableIdentifier, minValue, maxValue);
                ReadPropertyCollection(parameter.Properties, ReadCollectionElement(Elements.Properties, parameterElement, false));

                model.Parameters.Add(parameter);
            }
        }
        public static DataTable CreateTable <T>()
        {
            Type entityType = typeof(T);
            var  table      = new DataTable(entityType.Name);
            var  properties = TypeDescriptor.GetProperties(entityType);

            foreach (PropertyDescriptor prop in properties)
            {
                // respect nullable types
                Type type = ConvertExtensions.IsNullable(prop.PropertyType)
                                        ? Nullable.GetUnderlyingType(prop.PropertyType)
                                        : prop.PropertyType;

                table.Columns.Add(prop.Name, type);
            }

            return(table);
        }
示例#22
0
        /// <summary>
        /// Reads a collection of <see cref="Constraint"/> from XML.
        /// </summary>
        /// <param name="model"><see cref="Model"/> instance to be read from XML.</param>
        /// <param name="constraintsCollectionElement"><see cref="XElement"/> to read a collection from.</param>
        private static void ReadConstraints(Model model, XElement constraintsCollectionElement)
        {
            IEnumerable <XElement> constraintElements = constraintsCollectionElement.Descendants(Elements.FunctionalConstraint);

            foreach (XElement constraintElement in constraintElements)
            {
                TId      id   = TId.Parse(constraintElement.Attribute(Attributes.Id).Value);
                string   name = constraintElement.Attribute(Attributes.Name).Value;
                string   variableIdentifier = constraintElement.Attribute(Attributes.VariableIdentifier).Value;
                Relation constraintRelation = EnumExtensions.Parse <Relation>(constraintElement.Attribute(Attributes.Relation).Value);
                double   value      = ConvertExtensions.ToDoubleInvariant(constraintElement.Attribute(Attributes.Value).Value);
                string   expression = constraintElement.Attribute(Attributes.Expression).Value;

                Constraint constraint = new Constraint(id, name, variableIdentifier, constraintRelation, value, expression);
                ReadPropertyCollection(constraint.Properties, ReadCollectionElement(Elements.Properties, constraintElement, false));

                model.FunctionalConstraints.Add(constraint);
            }
        }
示例#23
0
        public async Task <GetStatisticsResponse> GetStatiststics(GetStatisticsRequest dto)
        {
            string                  query     = string.Empty;
            List <dynamic>          result    = new List <dynamic>();
            List <StatisticItemDto> statItems = new List <StatisticItemDto>();

            bool filterByMcc = dto.MccList?.Any() ?? false;

            string queryNoMccFilter = $@"SELECT count(s.id) as Count, date(s.created) as Day, c.mcc as Mcc, sum(c.pricePerSms) as TotalPrice, c.PricePerSms
                                        FROM app2sms.Sms s
                                        INNER JOIN app2sms.Country c on c.id = s.countryId
                                        where date(s.created) >= @dateFrom and date(s.created) <= @dateTo
                                        group by c.mcc, date(s.created)";

            string queryAllFilters = @"SELECT count(s.id) as Count, date(s.created) as Day, c.mcc as Mcc, sum(c.pricePerSms) as TotalPrice, c.PricePerSms
                                       FROM app2sms.Sms s
                                       INNER JOIN app2sms.Country c on c.id = s.countryId
                                       where date(s.created) >= @dateFrom and date(s.created) <= @dateTo
                                       and c.mcc in (@MccList)
                                       group by c.mcc, date(s.created)";

            query = filterByMcc ? queryAllFilters : queryNoMccFilter;

            using (var db = _dbFactory.OpenDbConnection())
            {
                result = await db.SelectAsync <dynamic>(query, new { dto.MccList, dto.DateFrom, dto.DateTo });
            }

            result.ForEach(row =>
            {
                StatisticItemDto item = ConvertExtensions.ConvertToStatDto(row);
                statItems.Add(item);
            });

            return(new GetStatisticsResponse()
            {
                StatisticsItems = statItems
            });
        }
        public void Test_Trade_With_Zero_Volume()
        {
            var trades = new List <TradeQueueItem.TradeInfo>()
            {
                new TradeQueueItem.TradeInfo
                {
                    MarketVolume = 0.000001,
                    LimitVolume  = 0,
                    Price        = 9000,
                    MarketAsset  = "BTC",
                    LimitAsset   = "USD"
                },
                new TradeQueueItem.TradeInfo
                {
                    MarketVolume = 0.3,
                    LimitVolume  = 2745,
                    Price        = 9150,
                    MarketAsset  = "BTC",
                    LimitAsset   = "USD"
                }
            };

            Assert.Equal(9150, ConvertExtensions.CalcEffectivePrice(trades, GetDefaultPair(), false));
        }
示例#25
0
        //extends to Int32/Int64/Decimal/Double
        internal static IConvertible Unify(IConvertible o)
        {
            switch (o.GetTypeCode())
            {
            case TypeCode.Char:
            case TypeCode.SByte:
            case TypeCode.Byte:
            case TypeCode.Int16:
            case TypeCode.UInt16:
                return((IConvertible)ConvertExtensions.ChangeType(o, TypeCode.Int32));

            case TypeCode.UInt32:
                return((IConvertible)ConvertExtensions.ChangeType(o, TypeCode.Int64));

            case TypeCode.UInt64:
                return((IConvertible)ConvertExtensions.ChangeType(o, TypeCode.Decimal));

            case TypeCode.Single:
                return((IConvertible)ConvertExtensions.ChangeType(o, TypeCode.Double));

            default:
                return(o);
            }
        }
        private static void ReadPromotableCriteria(ModelDraft modelDraft, XElement promotableCriterionCollectionElement)
        {
            IEnumerable <XElement> promotableCriterionElements = promotableCriterionCollectionElement.Descendants(Elements.PromotableCriterion);

            foreach (XElement promotableCriterionElement in promotableCriterionElements)
            {
                TId           id   = TId.Parse(promotableCriterionElement.Attribute(Attributes.Id).Value);
                string        name = promotableCriterionElement.Attribute(Attributes.Name).Value;
                string        variableIdentifier = promotableCriterionElement.Attribute(Attributes.VariableIdentifier).Value;
                bool          isPromoted         = Convert.ToBoolean(promotableCriterionElement.Attribute(Attributes.IsPromoted).Value);
                CriterionType criterionType      = EnumExtensions.Parse <CriterionType>(promotableCriterionElement.Attribute(Attributes.Type).Value);
                Relation      constraintRelation = EnumExtensions.Parse <Relation>(promotableCriterionElement.Attribute(Attributes.Relation).Value);
                double        value = ConvertExtensions.ToDoubleInvariant(promotableCriterionElement.Attribute(Attributes.Value).Value);

                PromotableCriterion promotableCriterion = new PromotableCriterion(id, name, variableIdentifier, criterionType)
                {
                    ConstraintRelation = constraintRelation,
                    IsPromoted         = isPromoted,
                    Value = value
                };

                modelDraft.PromotableCriteria.Add(promotableCriterion);
            }
        }
        private static void ReadPromotableConstants(ModelDraft modelDraft, XElement promotableConstantCollectionElement)
        {
            IEnumerable <XElement> promotableConstantElements = promotableConstantCollectionElement.Descendants(Elements.PromotableConstant);

            foreach (XElement promotableConstantElement in promotableConstantElements)
            {
                TId    id   = TId.Parse(promotableConstantElement.Attribute(Attributes.Id).Value);
                string name = promotableConstantElement.Attribute(Attributes.Name).Value;
                string variableIdentifier = promotableConstantElement.Attribute(Attributes.VariableIdentifier).Value;
                bool   isPromoted         = Convert.ToBoolean(promotableConstantElement.Attribute(Attributes.IsPromoted).Value);
                double value    = ConvertExtensions.ToDoubleInvariant(promotableConstantElement.Attribute(Attributes.Value).Value);
                double minValue = ConvertExtensions.ToDoubleInvariant(promotableConstantElement.Attribute(Attributes.MinValue).Value);
                double maxValue = ConvertExtensions.ToDoubleInvariant(promotableConstantElement.Attribute(Attributes.MaxValue).Value);

                PromotableConstant promotableConstant = new PromotableConstant(id, name, variableIdentifier, value)
                {
                    IsPromoted = isPromoted,
                    MaxValue   = maxValue,
                    MinValue   = minValue
                };

                modelDraft.PromotableConstants.Add(promotableConstant);
            }
        }
示例#28
0
        /// <summary>
        /// Reads <see cref="Double"/> values of entities represented by <typeparamref name="T"/> from <paramref name="streamReader"/>
        /// to the <paramref name="valuesCollection"/>
        /// </summary>
        /// <typeparam name="T">Type of the entity which value should be read</typeparam>
        /// <param name="entitiesCollection">Collection of entities to read values of</param>
        /// <param name="valuesCollection">A collection to read values to</param>
        /// <param name="streamReader"><see cref="StreamReader"/> instance used to read values</param>
        private static void ReadValues <T>(IEnumerable <T> entitiesCollection, IDictionary <TId, double> valuesCollection, StreamReader streamReader) where T : ModelEntity
        {
            if (entitiesCollection == null)
            {
                throw new ArgumentNullException("entitiesCollection");
            }

            if (valuesCollection == null)
            {
                throw new ArgumentNullException("valuesCollection");
            }

            if (streamReader == null)
            {
                throw new ArgumentNullException("streamReader");
            }

            foreach (T entity in entitiesCollection)
            {
                string valueString = streamReader.ReadLine();
                if (string.IsNullOrEmpty(valueString))
                {
                    throw new InvalidOperationException("Cannot read Double value from file stream");
                }

                double value = ConvertExtensions.ToDoubleInvariant(valueString);
                if (valuesCollection.ContainsKey(entity.Id))
                {
                    valuesCollection[entity.Id] = value;
                }
                else
                {
                    valuesCollection.Add(entity.Id, value);
                }
            }
        }
示例#29
0
        override public object Eval(DataRow row)
        {
            object val = expr.Eval(row);

            // TMPFIX :Eval shud never really return a null.. DBNull.Value but not null
            // needs to be done for all expressions .. for now ,just check for null
            if (val == null)
            {
                return(DBNull.Value);
            }

            if (val == DBNull.Value || val.GetType() == targetType)
            {
                return(val);
            }

            //--> String is always allowed
            if (targetType == typeof(string))
            {
                return(val.ToString());
            }

            //only TimeSpan <--> String is allowed
            if (targetType == typeof(TimeSpan))
            {
                if (val is string)
                {
                    return(TimeSpan.Parse((string)val));
                }
                else
                {
                    ThrowInvalidCastException(val);
                }
            }

            if (val is TimeSpan)
            {
                ThrowInvalidCastException(val);
            }

            //only Char <--> String/Int32/UInt32 is allowed
            if (val is Char && !(targetType == typeof(Int32) || targetType == typeof(UInt32)))
            {
                ThrowInvalidCastException(val);
            }

            if (targetType == typeof(Char) && !(val is Int32 || val is UInt32))
            {
                ThrowInvalidCastException(val);
            }

            //bool <--> Char/Single/Double/Decimal/TimeSpan/DateTime is not allowed
            if (val is Boolean && (targetType == typeof(Single) || targetType == typeof(Double) || targetType == typeof(Decimal)))
            {
                ThrowInvalidCastException(val);
            }

            if (targetType == typeof(Boolean) && (val is Single || val is Double || val is Decimal))
            {
                ThrowInvalidCastException(val);
            }

            //Convert throws the remaining invalid casts
            return(ConvertExtensions.ChangeType(val, targetType));
        }
        private static T CreateTypedObject <T>(DataRow row, CultureInfo culture, IEnumerable <ValueConverterDefinition> converterDefinitions)
        {
            var obj = Activator.CreateInstance <T>();

            var objType         = obj.GetType();
            var dataMemberProps = objType.GetProperties()
                                  .Where(p => Attribute.IsDefined(p, typeof(DataMemberAttribute)))
                                  .ToList();

            var dataFieldsProps = objType.GetProperties()
                                  .Where(p => Attribute.IsDefined(p, typeof(DataFieldAttribute)))
                                  .ToList();

            foreach (DataColumn column in row.Table.Columns)
            {
                bool isRequired = false;

                // get the property
                var property = objType.GetProperty(column.ColumnName.Trim(), BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

                if (property == null && dataFieldsProps.Any())
                {
                    // look for [DataField] attribute
                    property = dataFieldsProps.FirstOrDefault(p => ((DataFieldAttribute)Attribute.GetCustomAttribute(p, typeof(DataFieldAttribute))).Name == column.ColumnName);
                    if (property != null)
                    {
                        isRequired = ((DataFieldAttribute)Attribute.GetCustomAttribute(property, typeof(DataFieldAttribute))).IsRequired;
                    }
                }

                if (property == null && dataMemberProps.Any())
                {
                    // otherwise look for [DataMember] attribute
                    property = dataMemberProps.FirstOrDefault(p => ((DataMemberAttribute)Attribute.GetCustomAttribute(p, typeof(DataMemberAttribute))).Name == column.ColumnName);
                    if (property != null)
                    {
                        isRequired = ((DataMemberAttribute)Attribute.GetCustomAttribute(property, typeof(DataMemberAttribute))).IsRequired;
                    }
                }

                if (property != null)
                {
                    object value = row[column.ColumnName];

                    if (value == null && isRequired)
                    {
                        // When required but null, throw
                        throw new NoNullAllowedException(column.ColumnName);
                    }
                    else
                    {
                        // when converters exits convert the value
                        if (converterDefinitions != null)
                        {
                            foreach (var converterDef in converterDefinitions.Where(x => x.FieldName == column.ColumnName))
                            {
                                value = converterDef.Converter.Convert(value, property.PropertyType, converterDef.ConverterParameter, culture);
                            }
                        }

                        object tgtValue = ConvertExtensions.ChangeTypeExtended(value, property.PropertyType, culture);

                        property.SetValue(obj, tgtValue, null);
                    }
                }
            }
            return(obj);
        }