示例#1
0
        public void Initialize()
        {
            StockCode = "";
            Market = StockMarket.Unknown;

            SendBonus = 0;
            TransferBonus = 0;
            BonusIssue = 0;

            BonusRegDate = DateTime.MinValue;
            BonusExeDate = DateTime.MinValue;
            SendFlag = 0;
        }
示例#2
0
        public void Initialize()
        {
            StockCode = "";
            Market = StockMarket.Unknown;

            Scheme = 0;
            Price = 0;

            RecordDate = DateTime.MinValue;
            PayBeginDate = DateTime.MinValue;
            PayEndDate = DateTime.MinValue;
            ExecuteDate = DateTime.MinValue;
            Force = false;

            SendFlag = 0;
        }
        public ActionResult Edit([Bind(Include = "Id,BuyTarget,LastPrice,SellTarget,Quantity")] StockMarket stockMarket)
        {
            if (ModelState.IsValid)
            {
                StockRealTime sr = new StockRealTime();
                //sr.RefreshDataPerSymbol(stockMarket);

                db.StockMarkets.Attach(stockMarket);
                db.Entry(stockMarket).Property(p => p.BuyTarget).IsModified  = true;
                db.Entry(stockMarket).Property(p => p.SellTarget).IsModified = true;
                db.Entry(stockMarket).Property(p => p.Quantity).IsModified   = true;
                //db.Entry(stockMarket).Property(p => p.SellDecision).IsModified = true;
                //db.Entry(stockMarket).Property(p => p.BuyDecision).IsModified = true;
                //db.Entry(stockMarket).Property(p => p.CurrentValue).IsModified = true;
                db.SaveChanges();

                return(RedirectToAction("Index"));
            }
            return(View(stockMarket));
        }
示例#4
0
        public async Task InstallProductAsync(StockMarket stockMarket, Stream stream, CancellationToken cancellationToken)
        {
            this.lambdaContext.Logger.LogLine($"{stockMarket} product import started");

            switch (stockMarket)
            {
            case StockMarket.Eurex:
                await this.InstallProductEurexAsync(stream, cancellationToken);

                break;

            case StockMarket.Xetra:
                await this.InstallProductXetraAsync(stream, cancellationToken);

                break;

            default: throw new ArgumentException("Invalid Stock Market");
            }

            this.lambdaContext.Logger.LogLine($"{stockMarket} product import completed");
        }
示例#5
0
        private void StartStockMarketSimulator()
        {
            StockMarket = new StockMarket(StockRepository);
            StockMarket.AddStock("MSFT", 26.31m);
            StockMarket.AddStock("APPL", 404.18m);
            StockMarket.AddStock("GOOG", 596.30m);
            StockMarket.AddStock("SUN", 596.30m);
            StockMarket.AddStock("CSCO", 300);
            StockMarket.AddStock("AMZN", 170);

            var stockMarketListener = new StockMarketListener();

            StockMarket.MarketStateChanged += (sender, args) =>
                                              stockMarketListener.Handle(new MarketStateChange(args.Data));

            StockMarket.StockChanged += (sender, args) =>
                                        stockMarketListener.Handle(StockChangeEventFactory.Create(args.Data));


            StockMarket.Start();
        }
示例#6
0
        public static void Go()
        {
            var encog = new EncogPersistedCollection("market-network.dat", FileMode.Open);

            Console.WriteLine(@"Loading network");
            var network = (BasicNetwork)encog.Find("market-network");

            Console.WriteLine(@"Reading current data from db");
            var market = new StockMarket();

            market.Init(false);
            var data = market.GetCurrentData();

            Console.WriteLine(@"Running network on data");

            var madness = new ModelMadness();

            foreach (StockMarket.WorkableStockInfo info in data)
            {
                var input       = InputOutputMadness.CreateInputs(info);
                var neuralInput = new BasicMLData(input);
                var output      = network.Compute(neuralInput);

                Console.WriteLine(@"Stock " + info.ViewToday.stock + @" will change " + output[0] + @"% in the next 20 trading days");

                var future = new prediction
                {
                    day            = DateTime.Now.Date,
                    C20_Days_Close = 100 * (decimal)output[0],
                    stock          = info.ViewToday.stock
                };

                madness.AddTopredictions(future);
            }

            madness.SaveChanges();

            Console.WriteLine(@"Done - begin making $millions");
        }
示例#7
0
        public async Task ImportProduct(StockMarket stockMarket, CancellationToken cancellationToken)
        {
            var resourceBucketName = default(string);

            switch (stockMarket)
            {
            case StockMarket.Eurex:
                resourceBucketName = CumulusConstants.SystemBucketObject.EurexProducts;
                break;

            case StockMarket.Xetra:
                resourceBucketName = CumulusConstants.SystemBucketObject.XetraProducts;
                break;

            default: throw new ArgumentException("Invalid Stock Market");
            }

            var objectStream = await this.amazonS3.GetObjectStreamAsync(CumulusConstants.SystemBucket.Resource, resourceBucketName, null, cancellationToken);

            using (objectStream)
                await installService.InstallProductAsync(stockMarket, objectStream, cancellationToken);
        }
示例#8
0
 public void Initialize()
 {
     try
     {
         OrderID     = 0;
         UserID      = 0;
         OrdType     = OrderType.None;
         OrdStatus   = OrderStatus.Unknown;
         Side        = false;
         StockCode   = "";
         Market      = StockMarket.Unknown;
         OrderVolume = 0;
         OrderPrice  = 0;
         TradePrice  = 0;
         Curr        = Currency.Unknown;
         OrderDate   = Common.MinDateTime;
         UpdatedDate = Common.MinDateTime;
         ExpiredDate = Common.MaxDateTime;
     }
     catch
     { }
 }
