public void OnCurrentValueChanged(DateTime time, double value)
        {
            MaxValue = Math.Max(value, MaxValue);
            if (!AllowHistory)
            {
                return;
            }
            DateTime lastValueTime = DateTime.MinValue;

            if (ValueHistory.Count > 0)
            {
                lastValueTime = ValueHistory.Last().Time;
            }
            if (time - lastValueTime > AggregationTime)
            {
                ValueHistory.Add(new TimeBaseValue()
                {
                    Time = time, Value = value
                });
            }
            DateTime stopLossTime = DateTime.MinValue;

            if (StopLossHistory.Count > 0)
            {
                stopLossTime = StopLossHistory.Last().Time;
            }
            if (time - stopLossTime > AggregationTime)
            {
                StopLossHistory.Add(new TimeBaseValue()
                {
                    Time = time, Value = StopLoss
                });
            }
        }
예제 #2
0
 public System.Object ClientCommunication(Version serverversion, ICommunicateable communicator, bool full, System.Object obj)
 {
     try
     {
         if (serverversion.Major > 0)
         {
             if (full)
             {
                 IsComputer = communicator.ReceiveBool();
                 IsYou      = communicator.ReceiveBool();
                 ValueHistory.ClientCommunication(serverversion, communicator, full, obj);
             }
             if (IsYou && !full)
             {
                 communicator.SendString(Company);
                 communicator.SendString(Name);
             }
             else
             {
                 Company = communicator.ReceiveString();
                 Name    = communicator.ReceiveString();
             }
             Deposit.ClientCommunication(serverversion, communicator, full, obj);
             Capital = communicator.ReceiveDouble();
             ValueHistory.AddHistory(Value);
         }
         return(this);
     }
     catch (System.Exception ex)
     {
         throw ex;
     }
 }
예제 #3
0
 public System.Object ServerCommunication(Version clientversion, ICommunicateable communicator, bool full, System.Object obj)
 {
     try
     {
         if (clientversion.Major > 0)
         {
             if (full)
             {
                 communicator.SendBool(IsComputer);
                 communicator.SendBool(Id == (int)obj);
                 ValueHistory.ServerCommunication(clientversion, communicator, full, obj);
             }
             if (Id == (int)obj && !full)
             {
                 Company = communicator.ReceiveString();
                 Name    = communicator.ReceiveString();
             }
             else
             {
                 communicator.SendString(Company);
                 communicator.SendString(Name);
             }
             Deposit.ServerCommunication(clientversion, communicator, full, obj);
             communicator.SendDouble(Capital);
         }
         return(this);
     }
     catch (System.Exception ex)
     {
         throw ex;
     }
 }
예제 #4
0
        public List <string> GetValue(Date date)
        {
            var pairsWithEarlierOrSameDate = ValueHistory.TakeWhile(d => d.Key <= date);

            if (pairsWithEarlierOrSameDate.Any())
            {
                return(pairsWithEarlierOrSameDate.Last().Value);
            }
            return(InitialValue);
        }
예제 #5
0
        public async Task UpdateSensors()
        {
            var sensorsForUpdate = this.context.Sensors
                                   .Where(s => (DbFunctions.AddSeconds(s.LastUpdate, s.PollingInterval) <= DateTime.Now))
                                   .ToList();

            foreach (Sensor s in sensorsForUpdate)
            {
                var url = s.URL;

                var resp = await httpClient.GetAsync(url);

                var content = await resp.Content.ReadAsStringAsync();

                var updatedValue    = JsonConvert.DeserializeObject <SensorApiUpdate>(content);
                int pollingInterval = s.PollingInterval;

                if (s.IsBoolType)
                {
                    if (s.BoolTypeSensor.CurrentValue != bool.Parse(updatedValue.Value))
                    {
                        var valueHistory = new ValueHistory()
                        {
                            BoolSensor = s.BoolTypeSensor,
                            Date       = updatedValue.TimeStamp,
                            Value      = updatedValue.Value.ToLower() == "true" ? 1 : 0
                        };
                        s.BoolTypeSensor.BoolHistory.Add(valueHistory);
                        s.BoolTypeSensor.CurrentValue = bool.Parse(updatedValue.Value);
                    }
                }
                else
                {
                    if (s.ValueTypeSensor.CurrentValue != double.Parse(updatedValue.Value))
                    {
                        var valueHistory = new ValueHistory()
                        {
                            ValueSensor = s.ValueTypeSensor,
                            Date        = updatedValue.TimeStamp,
                            Value       = double.Parse(updatedValue.Value)
                        };
                        s.ValueTypeSensor.ValueHistory.Add(valueHistory);
                        s.ValueTypeSensor.CurrentValue = double.Parse(updatedValue.Value);

                        SendEmailIfNeeded(s);
                    }
                }

                s.LastUpdate = updatedValue.TimeStamp;
            }

            this.context.SaveChanges();
        }