示例#9
0
        public async Task <ActionResult> MarketEdit(StockMarketModel model)
        {
            var result = new JsonModel();

            if (!ModelState.IsValid)
            {
                result.GetError(ModelState);
                return(Json(result));
            }

            StockMarket market        = null;
            var         operationType = OperationType.Update;

            if (model.Id > 0)
            {
                operationType = OperationType.Update;
                market        = await StockMarketRepository.GetEnableByIdAsync(model.Id);

                if (market == null)
                {
                    result.statusCode = 300;
                    result.message    = "该条数据不存在,请刷新重试!";
                    return(Json(result));
                }
            }
            else
            {
                market = new StockMarket();
            }
            Mapper.Map(model, market);
            market.CommonStatus = CommonStatus.Enabled;
            await StockMarketRepository.SaveAsync(market);

            await LogRepository.Insert(TableSource.StockMarket, operationType, "", market.Id);

            result.Data    = market;
            result.message = "保存成功!";
            return(Json(result));
        }
示例#10
0
        public ActionResult SellStockOptions([Bind(Include = "StockAccountID,StockMarketID,TradeID,Quantity,SaleDate")] SellStockTradeOptions SSTO)
        {
            // Get the stock to sell
            StockMarket StockToSell = db.StockMarket.Find(SSTO.StockMarketID);

            // Get the trade
            Trade CustomerTrade = db.Trades.Find(SSTO.TradeID);

            // Create a new sellstock object and send to the view
            SellStocksTrade SST = new SellStocksTrade
            {
                StockMarketID   = SSTO.StockMarketID,
                StockAccountID  = SSTO.StockAccountID,
                StockName       = StockToSell.CompanyName,
                QuantitySold    = SSTO.Quantity,
                Fee             = StockToSell.Fee,
                Profit          = ((StockToSell.StockPrice * SSTO.Quantity) - (CustomerTrade.PricePerShare * SSTO.Quantity)),
                SharesRemaining = (CustomerTrade.Quantity - SSTO.Quantity),
                TradeID         = SSTO.TradeID,
                SaleDate        = SSTO.SaleDate
            };

            return(View("SellStocks", SST));
        }
示例#11
0
        public static void Create()
        {
            var market = new StockMarket();

            market.Init(true);

            Console.WriteLine(@"Fetching training data from db");

            var trainingData = market.GetTrainingData();

            Console.WriteLine(@"Creating training set");

            var inputs  = new ArrayList();
            var outputs = new ArrayList();
            var cur     = 1;

            foreach (var info in trainingData)
            {
                Console.WriteLine(@"Adding record " + (cur++) + @" of " + trainingData.Count);

                var input  = InputOutputMadness.CreateInputs(info);
                var output = new[] { InputOutputMadness.CreateOutput(info) };

                inputs.Add(input);
                outputs.Add(output);
            }

            Console.WriteLine(@"Created training set - saving");

            var trainingSet = new BasicMLDataSet((double[][])inputs.ToArray(typeof(double[])), (double[][])outputs.ToArray(typeof(double[])));
            var encog       = new EncogPersistedCollection("market-training.dat", FileMode.Create);

            encog.Add("market-training", trainingSet);

            Console.WriteLine(@"saved");
        }
示例#12
0
        private async Task PushSQSMessages(StockMarket sourceBucketType, ICollection <BucketObject> bucketObjectCollection, CancellationToken cancellationToken)
        {
            var queueUrl = default(string);

            switch (sourceBucketType)
            {
            case StockMarket.Eurex:
                queueUrl = CumulusConstants.MessageQueue.EurexPendingObjectQueueUrl;
                break;

            case StockMarket.Xetra:
                queueUrl = CumulusConstants.MessageQueue.XetraPendingObjectQueueUrl;
                break;

            default:
                throw new ArgumentException("Unknown source bucket type", nameof(sourceBucketType));
            }

            var sendMessageBatchRequest = new SendMessageBatchRequest()
            {
                QueueUrl = queueUrl
            };

            var messageDelayGap = CumulusConstants.MaximumSQSMessageDelaySeconds / bucketObjectCollection.Count;

            var messageDelay = 0;

            foreach (var bucketObject in bucketObjectCollection)
            {
                sendMessageBatchRequest.Entries.Add(new SendMessageBatchRequestEntry
                {
                    Id           = bucketObject.ObjectID,
                    DelaySeconds = messageDelay,
                    MessageBody  = bucketObject.ObjectKey
                });

                messageDelay += messageDelayGap;
            }

            var sendMessageBatchResponse = await this.sqsClient.SendMessageBatchAsync(sendMessageBatchRequest, cancellationToken);

            var queuedBucketObjectCollection = new List <BucketObject>();

            foreach (var sendMessageBatchResultEntry in sendMessageBatchResponse.Successful)
            {
                var bucketObject = bucketObjectCollection.Where(e => e.ObjectID == sendMessageBatchResultEntry.Id).FirstOrDefault();
                if (bucketObject != null)
                {
                    bucketObject.Status = (int)BucketObjectStatus.Queued;
                    bucketObject.CurrentStatusErrorCount = 0;
                    bucketObject.CurrentStatusLastError  = null;

                    queuedBucketObjectCollection.Add(bucketObject);
                }
            }

            await this.repository.SaveItemBatchInternalAsync(queuedBucketObjectCollection, cancellationToken);

            var errorBucketObjectCollection = new List <BucketObject>();

            foreach (var batchResultErrorEntry in sendMessageBatchResponse.Failed)
            {
                var bucketObject = bucketObjectCollection.Where(e => e.ObjectID == batchResultErrorEntry.Id).FirstOrDefault();
                if (bucketObject != null)
                {
                    bucketObject.CurrentStatusErrorCount++;
                    bucketObject.CurrentStatusLastError = batchResultErrorEntry.Message;

                    errorBucketObjectCollection.Add(bucketObject);
                }
            }

            await this.repository.SaveItemBatchInternalAsync(errorBucketObjectCollection, cancellationToken);

            this.context.Logger.LogLine($"{sourceBucketType} - {queuedBucketObjectCollection.Count} sqs messages queued successfully and {errorBucketObjectCollection.Count} sqs messages were failed");
        }
示例#13
0
        public async Task RerouteDeadMessages(StockMarket stockMarket, CancellationToken cancellationToken)
        {
            var deadMessageQueueUrl     = default(string);
            var destinationMessageQueue = default(string);

            switch (stockMarket)
            {
            case StockMarket.Eurex:
                deadMessageQueueUrl     = CumulusConstants.MessageQueue.EurexDeadObjectQueueUrl;
                destinationMessageQueue = CumulusConstants.MessageQueue.EurexPendingObjectQueueUrl;
                break;

            case StockMarket.Xetra:
                deadMessageQueueUrl     = CumulusConstants.MessageQueue.XetraDeadObjectQueueUrl;
                destinationMessageQueue = CumulusConstants.MessageQueue.XetraPendingObjectQueueUrl;
                break;

            default:
                break;
            }

            var deadMessageResponse = await this.sqsClient.ReceiveMessageAsync(new ReceiveMessageRequest
            {
                MaxNumberOfMessages = CumulusConstants.RerouteDeadMessageQueueCount,
                WaitTimeSeconds     = CumulusConstants.RerouteDeadMessageQueueWaitTime,
                QueueUrl            = deadMessageQueueUrl,
            });

            this.context.Logger.LogLine($"{deadMessageResponse.Messages.Count} dead messages retrived");

            var sendMessageBatchRequest = new SendMessageBatchRequest()
            {
                QueueUrl = destinationMessageQueue
            };

            var messageDelayGap = CumulusConstants.MaximumSQSMessageDelaySeconds / deadMessageResponse.Messages.Count;

            var messageDelay = 0;

            var newMessageIdCollection = deadMessageResponse
                                         .Messages
                                         .ToDictionary(
                deadMessage => Guid.NewGuid().ToStringID(),
                deadMessage => deadMessage
                );

            foreach (var deadmessage in deadMessageResponse.Messages)
            {
                var newMessageID = newMessageIdCollection
                                   .Where(e => e.Value.MessageId == deadmessage.MessageId)
                                   .Select(e => e.Key)
                                   .FirstOrDefault();

                if (!sendMessageBatchRequest.Entries.Where(e => e.MessageBody == deadmessage.Body).Any())
                {
                    sendMessageBatchRequest.Entries.Add(new SendMessageBatchRequestEntry
                    {
                        Id           = newMessageID,
                        DelaySeconds = messageDelay,
                        MessageBody  = deadmessage.Body
                    });

                    messageDelay += messageDelayGap;
                }
            }

            this.context.Logger.LogLine($"re-routing {sendMessageBatchRequest.Entries.Count} unique messages");

            var sendMessageBatchResponse = await this.sqsClient.SendMessageBatchAsync(sendMessageBatchRequest, cancellationToken);

            var deleteDeadMessageBatchRequest = new DeleteMessageBatchRequest
            {
                Entries  = new List <DeleteMessageBatchRequestEntry>(),
                QueueUrl = deadMessageQueueUrl
            };

            this.context.Logger.LogLine($"{sendMessageBatchResponse.Successful.Count} messages re-routed successfully and {sendMessageBatchResponse.Failed.Count} messages failed");

            foreach (var reRouteSuccessfulMessage in sendMessageBatchResponse.Successful)
            {
                var deadMessage = newMessageIdCollection[reRouteSuccessfulMessage.Id];

                deleteDeadMessageBatchRequest.Entries.Add(new DeleteMessageBatchRequestEntry
                {
                    Id            = deadMessage.MessageId,
                    ReceiptHandle = deadMessage.ReceiptHandle
                });
            }

            var deleteMessageBatchResponse = await this.sqsClient.DeleteMessageBatchAsync(deleteDeadMessageBatchRequest, cancellationToken);

            this.context.Logger.LogLine($"{deleteMessageBatchResponse.Successful.Count} messages successfully deleted from dead queue and {deleteMessageBatchResponse.Failed.Count} messages failed");
        }
示例#14
0
        protected async Task <PendingBucketObjectKeyCollection> GetPendingObjectKeyCollectionInternal(string lastObjectMarkerKey, StockMarket sourceBucketType, int maxNumberOfPendingObject, CancellationToken cancellationToken)
        {
            var pendingObjectKeyCollection = new PendingBucketObjectKeyCollection();

            pendingObjectKeyCollection.LastMarker = await this.repository.GetApplicationProperty(lastObjectMarkerKey, cancellationToken);

            var bucketName = this.GetBucketName(sourceBucketType);

            var listObjectResponse = default(ListObjectsResponse);

            var maxLoop     = 100;
            var currentLoop = 0;

            do
            {
                var listObjectRequest = new ListObjectsRequest
                {
                    BucketName = bucketName,
                    MaxKeys    = maxNumberOfPendingObject,
                    Marker     = pendingObjectKeyCollection.LastMarker
                };

                listObjectResponse = await amazonS3.ListObjectsAsync(listObjectRequest, cancellationToken);

                var bucketObjectStatusCollection = await this.GetBucketObjectStatusCollection(sourceBucketType, listObjectResponse.S3Objects, cancellationToken);

                pendingObjectKeyCollection.AddRange(bucketObjectStatusCollection.Where(e => e.Status == (int)BucketObjectStatus.Unknown));

                pendingObjectKeyCollection.IsTruncated = listObjectResponse.IsTruncated;

                if (listObjectResponse.IsTruncated)
                {
                    pendingObjectKeyCollection.LastMarker = listObjectResponse.NextMarker;
                }

                currentLoop += 1;
            } while (
                pendingObjectKeyCollection.Count < maxNumberOfPendingObject &&
                listObjectResponse.S3Objects.Any() &&
                listObjectResponse.IsTruncated &&
                currentLoop < maxLoop);

            return(pendingObjectKeyCollection);
        }