예제 #6
0
 public void Reset(System.Random random)
 {
     try
     {
         Capital = CAPITAL_INITIALIZE;
         Deposit.Reset(random);
         ValueHistory.Reset(random);
         ValueHistory.Add(Value);
     }
     catch (System.Exception ex)
     {
         throw ex;
     }
 }
예제 #7
0
        public void RollBackToFirstValue()
        {
            var storage = new ValueHistory<int>();

            int maximumValue = 10;
            for (int i = 0; i < maximumValue; i++)
            {
                storage.Current = i;
                storage.StoreCurrent(new TimeMarker((ulong)(i + 1)));
            }

            storage.RollBackTo(new TimeMarker(1));
            int storedValue = storage;
            Assert.AreEqual(0, storedValue);
        }
예제 #8
0
        /// <summary>
        /// Creates a default layer that isn't linked to a timeline.
        /// </summary>
        /// <param name="instanceStorage">The object that stores the instances of the parts.</param>
        /// <remarks>
        /// This method is provided for testing purposes only.
        /// </remarks>
        /// <returns>The newly created instance.</returns>
        internal static CompositionLayer CreateInstanceWithoutTimeline(IStoreInstances instanceStorage)
        {
            var history = new ValueHistory <IStoreInstances>
            {
                Current = instanceStorage
            };

            return(new CompositionLayer(
                       new HistoryId(),
                       new DictionaryHistory <GroupRegistrationId, GroupDefinition>(),
                       new DictionaryHistory <GroupCompositionId, GroupRegistrationId>(),
                       new BidirectionalGraphHistory <GroupCompositionId, GroupCompositionGraphEdge>(),
                       new DictionaryHistory <PartCompositionId, PartCompositionInfo>(),
                       new BidirectionalGraphHistory <PartCompositionId, PartImportExportEdge <PartCompositionId> >(),
                       history));
        }
예제 #9
0
        public override void UpdateData(IEvolutionaryPopulation population)
        {
            var f          = population.FitnessFunction;
            var individual = population.HeavenPolicy.Memory.Last();

            if (Index == History.Length)
            {
                History      = History.Resize();
                ValueHistory = ValueHistory.Resize();
            }

            ValueHistory[Index] = f.GetValue(individual);
            History[Index]      = Length + 1 == 0
                ? ValueHistory[Index]
                : ValueHistory[Index] - ValueHistory[Index - 1];
            Index++;
        }
예제 #10
0
        public override void SensorChangedProcess(SensorEvent e)
        {
            // Check if we even want to read this sensor
            switch (e.Sensor.Type)
            {
            case SensorType.Accelerometer:
                _accelerometer = e.Values.ToArray();
                break;

            case SensorType.MagneticField:
                _geomagnetic = e.Values.ToArray();
                break;

            case SensorType.Gravity:
                _gravity = e.Values.ToArray();
                break;
            }


            if (_gravity != null && _geomagnetic != null && _accelerometer != null)
            {
                var R = new float[16];
                var I = new float[16];
                SensorManager.GetRotationMatrix(R, I, _gravity, _geomagnetic);
                var relativacc = new float[4];
                var inv        = new float[16];

                relativacc[0] = _accelerometer[0];
                relativacc[1] = _accelerometer[1];
                relativacc[2] = _accelerometer[2];
                relativacc[3] = 0;

                var A_W = new float[4];

                Matrix.InvertM(inv, 0, R, 0);
                Matrix.MultiplyMV(A_W, 0, inv, 0, relativacc, 0);
                Value = new Vector3(A_W);
                // Value = new Vector3(_accelerometer);
                ValueHistory.Enqueue(Value);
                if (OnValueChanged != null)
                {
                    OnValueChanged(Value);
                }
            }
        }