示例#15
0
        public async Task ImportObjectInternalAsync(StockMarket sourceBucketType, string objectKey, char csvSeperator, CancellationToken cancellationToken)
        {
            var objectID = this.encryptionService.GetBucketObjectHash(sourceBucketType, objectKey);

            var bucketName = this.GetBucketName(sourceBucketType);

            var bucketObject = await this.repository.GetItemAsync <BucketObject>(objectID, cancellationToken);

            if (bucketObject == null)
            {
                var objectMetaData = await amazonS3.GetObjectMetadataAsync(bucketName, objectKey, cancellationToken);

                bucketObject = new BucketObject
                {
                    ObjectID                = objectID,
                    ObjectKey               = objectKey,
                    SourceBucketType        = (int)sourceBucketType,
                    Status                  = (int)BucketObjectStatus.Detected,
                    ObjectSize              = objectMetaData.Headers.ContentLength,
                    CurrentStatusErrorCount = 0,
                    CurrentStatusLastError  = null,
                    VersionNumber           = null
                };
            }

            if (bucketObject.Status > (int)BucketObjectStatus.Queued)
            {
                return;
            }

            bucketObject.Status = (int)BucketObjectStatus.Processing;

            await this.repository.SaveItemAsync(bucketObject, cancellationToken);

            try
            {
                var objectStream = await amazonS3.GetObjectStreamAsync(bucketName, objectKey, null, cancellationToken);

                var enumerable = csvConverter.Convert <TradeActivity>(objectStream, csvSeperator);

                using (var bae = new BufferedAsyncEnumerable <TradeActivity>(enumerable, CumulusConstants.DynamoDbBatchWriteSize))
                {
                    while (await bae.MoveNextAsync())
                    {
                        await productService.SaveTraceActivityCollectionAsync(bae.Current, cancellationToken);
                    }
                }

                bucketObject.Status = (int)BucketObjectStatus.Processed;
            }
            catch (Exception exception)
            {
                bucketObject.CurrentStatusLastError = exception.Message;
                bucketObject.CurrentStatusErrorCount++;
                throw;
            }
            finally
            {
                await this.repository.SaveItemAsync(bucketObject, cancellationToken);
            }
        }
示例#16
0
 public override void PurchaseStock(IStock stock, decimal numOfStock)
 {
     StockMarket.Get(stock).Purchase(numOfStock);
 }
示例#17
0
 public void TestStockMarket()
 {
     Assert.Throws <KeyNotFoundException>(() => StockMarket.GetExchangeRates(StockMarketCurrency.Rub));
     Assert.InRange(StockMarket.GetExchangeRates(StockMarketCurrency.Eur), 20, 200);
     Assert.InRange(StockMarket.GetExchangeRates(StockMarketCurrency.Usd), 20, 200);
 }
示例#18
0
        /// <summary>
        /// ��ȡ��Ʊ����
        /// </summary>
        /// <param name="StockCode"></param>
        /// <param name="Market"></param>
        /// <returns></returns>
        public StockType GetStockType(string StockCode, StockMarket Market)
        {
            try
            {
                // �����Ƿ���Ч
                if (StockCode == null || StockCode.Trim().Length != 6)
                    return StockType.Unknown;
                StockCode = StockCode.Trim();
                if (StockCode == "000000")
                    return StockType.Unknown;
                if (Market == StockMarket.Shanghai && (StockCode == "510180" ||
                    StockCode == "510050" || StockCode == "510880"))
                    return StockType.ETF;
                if (Market == StockMarket.Shenzhen && (
                    StockCode == "159901" || StockCode == "159902"))
                    return StockType.ETF;

                // �����������
                switch (Market)
                {
                    case StockMarket.Shenzhen:
                        if (StockCode.StartsWith("00"))
                            return StockType.SZ_A;
                        else if (StockCode.StartsWith("184"))
                            return StockType.SZ_ClosedFund;
                        else if (StockCode.StartsWith("17") || StockCode.StartsWith("18") ||
                           StockCode.StartsWith("1599"))
                            return StockType.SZ_OpenedFund;
                        else if (StockCode.StartsWith("20"))
                            return StockType.SZ_B;
                        else if (StockCode.StartsWith("39"))
                            return StockType.SZ_Index;
                        else if (StockCode.StartsWith("031"))
                            return StockType.SZ_Warrant;
                        else
                            return StockType.SZ_Bond;

                    case StockMarket.Shanghai:
                        if (StockCode.StartsWith("500"))
                            return StockType.SH_ClosedFund;
                        else if (StockCode.StartsWith("510")
                             || StockCode.StartsWith("519"))
                            return StockType.SH_OpenedFund;
                        else if (StockCode.StartsWith("6"))
                            return StockType.SH_A;
                        else if (StockCode.StartsWith("900"))
                            return StockType.SH_B;
                        else if (StockCode.StartsWith("000"))
                            return StockType.SH_Index;
                        else if (StockCode.StartsWith("580"))
                            return StockType.SH_Warrant;
                        else
                            return StockType.SH_Bond;

                    default:	// �Ƿ�����
                        return StockType.Unknown;
                }
            }
            catch
            {
                return StockType.Unknown;
            }
        }
 public void Initialize()
 {
     try
     {
         OrderID = 0;
         UserID = 0;
         OrdType = OrderType.None;
         OrdStatus = OrderStatus.Unknown;
         Side = false;
         StockCode = "";
         Market = StockMarket.Unknown;
         OrderVolume = 0;
         OrderPrice = 0;
         TradePrice = 0;
         Curr = Currency.Unknown;
         OrderDate = Common.MinDateTime;
         UpdatedDate = Common.MinDateTime;
         ExpiredDate = Common.MaxDateTime;
     }
     catch
     { }
 }
示例#20
0
 public void StockMarket_ValueChanged_CallReceived()
 {
     StockMarket.StockNotifications = true;
     StockMarket.ValueChanged(_stock);
     _stock.Received();
 }
示例#21
0
        public string GetBucketObjectHash(StockMarket sourceBucketType, string objectKey)
        {
            var objectKeyMeta = $"{sourceBucketType}_{objectKey}";

            return(new Guid(this.GetHashBytes(objectKeyMeta)).ToStringID());
        }
示例#22
0
        public ActionResult PurchaseStocks(PurchaseStockTrade PurchcaseTrade)
        {
            try
            {
                // get the customer
                AppUser Customer = db.Users.Find(PurchcaseTrade.CustomerProfile.Id);

                if (Customer == null)
                {
                    return(RedirectToAction("Portal", "Home"));
                }

                if (PurchcaseTrade.TradeDate < DateTime.Today || PurchcaseTrade.TradeDate == null)
                {
                    ViewBag.Error = "Date cannot be before today";
                    return(View("PurchaseError"));
                }

                if (PurchcaseTrade.Quantity == 0)
                {
                    ViewBag.Error = "Quantity cannot be 0";
                    return(View("PurchaseError"));
                }
                // Get the stock
                StockMarket SelectedStock = db.StockMarket.Find(PurchcaseTrade.SelectedStock.StockMarketID);

                // Get the total amount
                Decimal decTotal = (PurchcaseTrade.Quantity * SelectedStock.StockPrice);

                // create a new transaction list for the trade
                List <BankingTransaction> TradeTrans = new List <BankingTransaction>();

                // Create a new fee transaction and add it to the list
                BankingTransaction FeeTrans = new BankingTransaction
                {
                    Amount = SelectedStock.Fee,
                    BankingTransactionType = BankingTranactionType.Fee,
                    Description            = ("Fee for purchase of " + SelectedStock.CompanyName),
                    TransactionDate        = (PurchcaseTrade.TradeDate),
                    StockAccount           = Customer.StockAccount.FirstOrDefault(),
                    TransactionDispute     = DisputeStatus.NotDisputed
                };

                TradeTrans.Add(FeeTrans);

                // Make the trade happen
                Trade Trade = new Trade()
                {
                    Amount              = decTotal,
                    Quantity            = PurchcaseTrade.Quantity,
                    Ticker              = SelectedStock.Ticker,
                    TransactionDate     = PurchcaseTrade.TradeDate,
                    PricePerShare       = SelectedStock.StockPrice,
                    TradeType           = TradeType.Buy,
                    StockAccount        = Customer.StockAccount.FirstOrDefault(),
                    StockMarket         = SelectedStock,
                    BankingTransactions = TradeTrans,
                    DisputeMessage      = "None",
                    TransactionDispute  = DisputeStatus.NotDisputed,
                    Description         = "None",
                    CorrectedAmount     = 0
                };

                // Get the customer Savings account
                var SAQ = from sa in db.StockAccount
                          where sa.Customer.Id == Customer.Id
                          select sa;

                StockAccount CustomerStockAccount = SAQ.FirstOrDefault();

                // check the account nulls
                if (PurchcaseTrade.CheckingAccounts != null)
                {
                    // find the account
                    Checking CustomerChecking = db.CheckingAccount.Find(PurchcaseTrade.CheckingAccounts.CheckingID);

                    if (CustomerChecking == null)
                    {
                        return(RedirectToAction("Portal", "Home"));
                    }

                    // take the money from the account
                    if (CustomerChecking.Balance - decTotal >= 0)
                    {
                        // Check to see if the cash balance is enough for the fee
                        if (db.StockAccount.Find(Customer.StockAccount.FirstOrDefault().StockAccountID).CashBalance < SelectedStock.Fee)
                        {
                            ViewBag.Error = "Fee was greater than Stock Cash Balance";
                            return(View("PurchaseError"));
                        }

                        // create a list to hold the checking account
                        List <Checking> CheckingList = new List <Checking>();
                        CheckingList.Add(CustomerChecking);

                        //Create a new transaction
                        BankingTransaction CheckingTrans = new BankingTransaction
                        {
                            Amount = decTotal,
                            BankingTransactionType = BankingTranactionType.Withdrawl,
                            CheckingAccount        = CheckingList,
                            Description            = ("Stock Purchase - Stock Account " + Customer.StockAccount.FirstOrDefault().AccountNumber.ToString()),
                            TransactionDate        = PurchcaseTrade.TradeDate,
                            Trade = Trade,
                            TransactionDispute = DisputeStatus.NotDisputed
                        };

                        // add the stuff to the database
                        db.BankingTransaction.Add(FeeTrans);
                        db.SaveChanges();

                        db.Trades.Add(Trade);
                        db.SaveChanges();

                        // Take the money out
                        db.CheckingAccount.Find(CustomerChecking.CheckingID).Balance -= decTotal;

                        // take out the fee
                        CustomerStockAccount.CashBalance -= SelectedStock.Fee;

                        // take out the fee
                        CustomerStockAccount.TradingFee += SelectedStock.Fee;

                        db.Entry(CustomerStockAccount).State = System.Data.Entity.EntityState.Modified;
                        db.BankingTransaction.Add(CheckingTrans);
                        db.SaveChanges();
                    }

                    // HACK
                    else
                    {
                        ViewBag.Error = "Not Enough Money in Account to Purchase the Stocks";
                        return(View("PurchaseError"));
                    }


                    // Any further changes
                }
                else if (PurchcaseTrade.SavingsAccount != null)
                {
                    // Get the customer Savings account
                    Saving CustomerSavings = db.SavingsAccount.Find(PurchcaseTrade.SavingsAccount.SavingID);

                    // take the money from the account
                    if (CustomerSavings.Balance - decTotal >= 0)
                    {
                        // Check to see if the cash balance is enough for the fee
                        if (db.StockAccount.Find(Customer.StockAccount.FirstOrDefault().StockAccountID).CashBalance < SelectedStock.Fee)
                        {
                            ViewBag.Error = "Fee was greater than Stock Cash Balance";
                            return(View("PurchaseError"));
                        }

                        // create a list to hold the checking account
                        List <Saving> SavingsList = new List <Saving>();
                        SavingsList.Add(CustomerSavings);

                        //Create a new transaction
                        BankingTransaction SavingsTrans = new BankingTransaction
                        {
                            Amount = decTotal,
                            BankingTransactionType = BankingTranactionType.Withdrawl,
                            SavingsAccount         = SavingsList,
                            Description            = ("Stock Purchase - Stock Account " + Customer.StockAccount.FirstOrDefault().AccountNumber.ToString()),
                            TransactionDate        = PurchcaseTrade.TradeDate,
                            Trade = Trade,
                            TransactionDispute = DisputeStatus.NotDisputed
                        };

                        // add the stuff to the database
                        db.BankingTransaction.Add(FeeTrans);
                        db.SaveChanges();

                        db.Trades.Add(Trade);
                        db.SaveChanges();

                        // Take the money out
                        db.SavingsAccount.Find(CustomerSavings.SavingID).Balance -= decTotal;

                        // take out the fee
                        CustomerStockAccount.CashBalance -= SelectedStock.Fee;

                        // take out the fee
                        CustomerStockAccount.TradingFee += SelectedStock.Fee;

                        db.Entry(CustomerStockAccount).State = System.Data.Entity.EntityState.Modified;
                        db.BankingTransaction.Add(SavingsTrans);
                        db.SaveChanges();
                    }

                    // HACK
                    else
                    {
                        ViewBag.Error = "Not Enough Money in Account to Purchase the Stocks";
                        return(View("PurchaseError"));
                    }
                }
                else if (PurchcaseTrade.AccountStock != null)
                {
                    // take the money from the account
                    if (CustomerStockAccount.CashBalance - decTotal >= 0)
                    {
                        // Check to see if the cash balance is enough for the fee
                        if (db.StockAccount.Find(Customer.StockAccount.FirstOrDefault().StockAccountID).CashBalance < SelectedStock.Fee)
                        {
                            ViewBag.Error = "Fee was greater than Stock Cash Balance";
                            return(View("PurchaseError"));
                        }

                        // create a list to hold the checking account
                        List <StockAccount> StockAccountList = new List <StockAccount>();
                        StockAccountList.Add(CustomerStockAccount);

                        //Create a new transaction
                        BankingTransaction StocksTrans = new BankingTransaction()
                        {
                            Amount = decTotal,
                            BankingTransactionType = BankingTranactionType.Withdrawl,
                            StockAccount           = CustomerStockAccount,
                            Description            = ("Stock Purchase - Stock Account " + Customer.StockAccount.FirstOrDefault().AccountNumber.ToString()),
                            TransactionDate        = PurchcaseTrade.TradeDate,
                            Trade = Trade,
                            TransactionDispute = DisputeStatus.NotDisputed
                        };

                        // add the stuff to the database
                        db.BankingTransaction.Add(FeeTrans);
                        db.SaveChanges();

                        db.Trades.Add(Trade);
                        db.SaveChanges();

                        // Take the money out
                        CustomerStockAccount.CashBalance -= decTotal;

                        // take out the fee
                        CustomerStockAccount.CashBalance -= SelectedStock.Fee;

                        // take out the fee
                        CustomerStockAccount.TradingFee += SelectedStock.Fee;

                        db.Entry(CustomerStockAccount).State = System.Data.Entity.EntityState.Modified;
                        db.BankingTransaction.Add(StocksTrans);
                        db.SaveChanges();
                    }

                    // HACK
                    else
                    {
                        ViewBag.Error = "Not Enough Money in Account to Purchase the Stocks";
                        return(View("PurchaseError"));
                    }
                }

                else
                {
                    return(HttpNotFound());
                }

                // Add the stuff to the database
                // check to see if the porfolio is balanced
                BalancedPortfolio.CheckBalanced(db, Customer);

                return(View("PurchaseConfirmation"));
            }
            catch (Exception e)
            {
                ViewBag.Error = "An unknown error occured";
                return(View("PurchaseError"));
            }
        }