예제 #11
0
        public void RollBackToPreviousValue()
        {
            var storage = new ValueHistory<int>();

            int maximumValue = 10;
            for (int i = 0; i < maximumValue; i++)
            {
                storage.Current = i;
                storage.StoreCurrent(new TimeMarker((ulong)(i + 1)));
            }

            for (int i = maximumValue; i > 0; i--)
            {
                storage.RollBackTo(new TimeMarker((ulong)i));
                int storedValue = storage;
                Assert.AreEqual(i - 1, storedValue);
            }
        }
예제 #12
0
        public override void SensorChangedProcess(SensorEvent e)
        {
            switch (e.Sensor.Type)
            {
            case SensorType.MagneticField:
                mMagnetic = e.Values.ToArray();
                break;

            case SensorType.Gravity:
                mGravity = e.Values.ToArray();
                break;
            }

            if (mGravity != null && mMagnetic != null)
            {
                var success = SensorManager.GetRotationMatrix(mRotationMatrix, null, mGravity, mMagnetic);
                if (success)
                {
                    // inclination is the degree of tilt by the device independent of orientation (portrait or landscape)
                    // if less than 25 or more than 155 degrees the device is considered lying flat
                    float inclination = (float)Math.Acos(mRotationMatrix[8]);
                    if (inclination < TWENTY_FIVE_DEGREE_IN_RADIAN ||
                        inclination > ONE_FIFTY_FIVE_DEGREE_IN_RADIAN)
                    {
                        // mFacing is undefined, so we need to clear the history
                        ClearRotHist();
                        mFacing = float.NaN;
                    }
                    else
                    {
                        SetRotHist();
                        // mFacing = azimuth is in radian
                        mFacing = FindFacing();
                    }

                    Value = mFacing;
                    ValueHistory.Enqueue(Value);
                    if (OnValueChanged != null)
                    {
                        OnValueChanged(Value);
                    }
                }
            }
        }
예제 #13
0
        public LatencyMonitor(
            IRpcProtocol protocol, IPhotonPeer nativePeer, byte operationCode, int maxHistoryLength, int intervalMs, WorkloadController workloadController)
            : base(protocol, nativePeer)
        {
            this.operationCode = operationCode;
            this.intervalMs = intervalMs;
            this.workloadController = workloadController;
            this.latencyHistory = new ValueHistory(maxHistoryLength);
            this.averageLatencyMs = 0;
            this.lastLatencyMs = 0;

            log.InfoFormat("{1} connection for latency monitoring established (id={0}), serverId={2}", this.ConnectionId, this.NetworkProtocol, GameApplication.ServerId);

            if (!Stopwatch.IsHighResolution)
            {
                log.InfoFormat("No hires stopwatch!");
            }
            
            this.pingTimer = this.RequestFiber.ScheduleOnInterval(this.Ping, 0, this.intervalMs);
        }
예제 #14
0
 public void Save(Version fv, WsgFileStream fs)
 {
     try
     {
         if (fv.Major > 0)
         {
             fs.WriteString(Company);
             fs.WriteString(Name);
             fs.WriteBool(IsComputer);
             fs.WriteBool(IsYou);
             Deposit.Save(fv, fs);
             ValueHistory.Save(fv, fs);
             fs.WriteDouble(Capital);
         }
     }
     catch (System.Exception ex)
     {
         throw ex;
     }
 }
예제 #15
0
 public System.Object Load(Version fv, WsgFileStream fs, System.Object obj)
 {
     try
     {
         if (fv.Major > 0)
         {
             Company    = fs.ReadString();
             Name       = fs.ReadString();
             IsComputer = fs.ReadBool();
             IsYou      = fs.ReadBool();
             Deposit.Load(fv, fs, obj);
             ValueHistory.Load(fv, fs, obj);
             Capital = fs.ReadDouble();
         }
         return(this);
     }
     catch (System.Exception ex)
     {
         throw ex;
     }
 }