示例#23
0
        // GET: /StockTrades/PurchaseStocks
        // Returns page to purchase stocks
        public ActionResult PurchaseStocks(int?StockID, int?Choice, int?AccountID)
        {
            // Check to see if any IDs are null
            if (StockID == null || Choice == null || AccountID == null)
            {
                return(HttpNotFound());
            }

            // Get the users account
            // Query the Database for the logged in user
            var CustomerQuery = from c in db.Users
                                where c.UserName == User.Identity.Name
                                select c;
            // Get the Customer
            AppUser customer = CustomerQuery.FirstOrDefault();

            //Return frozen view if no go
            if (customer.ActiveStatus == false)
            {
                return(View("Frozen"));
            }

            // Get the Selected Stock
            StockMarket SelectedStock = db.StockMarket.Find(StockID);

            // Create a new model instance
            PurchaseStockTrade StockTrade = new PurchaseStockTrade
            {
                CustomerProfile = customer,
                SelectedStock   = SelectedStock
            };

            switch (Choice)
            {
            case 1:
                // Find the Checking Account
                Checking SelectedChecking = db.CheckingAccount.Find(AccountID);

                // Add to model
                StockTrade.CheckingAccounts = SelectedChecking;

                break;

            case 2:
                // Find the savings account
                Saving SelectedSavings = db.SavingsAccount.Find(AccountID);

                StockTrade.SavingsAccount = SelectedSavings;

                break;

            case 3:
                // Find the portfolio
                StockAccount SelectedStockAccount = db.StockAccount.Find(AccountID);

                StockTrade.AccountStock = SelectedStockAccount;

                break;

            default:
                return(HttpNotFound());
            }

            return(View(StockTrade));
        }
 private void Awake()
 {
     market = GetComponentInParent <StockMarket>();
     player = GetComponentInParent <Player>();
     player.OnAccountChange += HandleAccountChange;
 }
示例#25
0
        /// <summary>
        /// �ж��Ƿ��ܹ���
        /// </summary>
        /// <param name="UserID"></param>
        /// <param name="StockCode"></param>
        /// <param name="Market"></param>
        /// <param name="Curr"></param>
        /// <param name="WannaBuy"></param>
        /// <returns></returns>
        public bool CanBuy(int UserID, string StockCode, StockMarket Market, Currency Curr, double WannaBuy)
        {
            try
            {
                if (UserID <= 0 || StockCode == null || StockCode.Trim().Length != 6 || Market == StockMarket.Unknown)
                    return false;
                if (!mapUserFund.ContainsKey(UserID))
                    return false;
                if (!mapUserFund[UserID].ContainsKey((byte)Curr))
                    return false;
                double dValue = 0;
                lock (mapUserOrders)
                {
                    foreach (object objKey in mapUserOrders.Keys)
                    {
                        if (objKey == null)
                            continue;
                        int nOrderID = Convert.ToInt32(objKey);
                        if (!mapUserOrders.ContainsKey(nOrderID))
                            continue;
                        if (mapUserOrders[nOrderID].UserID == UserID
                            && string.Compare(StockCode.Trim(),
                            mapUserOrders[nOrderID].StockCode.Trim()) == 0
                            && Market == mapUserOrders[nOrderID].Market && mapUserOrders[nOrderID].Side
                            && (mapUserOrders[nOrderID].OrdStatus == OrderStatus.Cancelling
                            || mapUserOrders[nOrderID].OrdStatus == OrderStatus.Waiting)
                            && Curr == mapUserOrders[nOrderID].Curr)
                            dValue += (mapUserOrders[nOrderID].OrderPrice * mapUserOrders[nOrderID].OrderVolume * (1 + defaultBuyTax));
                    }
                }

                Show2003DBFRecord SHRate = new Show2003DBFRecord(); SHRate.Clear();
                SjshqDBFRecord SZRate = new SjshqDBFRecord(); SZRate.Clear();
                double PreClose = 0;
                if (Common.stkQuotation.GetStkRate(StockCode.Trim(), Market, out SHRate, out SZRate))
                {
                    switch (Market)
                    {
                        case StockMarket.Shanghai:
                            PreClose = SHRate.PreClosePrice;
                            break;
                        case StockMarket.Shenzhen:
                            PreClose = SZRate.PreClosePrice;
                            break;
                    }
                }

                lock (mapUserStocks)
                {
                    if (mapUserStocks.ContainsKey(UserID))
                    {
                        foreach (UserStocks data in mapUserStocks[UserID])
                        {
                            if (data.UserID == UserID
                                && string.Compare(StockCode.Trim(),
                                data.StockCode.Trim()) == 0
                                && Market == data.Market
                                && Curr == data.Curr)
                            {
                                if (PreClose >= 0.001)
                                    dValue += (PreClose * data.Volume);
                                else
                                    dValue += (data.AveragePrice * data.Volume);
                            }
                        }
                    }
                }
                double dMax = mapUserFund[UserID][(byte)Curr].Wealth;
                if (defaultSingleStockRate > 0)
                    dMax *= defaultSingleStockRate;
                if (dValue + WannaBuy > dMax)
                    return false;
                else
                    return true;
            }
            catch
            {
                return false;
            }
        }
示例#26
0
 public ValueChangeReposirory(StockMarket dbCtx)
 {
     ctx = dbCtx;
 }
示例#27
0
 public override decimal GetCurrentStockValue(IStock stock)
 {
     return(StockMarket.Get(stock).CurrentValue);
 }
示例#28
0
 /// <summary>
 /// ��ȡָ����Ʊ�Ŀ������
 /// </summary>
 /// <param name="UserID"></param>
 /// <param name="StockCode"></param>
 /// <param name="Market"></param>
 /// <returns></returns>
 public int GetSellableStockVolume(int UserID, string StockCode, StockMarket Market)
 {
     try
     {
         if (UserID <= 0 || StockCode == null || StockCode.Trim().Length != 6 || Market == StockMarket.Unknown)
             return -1;
         if (!mapUserFund.ContainsKey(UserID))
             return -1;
         int nVolume = 0;
         lock (mapUserStocks)
         {
             if (!mapUserStocks.ContainsKey(UserID))
                 return -1;
             foreach (UserStocks stk in mapUserStocks[UserID])
             {
                 if (string.Compare(StockCode.Trim(),
                     stk.StockCode.Trim()) == 0
                     && Market == stk.Market
                     && stk.Sellable)
                 {
                     nVolume += stk.Volume;
                 }
             }
         }
         lock (mapUserOrders)
         {
             int nKey = 0;
             foreach (object objKey in mapUserOrders.Keys)
             {
                 if (objKey == null)
                     continue;
                 nKey = Convert.ToInt32(objKey);
                 if (mapUserOrders[nKey].UserID == UserID
                     && string.Compare(StockCode.Trim(),
                     mapUserOrders[nKey].StockCode.Trim()) == 0
                     && Market == mapUserOrders[nKey].Market
                     && (mapUserOrders[nKey].OrdStatus == OrderStatus.Waiting
                     || mapUserOrders[nKey].OrdStatus == OrderStatus.Cancelling)
                     && !mapUserOrders[nKey].Side)
                 {
                     nVolume -= mapUserOrders[nKey].OrderVolume;
                 }
             }
         }
         return nVolume;
     }
     catch
     {
         return -1;
     }
 }
示例#29
0
 public BaseStockExchange(StockMarket stockMarket)
 {
     StockMarket = stockMarket;
 }
示例#30
0
 public TransactionRepository(StockMarket dbCtx)
 {
     ctx = dbCtx;
 }
示例#31
0
 public StockExchange(StockMarket stockMarket)
     : base(stockMarket)
 {
 }
示例#32
0
 public LoggedBrokerRepository(StockMarket dbCtx)
 {
     ctx = dbCtx;
 }