예제 #16
0
 /**
  * Generate a new ARTA-Process with the given parameters.
  * */
 public ArProcess(double[] alphas, NormalDistribution whiteNoiseProcess)
 {
     this.alphas            = alphas;
     this.values            = new DoubleHistory(alphas.Length);
     this.whiteNoiseProcess = whiteNoiseProcess;
 }
예제 #17
0
        public async Task RecordValueHistory(VooperContext context, string type, DateTime time)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            // First clear outdated records
            if (type == "MINUTE")
            {
                context.RemoveRange(context.ValueHistory.AsQueryable().Where(v => v.Type == "MINUTE" && EF.Functions.DateDiffMinute(v.Time, time) > 2000));
            }
            else if (type == "HOUR")
            {
                context.RemoveRange(context.ValueHistory.AsQueryable().Where(v => v.Type == "HOUR" && EF.Functions.DateDiffHour(v.Time, time) > 2000));
            }
            else if (type == "DAY")
            {
                context.RemoveRange(context.ValueHistory.AsQueryable().Where(v => v.Type == "DAY" && EF.Functions.DateDiffDay(v.Time, time) > 2000));
            }

            // Add new records

            List <ValueHistory> additions = new List <ValueHistory>();

            // User Portfolios

            foreach (Entity user in context.Users)
            {
                decimal portValue = await user.GetPortfolioValue();

                if (portValue > 0)
                {
                    ValueHistory hist = new ValueHistory()
                    {
                        Id         = Guid.NewGuid().ToString(),
                        Account_Id = user.Id,
                        Time       = time,
                        Type       = type,
                        Value      = Math.Min(portValue, 9999999999M)
                    };

                    additions.Add(hist);
                }
            }

            // Group Portfolios

            foreach (Entity group in context.Groups)
            {
                decimal portValue = await group.GetPortfolioValue();

                if (portValue > 0)
                {
                    ValueHistory hist = new ValueHistory()
                    {
                        Id         = Guid.NewGuid().ToString(),
                        Account_Id = group.Id,
                        Time       = time,
                        Type       = type,
                        Value      = Math.Min(portValue, 9999999999M)
                    };

                    additions.Add(hist);
                }
            }

            // Stocks

            foreach (StockDefinition stock in context.StockDefinitions)
            {
                decimal value = stock.Current_Value;

                int volume = 0;

                Dictionary <string, int> volumesDict = null;

                if (type == "MINUTE")
                {
                    volumesDict = ExchangeManager.VolumesMinute;
                }
                else if (type == "HOUR")
                {
                    volumesDict = ExchangeManager.VolumesHour;
                }
                else
                {
                    volumesDict = ExchangeManager.VolumesDay;
                }

                if (volumesDict.ContainsKey(stock.Ticker))
                {
                    volume = volumesDict[stock.Ticker];
                    volumesDict[stock.Ticker] = 0;
                }

                ValueHistory hist = new ValueHistory()
                {
                    Id         = Guid.NewGuid().ToString(),
                    Account_Id = stock.Ticker,
                    Time       = time,
                    Type       = type,
                    Value      = Math.Min(value, 9999999999M),
                    Volume     = volume
                };

                additions.Add(hist);
            }

            await context.AddRangeAsync(additions);

            await context.SaveChangesAsync();

            sw.Stop();

            _logger.LogInformation($"Added {additions.Count} financial records in {sw.Elapsed.Seconds} seconds.");
        }
 public AverageCounterReader(int capacity, string categoryName, string counterName, string instanceName)
     : base(categoryName, counterName, instanceName)
 {
     this.values = new ValueHistory(capacity);
 }