示例#33
0
        public ActionResult SellStocks(SellStocksTrade Sale)
        {
            // Get the Customer
            // Query the Database for the logged in user
            var CustomerQuery = from c in db.Users
                                where c.UserName == User.Identity.Name
                                select c;
            // Get the Customer
            AppUser customer = CustomerQuery.FirstOrDefault();

            //Return frozen view if no go
            if (customer.ActiveStatus == false)
            {
                return(View("Frozen"));
            }

            // Get the original trade
            Trade OriginalTrade = db.Trades.Find(Sale.TradeID);

            // Get the Stock that is being sold
            StockMarket StockSale = db.StockMarket.Find(Sale.StockMarketID);

            // Get the Stock Account
            StockAccount CustomerStockAccount = db.StockAccount.Find(Sale.StockAccountID);

            // create a new transaction list for the trade
            List <BankingTransaction> TradeTrans = new List <BankingTransaction>();

            // Check the dates
            if (Sale.SaleDate < OriginalTrade.TransactionDate)
            {
                ViewBag.Error = "Cannot sell before purchase";
                return(View("SaleError"));
            }

            if (Sale.QuantitySold == 0)
            {
                ViewBag.Error = "Cannot sell with zero quantity";
                return(View("SaleError"));
            }

            // String for the description
            String Description = ($"Sale of {StockSale.CompanyName}, for {Sale.QuantitySold} shares, with initial price of {OriginalTrade.PricePerShare}, current price of {StockSale.StockPrice}, and a gain/loss of {Sale.Profit}");

            // Sale Amount
            Decimal SaleAmount = (Sale.QuantitySold * StockSale.StockPrice);

            // Create a new fee transaction and add it to the list
            BankingTransaction FeeTrans = new BankingTransaction
            {
                Amount = StockSale.Fee,
                BankingTransactionType = BankingTranactionType.Fee,
                Description            = ("Fee for sale of " + StockSale.CompanyName),
                StockAccount           = CustomerStockAccount,
                TransactionDate        = Sale.SaleDate,
                TransactionDispute     = DisputeStatus.NotDisputed
            };

            // Add the transaction to the list
            TradeTrans.Add(FeeTrans);

            // Make the trade happen
            Trade SaleTrade = new Trade()
            {
                TradeType           = TradeType.Sell,
                Amount              = (Sale.QuantitySold * StockSale.StockPrice),
                PricePerShare       = StockSale.StockPrice,
                Ticker              = StockSale.Ticker,
                Quantity            = Sale.QuantitySold,
                TransactionDate     = Sale.SaleDate,
                Description         = Description,
                StockMarket         = StockSale,
                StockAccount        = CustomerStockAccount,
                BankingTransactions = TradeTrans,
                TransactionDispute  = DisputeStatus.NotDisputed
            };

            // Create a new transaction for the actual sale
            BankingTransaction SaleTrans = new BankingTransaction
            {
                Amount = SaleAmount,
                BankingTransactionType = BankingTranactionType.Deposit,
                Description            = Description,
                StockAccount           = CustomerStockAccount,
                Trade              = SaleTrade,
                TransactionDate    = Sale.SaleDate,
                TransactionDispute = DisputeStatus.NotDisputed
            };

            // Add the transactions and the trades the the db
            db.BankingTransaction.Add(FeeTrans);
            db.SaveChanges();

            db.Trades.Add(SaleTrade);
            db.SaveChanges();

            db.BankingTransaction.Add(SaleTrans);
            db.SaveChanges();

            // Update the stock account

            // Take out the fee
            CustomerStockAccount.CashBalance -= Sale.Fee;

            // Add the fee to the account
            CustomerStockAccount.TradingFee += Sale.Fee;

            // Add/Subtract the profit
            CustomerStockAccount.CashBalance += Sale.Profit;

            // Update the Database
            db.Entry(CustomerStockAccount).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();


            // Remove the shares from the account

            // Check to see if there is any stock left
            // If there is no stock left then we need to remove the original buy trade
            if (OriginalTrade.Quantity - Sale.QuantitySold == 0)
            {
                // Clear the associated foriegn keys
                OriginalTrade.BankingTransactions.Clear();

                // Remove the original trade
                db.Trades.Remove(OriginalTrade);
            }

            // If the original trade quantity is not zero
            else
            {
                // update the quantity
                OriginalTrade.Quantity -= Sale.QuantitySold;

                // update the database
                db.Entry(OriginalTrade).State = System.Data.Entity.EntityState.Modified;
            }

            // Save the changes
            db.SaveChanges();

            // Check to see if the account is balanced
            BalancedPortfolio.CheckBalanced(db, customer);

            // Return users to the stock account details page
            return(RedirectToAction("Details", "StockAccounts"));
        }
示例#34
0
 [Test] // Inconclusive - Reason: The method required user input from console, very difficult to test.
 public void StockMarket_RefreshStocks_StockReceivedInstabilityCall()
 {
     StockMarket.Stocks.Add(_stock);
     StockMarket.RefreshStocks();
     _stock.Received().Instability();
 }
示例#35
0
 /// <summary>
 /// Changes a single Stock inside the Stockmarket
 /// </summary>
 /// <param name="stockMarket">The StockMarket to change</param>
 /// <param name="amount">The amount of change</param>
 public static void SingleChange(StockMarket stockMarket, float amount)
 {
     stockMarket.Value += amount;
 }
 public void Initialize()
 {
     try
     {
         UserID = 0;
         StockCode = "";
         Market = StockMarket.Unknown;
         Volume = 0;
         AveragePrice = 0;
         Curr = Currency.Unknown;
         Sellable = false;
     }
     catch
     { }
 }
示例#37
0
 private void Awake()
 {
     market = GetComponentInParent <StockMarket>();
     market.OnActiveStockProcessed += HandleActiveStockChanged;
     market.OnActiveStockCleared   += HandleActiveStockCleared;
 }