예제 #19
0
 /// <summary>
 /// Creates a default layer that isn't linked to a timeline.
 /// </summary>
 /// <param name="instanceStorage">The object that stores the instances of the parts.</param>
 /// <remarks>
 /// This method is provided for testing purposes only.
 /// </remarks>
 /// <returns>The newly created instance.</returns>
 internal static CompositionLayer CreateInstanceWithoutTimeline(IStoreInstances instanceStorage)
 {
     var history = new ValueHistory<IStoreInstances>
         {
             Current = instanceStorage
         };
     return new CompositionLayer(
         new HistoryId(),
         new DictionaryHistory<GroupRegistrationId, GroupDefinition>(),
         new DictionaryHistory<GroupCompositionId, GroupRegistrationId>(),
         new BidirectionalGraphHistory<GroupCompositionId, GroupCompositionGraphEdge>(),
         new DictionaryHistory<PartCompositionId, PartCompositionInfo>(),
         new BidirectionalGraphHistory<PartCompositionId, PartImportExportEdge<PartCompositionId>>(),
         history);
 }
예제 #20
0
        public void Play(MarketState marketstate, System.Random random)
        {
            try
            {
                if (IsComputer)
                {
                    if (Deposit.Count > 0)
                    {
                        StockIndex lastindex        = null;
                        double     lastpriceaverage = 0D;
                        double     savecapital      = 0D;
                        foreach (DepositContent content in Deposit.Values)
                        {
                            if (content.Stock.StockIndexes.Count > 0)
                            {
                                System.Collections.Generic.Dictionary <string, StockIndex> .Enumerator e = content.Stock.StockIndexes.GetEnumerator();
                                if (e.MoveNext())
                                {
                                    if (lastindex == null)
                                    {
                                        lastindex        = e.Current.Value;
                                        lastpriceaverage = lastindex.PriceAverage;
                                        savecapital      = (lastindex.PriceAverage * 15);
                                    }
                                    else if (e.Current.Value.Id != lastindex.Id)
                                    {
                                        lastindex        = e.Current.Value;
                                        lastpriceaverage = lastindex.PriceAverage;
                                        savecapital      = (lastindex.PriceAverage * 15);
                                    }
                                    // Handle computer players deposit.
                                    int buyprocentlow = 0, buyprocentmiddle = 0, buyprocenthigh = 0, maxbuyprepoch = MAX_BUY_PR_EPOCH, stockstobuy = 0;
                                    int sellprocentlow = 0, sellprocentmiddle = 0, sellprocenthigh = 0, maxsellprepoch = MAX_SELL_PR_EPOCH, stockstosell = 0;
                                    switch (marketstate.State)
                                    {
                                    case MarketStateType.Normal:
                                        buyprocentlow     = 75;
                                        buyprocentmiddle  = 85;
                                        buyprocenthigh    = 95;
                                        sellprocentlow    = 50;
                                        sellprocentmiddle = 70;
                                        sellprocenthigh   = 90;
                                        break;

                                    case MarketStateType.Depression:
                                        buyprocentlow     = 60;
                                        buyprocentmiddle  = 70;
                                        buyprocenthigh    = 80;
                                        sellprocentlow    = 30;
                                        sellprocentmiddle = 50;
                                        sellprocenthigh   = 70;
                                        break;

                                    case MarketStateType.Boom:
                                        buyprocentlow     = 70;
                                        buyprocentmiddle  = 80;
                                        buyprocenthigh    = 90;
                                        sellprocentlow    = 70;
                                        sellprocentmiddle = 80;
                                        sellprocenthigh   = 90;
                                        break;

                                    default:
                                        buyprocentlow     = 100;
                                        buyprocentmiddle  = 100;
                                        buyprocenthigh    = 100;
                                        sellprocentlow    = 100;
                                        sellprocentmiddle = 100;
                                        sellprocenthigh   = 100;
                                        break;
                                    }
                                    // Try to buy stocks.
                                    if (content.Stock.Price < content.Stock.MinPrice * 4 && content.Stock.Available > 0)
                                    {
                                        if (random.Next(100) > buyprocentlow / 1.75 && maxbuyprepoch > 0)
                                        {
                                            stockstobuy = MAX_STOCKS_TO_BUY;
                                            if (stockstobuy > content.Stock.Available)
                                            {
                                                stockstobuy = content.Stock.Available;
                                            }
                                            while (stockstobuy > 0 && content.Stock.CalculatePrice(stockstobuy) + content.Stock.CalculateBrokerage(marketstate, stockstobuy) > Capital - savecapital)
                                            {
                                                stockstobuy = (int)System.Math.Floor((double)(stockstobuy / 10));
                                            }
                                            if (stockstobuy > 5)
                                            {
                                                content.Buy(marketstate, random.Next(stockstobuy));
                                                maxbuyprepoch -= 1;
                                            }
                                            else if (stockstobuy > 0)
                                            {
                                                content.Buy(marketstate, stockstobuy);
                                                maxbuyprepoch -= 1;
                                            }
                                        }
                                    }
                                    else if (content.Stock.Price < lastpriceaverage / 8 && (content.LastSellPrice == 0 || content.Stock.Price < content.LastSellPrice || content.Stock.Price > content.LastSellPrice * 1.5) && content.Stock.Available > 0)
                                    {
                                        // Try to buy stocks.
                                        if (random.Next(100) > buyprocentlow && maxbuyprepoch > 0)
                                        {
                                            stockstobuy = MAX_STOCKS_TO_BUY;
                                            if (stockstobuy > content.Stock.Available)
                                            {
                                                stockstobuy = content.Stock.Available;
                                            }
                                            while (stockstobuy > 0 && content.Stock.CalculatePrice(stockstobuy) + content.Stock.CalculateBrokerage(marketstate, stockstobuy) > Capital - savecapital)
                                            {
                                                stockstobuy = (int)System.Math.Floor((double)(stockstobuy / 10));
                                            }
                                            if (stockstobuy > 5)
                                            {
                                                content.Buy(marketstate, random.Next(stockstobuy));
                                                maxbuyprepoch -= 1;
                                            }
                                            else if (stockstobuy > 0)
                                            {
                                                content.Buy(marketstate, stockstobuy);
                                                maxbuyprepoch -= 1;
                                            }
                                        }
                                    }
                                    else if (content.Stock.Price < lastpriceaverage / 4 && (content.LastSellPrice == 0 || content.Stock.Price < content.LastSellPrice || content.Stock.Price > content.LastSellPrice * 1.5) && content.Stock.Available > 0)
                                    {
                                        // Try to buy stocks.
                                        if (random.Next(100) > buyprocentmiddle && maxbuyprepoch > 0)
                                        {
                                            stockstobuy = MAX_STOCKS_TO_BUY;
                                            if (stockstobuy > content.Stock.Available)
                                            {
                                                stockstobuy = content.Stock.Available;
                                            }
                                            while (stockstobuy > 0 && content.Stock.CalculatePrice(stockstobuy) + content.Stock.CalculateBrokerage(marketstate, stockstobuy) > Capital - savecapital)
                                            {
                                                stockstobuy = (int)System.Math.Floor((double)(stockstobuy / 10));
                                            }
                                            if (stockstobuy >= 10)
                                            {
                                                stockstobuy = stockstobuy / 2;
                                                if (stockstobuy > 5)
                                                {
                                                    content.Buy(marketstate, random.Next(stockstobuy));
                                                    maxbuyprepoch -= 1;
                                                }
                                                else if (stockstobuy > 0)
                                                {
                                                    content.Buy(marketstate, stockstobuy);
                                                    maxbuyprepoch -= 1;
                                                }
                                            }
                                        }
                                    }
                                    else if (content.Stock.Price < lastpriceaverage && (content.LastSellPrice == 0 || content.Stock.Price < content.LastSellPrice || content.Stock.Price > content.LastSellPrice * 1.5) && content.Stock.Available > 0)
                                    {
                                        // Try to buy stocks.
                                        if (random.Next(100) > buyprocenthigh && maxbuyprepoch > 0)
                                        {
                                            stockstobuy = MAX_STOCKS_TO_BUY;
                                            if (stockstobuy > content.Stock.Available)
                                            {
                                                stockstobuy = content.Stock.Available;
                                            }
                                            while (stockstobuy > 0 && content.Stock.CalculatePrice(stockstobuy) + content.Stock.CalculateBrokerage(marketstate, stockstobuy) > Capital - savecapital)
                                            {
                                                stockstobuy = (int)System.Math.Floor((double)(stockstobuy / 10));
                                            }
                                            if (stockstobuy >= 20)
                                            {
                                                stockstobuy = stockstobuy / 4;
                                                if (stockstobuy > 5)
                                                {
                                                    content.Buy(marketstate, random.Next(stockstobuy));
                                                    maxbuyprepoch -= 1;
                                                }
                                                else if (stockstobuy > 0)
                                                {
                                                    content.Buy(marketstate, stockstobuy);
                                                    maxbuyprepoch -= 1;
                                                }
                                            }
                                        }
                                    }
                                    // Try to sell stocks.
                                    if (marketstate.State == MarketStateType.Depression && content.Stock.Price < content.LastBuyPrice / 4 && content.LastBuyPrice > content.Stock.MinPrice * 50)
                                    {
                                        // No profit expected.
                                        stockstosell = content.Count;
                                        if (stockstosell > 5)
                                        {
                                            content.Sell(marketstate, random.Next(stockstosell));
                                            maxsellprepoch -= 1;
                                        }
                                        else
                                        {
                                            content.Sell(marketstate, stockstosell);
                                            maxsellprepoch -= 1;
                                        }
                                    }
                                    else if (content.Count > 0 && content.Stock.Price > content.LastBuyPrice * 2 && content.Stock.Price > content.Stock.MinPrice * 5)
                                    {
                                        // Try to sell stocks.
                                        if (random.Next(100) > sellprocentlow && maxsellprepoch > 0)
                                        {
                                            stockstosell = content.Count;
                                            if (stockstosell > 5)
                                            {
                                                content.Sell(marketstate, random.Next(stockstosell));
                                                maxsellprepoch -= 1;
                                            }
                                            else
                                            {
                                                content.Sell(marketstate, stockstosell);
                                                maxsellprepoch -= 1;
                                            }
                                        }
                                    }
                                    else if (content.Count > 0 && content.Stock.Price > content.LastBuyPrice * 1.5 && content.Stock.Price > content.Stock.MinPrice * 5)
                                    {
                                        // Try to sell stocks.
                                        if (random.Next(100) > sellprocentmiddle && maxsellprepoch > 0)
                                        {
                                            stockstosell = content.Count;
                                            if (stockstosell >= 10)
                                            {
                                                stockstosell = stockstosell / 2;
                                                if (stockstosell > 5)
                                                {
                                                    content.Sell(marketstate, random.Next(stockstosell));
                                                    maxsellprepoch -= 1;
                                                }
                                                else
                                                {
                                                    content.Sell(marketstate, stockstosell);
                                                    maxsellprepoch -= 1;
                                                }
                                            }
                                            else
                                            {
                                                content.Sell(marketstate, stockstosell);
                                                maxsellprepoch -= 1;
                                            }
                                        }
                                    }
                                    else if (content.Count > 0 && content.Stock.Price > content.LastBuyPrice * 1.25 && content.Stock.Price > content.Stock.MinPrice * 5)
                                    {
                                        // Try to sell stocks.
                                        if (random.Next(100) > sellprocenthigh && maxsellprepoch > 0)
                                        {
                                            stockstosell = content.Count;
                                            if (stockstosell >= 20)
                                            {
                                                stockstosell = stockstosell / 4;
                                                if (stockstosell > 5)
                                                {
                                                    content.Sell(marketstate, random.Next(stockstosell));
                                                    maxsellprepoch -= 1;
                                                }
                                                else
                                                {
                                                    content.Sell(marketstate, stockstosell);
                                                    maxsellprepoch -= 1;
                                                }
                                            }
                                            else
                                            {
                                                content.Sell(marketstate, stockstosell);
                                                maxsellprepoch -= 1;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                ValueHistory.AddHistory(Value);
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
예제 #21
0
 public void RollBackToStartWithNoValues()
 {
     var storage = new ValueHistory<int>();
     Assert.DoesNotThrow(() => storage.RollBackToStart());
 }