Example #1
0
 /// <summary>
 /// 更新指令
 /// </summary>
 /// <param name="command"></param>
 /// <returns></returns>
 public static string Update(Command command)
 {
     try
     {
         MongoDBHelper <Command> mongo = new MongoDBHelper <Command>();
         var query = new QueryDocument();
         query.Add("_id", command._id);
         var update = new UpdateDocument();
         update.Add("CommandState", command.CommandState);
         update.Add("AnswerDate", command.AnswerDate);
         update.Add("AnswerData", command.AnswerData);
         update.Add("ControlCode", command.ControlCode);
         update.Add("DataCommand", command.DataCommand);
         update.Add("DataLength", command.DataLength);
         update.Add("TaskID", command.TaskID);
         update.Add("Identification", command.Identification);
         update.Add("Order", command.Order);
         mongo.Update(CollectionNameDefine.CommandCollectionName, query, update);
     }
     catch (Exception e)
     {
         return(e.Message);
     }
     return("");
 }
Example #2
0
        public bool Update(string collectionName, IDictionary <string, object> condition, IDictionary <string, object> forUpdate)
        {
            var collection = GetCollection(collectionName);

            if (collection == null)
            {
                throw new InvalidOperationException(string.Format("fail to get collection [{0}]", collectionName));
            }

            if (condition == null || forUpdate == null)
            {
                return(false);
            }

            if (!condition.Any() || !forUpdate.Any())
            {
                return(false);
            }

            var query = new QueryDocument();

            query.Add(condition, condition.Keys);

            var update = new UpdateDocument();

            var setDictionary = new Dictionary <string, object>();

            foreach (var updatePair in forUpdate)
            {
                var updateDictionary = updatePair.Value as IDictionary <string, object>;

                if (updateDictionary != null)
                {
                    var pushDoc = new BsonDocument(updateDictionary);

                    update.Add("$push", new BsonDocument().Add(updatePair.Key, pushDoc));
                }
                else
                {
                    setDictionary.Add(updatePair.Key, updatePair.Value);
                }
            }

            if (setDictionary.Any())
            {
                var setDoc = new BsonDocument(setDictionary);

                update.Add("$set", setDoc);
            }

            collection.Update(query, update);

            return(true);
        }
    static void Main(string[] args)
    {
        // TO DO: Add your code here
        MongoClient   client   = new MongoClient("mongodb://localhost:27017");
        MongoServer   server   = client.GetServer();
        MongoDatabase database = server.GetDatabase("FinanceLast");
        MongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>("RandomTradeRecords");

        foreach (BsonDocument aRecord in collection.FindAll())
        {
            int traded    = 0;
            int oriInside = 0;
            if (aRecord["HoldingPeriod"] == 1)
            {
                oriInside = 0;
            }
            else if (aRecord["HoldingPeriod"] > 1)
            {
                oriInside = 1;
            }
            traded = Math.Abs((int)aRecord["Inside"] - oriInside);
            QueryDocument  query  = new QueryDocument(new BsonElement("_id", aRecord["_id"]));
            UpdateDocument update = new UpdateDocument();
            QueryDocument  query2 = new QueryDocument();
            query2.Add(new BsonElement("OriInside", oriInside));
            query2.Add(new BsonElement("Traded", traded));
            update.Add(new BsonElement("$set", query2));
            collection.Update(query, update);
        }
    }
    public static void UpdateNextTradeDate(string _id, string nextTradeDateString)
    {
        QueryDocument  query  = new QueryDocument(new BsonElement("_id", new BsonObjectId(_id)));
        UpdateDocument update = new UpdateDocument();

        update.Add(new BsonElement("$set", new BsonDocument(new BsonElement("NextTradeDate", nextTradeDateString))));
        collection.Update(query, update);
    }
Example #5
0
    public static void UpdateClosedRecord(string dateString, string symbol, int holdingPeriod, float profit)
    {
        BsonElement[] eleArray = new BsonElement[3];
        eleArray[0] = new BsonElement("Symbol", symbol);
        eleArray[1] = new BsonElement("Date", dateString);
        eleArray[2] = new BsonElement("Closed", false);
        QueryDocument  query  = new QueryDocument(eleArray);
        UpdateDocument update = new UpdateDocument();

        BsonElement[] eleArray1 = new BsonElement[3];
        eleArray1[0] = new BsonElement("HoldingPeriod", holdingPeriod);
        eleArray1[1] = new BsonElement("Profit", profit);
        eleArray1[2] = new BsonElement("Closed", true);
        update.Add(new BsonElement("$set", new BsonDocument(eleArray1)));
        collection.Update(query, update);
    }
Example #6
0
 public void Update()
 {
     MongoDBHelper<File> mongo = new MongoDBHelper<File>();
     var query = new QueryDocument();
     query.Add("_id", this._id);
     var update = new UpdateDocument();
     update.Add("MAC", this.MAC);
     update.Add("FileName", this.FileName);
     update.Add("Length", this.Length);
     update.Add("State", this.State);
     update.Add("TotalSeg", this.TotalSeg);
     update.Add("segIndex", this.segIndex);
     update.Add("Data", this.Data);
     mongo.Update(LCD.FileCollectionName, query, update);
 }
Example #7
0
        private void btn_test_Click(object sender, EventArgs e)
        {
            MongoCollection collection = MongoHelper.base_db.GetCollection("user");
            QueryDocument   query_doc  = MongoHelper.get_query_from_str("{}");
            UpdateDocument  update_doc = new UpdateDocument();

            collection.Update(query_doc, update_doc);
            update_doc.Add("$set", new BsonDocument()
            {
                { "test", "test" }
            });

            QueryDocument doc_query = new QueryDocument()
            {
                { "", "" }, { "", "" }
            };
        }
Example #8
0
        public string TaskCompile(Task task)
        {
            MongoDBHelper <Task> mongo = new MongoDBHelper <Task>();
            var query = new QueryDocument();

            query.Add("_id", task._id);
            var update = new UpdateDocument();

            update.Add("TaskState", task.TaskState);
            update.Add("Finished", QuShi.getDate());
            update.Add("MeterMac", task.MeterMac);
            update.Add("TaskDate", task.TaskDate);
            update.Add("TaskID", task.TaskID);
            update.Add("TaskType", task.TaskType);
            update.Add("TaskSource", task.TaskSource == null ?"":task.TaskSource);
            //update.Add("CommandList", task.CommandList);
            return(mongo.Update(CollectionNameDefine.TaskCollectionName, query, update));
        }
Example #9
0
        public string UpdateMeter(Meter meter)
        {
            MongoDBHelper <Meter> mongo = new MongoDBHelper <Meter>();
            var query = new QueryDocument();

            query.Add("_id", meter._id);
            var update = new UpdateDocument();

            update.Add("MeterID", meter.MeterID);
            update.Add("UserID", meter.UserID == null?"":meter.UserID);
            update.Add("Mac", meter.Mac);
            update.Add("MKeyVer", meter.MKeyVer);
            update.Add("Key", meter.Key);
            update.Add("MeterType", meter.MeterType);
            update.Add("TotalAmount", (double)meter.TotalAmount);
            update.Add("TotalTopUp", (double)meter.TotalTopUp);
            update.Add("SettlementType", meter.SettlementType);
            update.Add("SettlementDay", meter.SettlementDay);
            update.Add("SettlementMonth", meter.SettlementMonth);

            update.Add("ValveState", meter.ValveState);
            update.Add("MeterState", meter.MeterState);
            update.Add("PriceCheck", meter.PriceCheck);
            update.Add("LastTopUpSer", meter.LastTopUpSer);
            update.Add("LastJiaoShiDate", meter.LastJiaoShiDate == null ? DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") : meter.LastJiaoShiDate);

            update.Add("IsUsedLadder", meter.IsUsedLadder);
            update.Add("Ladder", meter.Ladder);
            update.Add("Price1", (double)meter.Price1);
            update.Add("Price2", (double)meter.Price2);
            update.Add("Price3", (double)meter.Price3);
            update.Add("Price4", (double)meter.Price4);
            update.Add("Price5", (double)meter.Price5);
            update.Add("Gas1", (double)meter.Gas1);
            update.Add("Gas2", (double)meter.Gas2);
            update.Add("Gas3", (double)meter.Gas3);
            update.Add("Gas4", (double)meter.Gas4);
            update.Add("LastSettlementAmount", (double)meter.LastSettlementAmount);
            update.Add("LastTotal", (double)meter.LastTotal);

            //update.Add("MeterType", meter.MeterType);
            update.Add("NextSettlementPointGas", (double)meter.NextSettlementPointGas);//下一个结算点气量
            update.Add("CurrentLadder", meter.CurrentLadder);
            update.Add("CurrentPrice", (double)meter.CurrentPrice);
            update.Add("LastGasPoint", (double)meter.LastGasPoint);
            update.Add("CurrentBalance", (double)meter.CurrentBalance);
            update.Add("LJMoney", (double)meter.LJMoney);
            update.Add("SettlementDateTime", meter.SettlementDateTime == null ? "":meter.SettlementDateTime);
            update.Add("IsDianHuo", meter.IsDianHuo);
            update.Add("IsPricing", meter.IsPricing);
            update.Add("BillID", meter.BillID);
            update.Add("TiaoJiaPointGas", (double)meter.TiaoJiaPointGas);

            if (meter.PricingPlan != null)
            {
                MongoDB.Bson.BsonDocument b = new MongoDB.Bson.BsonDocument();
                b.Add("IsUsedLadder", meter.PricingPlan.IsUsedLadder);
                b.Add("Ladder", meter.PricingPlan.Ladder);
                b.Add("Price1", (double)meter.PricingPlan.Price1);
                b.Add("Gas1", (double)meter.PricingPlan.Gas1);
                b.Add("Price2", (double)meter.PricingPlan.Price2);
                b.Add("Gas2", (double)meter.PricingPlan.Gas2);
                b.Add("Price3", (double)meter.PricingPlan.Price3);
                b.Add("Gas3", (double)meter.PricingPlan.Gas3);
                b.Add("Price4", (double)meter.PricingPlan.Price4);
                b.Add("Gas4", (double)meter.PricingPlan.Gas4);
                b.Add("Price5", (double)meter.PricingPlan.Price5);
                b.Add("MeterType", meter.PricingPlan.MeterType);
                b.Add("UseDate", meter.PricingPlan.UseDate);
                update.Add("PricingPlan", b);
            }
            mongo.Update(CollectionNameDefine.MeterCollectionName, query, update);
            return("");
        }
Example #10
0
        public void Update()
        {
            MSimulator simulator             = this;
            MongoDBHelper <MSimulator> mongo = new MongoDBHelper <MSimulator>();
            var query = new QueryDocument();

            query.Add("_id", simulator._id);
            var update = new UpdateDocument();

            update.Add("Mac", this.Mac);
            update.Add("Key", simulator.Key);
            update.Add("MKeyVer", simulator.MKeyVer);
            update.Add("周期", simulator.周期);
            update.Add("PriceCheck", simulator.PriceCheck);
            update.Add("ValveState", simulator.ValveState);
            update.Add("TotalAmount", simulator.TotalAmount.ToString("0.0000"));
            update.Add("MeterState", simulator.MeterState == null ? "0" : simulator.MeterState);
            update.Add("MeterType", simulator.MeterType);
            update.Add("TotalTopUp", (double)simulator.TotalTopUp);
            update.Add("hostname", simulator.hostname);
            update.Add("port", simulator.port);
            update.Add("SettlementType", simulator.SettlementType == null ? "00" : simulator.SettlementType);
            update.Add("SettlementDay", simulator.SettlementDay);
            update.Add("SettlementMonth", simulator.SettlementMonth);

            update.Add("IsUsedLadder", simulator.IsUsedLadder);
            update.Add("Ladder", simulator.Ladder);
            update.Add("Price1", (double)simulator.Price1);
            update.Add("Gas1", (double)simulator.Gas1);
            update.Add("Price2", (double)simulator.Price2);
            update.Add("Gas2", (double)simulator.Gas2);
            update.Add("Price3", (double)simulator.Price3);
            update.Add("Gas3", (double)simulator.Gas3);
            update.Add("Price4", (double)simulator.Price4);
            update.Add("Gas4", (double)simulator.Gas4);
            update.Add("Price5", (double)simulator.Price5);

            update.Add("LastSettlementAmount", (double)simulator.LastSettlementAmount);
            update.Add("LastTotal", (double)simulator.LastTotal);
            update.Add("CurrentBalance", (double)simulator.CurrentBalance);
            update.Add("出厂状态", simulator.出厂状态);

            update.Add("NextSettlementPointGas", (double)simulator.NextSettlementPointGas);//下一个结算点气量
            update.Add("CurrentLadder", simulator.CurrentLadder);
            update.Add("CurrentPrice", (double)simulator.CurrentPrice);
            update.Add("LastGasPoint", (double)simulator.LastGasPoint);
            update.Add("SettlementDateTime", simulator.SettlementDateTime);



            //if (this.PricingPlan != null)
            //{
            //    MongoDB.Bson.BsonDocument b = new MongoDB.Bson.BsonDocument();
            //    b.Add("IsUsedLadder", this.PricingPlan.IsUsedLadder);
            //    b.Add("Ladder", this.PricingPlan.Ladder);
            //    b.Add("Price1", (double)this.PricingPlan.Price1);
            //    b.Add("Gas1", (double)this.PricingPlan.Gas1);
            //    b.Add("Price2", (double)this.PricingPlan.Price2);
            //    b.Add("Gas2", (double)this.PricingPlan.Gas2);
            //    b.Add("Price3", (double)this.PricingPlan.Price3);
            //    b.Add("Gas3", (double)this.PricingPlan.Gas3);
            //    b.Add("Price4", (double)this.PricingPlan.Price4);
            //    b.Add("Gas4", (double)this.PricingPlan.Gas4);
            //    b.Add("Price5", (double)this.PricingPlan.Price5);
            //    b.Add("MeterType", this.PricingPlan.MeterType);
            //    b.Add("UseDate", this.PricingPlan.UseDate);

            //    update.Add("PricingPlan", b);
            //}

            mongo.Update(TaskCollectionName, query, update);
            if (this.OnJiliang != null)
            {
                this.OnJiliang(this);
            }
        }
        /// <summary>
        /// This method stores a burrito.
        /// </summary>
        /// <param name="b">The burrito object to store</param>
        /// <returns>Success/Failure</returns>
        public Boolean storeBurrito(Burrito b)
        {
            dLog.Info("Entering method storeBurrito | ID: " + b.id);
            Boolean result = false;

            try
            {
                MongoServer   server = MongoServer.Create();
                MongoDatabase db     = server.GetDatabase("neatoBurrito");
                //MongoCredentials credentials = new MongoCredentials("username", "password");
                //MongoDatabase salaries = server.GetDatabase("salaries", credentials);

                using (server.RequestStart(db))
                {
                    MongoCollection <BsonDocument> coll = db.GetCollection("burrito");
                    var query = new QueryDocument("id", b.id);

                    dLog.Debug("Finding if burrito exists");
                    BsonDocument myDoc = coll.FindOne(query);

                    query.Add("beef", b.Beef);
                    query.Add("blackBeans", b.BlackBeans);
                    query.Add("brownRice", b.BrownRice);
                    query.Add("chicken", b.Chicken);
                    query.Add("chiliTortilla", b.ChiliTortilla);
                    query.Add("cucumber", b.Cucumber);
                    query.Add("flourTortilla", b.FlourTortilla);
                    query.Add("guacamole", b.Guacamole);
                    query.Add("herbGarlicTortilla", b.HerbGarlicTortilla);
                    query.Add("hummus", b.Hummus);
                    query.Add("jalapenoCheddarTortilla", b.JalapenoCheddarTortilla);
                    query.Add("jalapenos", b.Jalapenos);
                    query.Add("lettuce", b.Lettuce);
                    query.Add("onion", b.Onion);
                    query.Add("orderID", b.orderID);
                    query.Add("pintoBeans", b.PintoBeans);
                    query.Add("price", b.Price.ToString());
                    query.Add("salsaPico", b.SalsaPico);
                    query.Add("salsaSpecial", b.SalsaSpecial);
                    query.Add("salsaVerde", b.SalsaVerde);
                    query.Add("tomatoBasilTortilla", b.TomatoBasilTortilla);
                    query.Add("tomatoes", b.Tomatoes);
                    query.Add("wheatTortilla", b.WheatTortilla);
                    query.Add("whiteRice", b.WhiteRice);

                    //ensure we were passed a valid object before attempting to write
                    if (myDoc == null)
                    {
                        dLog.Debug("Inserting burrito");
                        coll.Insert(query);

                        result = true;
                    }
                    else
                    {
                        var update = new UpdateDocument();
                        update.Add(query.ToBsonDocument());
                        dLog.Debug("Updating burrito");
                        dLog.Debug("myDoc: " + myDoc.ToString());
                        dLog.Debug("update Query: " + update.ToString());

                        SafeModeResult wr = coll.Update(new QueryDocument("id", b.id), update, SafeMode.True);

                        dLog.Debug("SafeModeResult: " + wr.Ok);
                        if (wr.LastErrorMessage == null && wr.Ok)
                        {
                            result = true;
                        }
                        else
                        {
                            dLog.Debug("SafeModeResult: " + wr.LastErrorMessage);
                        }
                    }
                }
            }
            catch (Exception e2)
            {
                dLog.Error("Exception in storeBurrito: " + e2.Message);
            }
            finally
            {
                //using statement above already calls RequestDone()
            }

            return(result);
        }
        public void RequestAddFriend(string ownerUsername, string friendUsername, string remark, string groupName, string message,
                                     RequestAddFriendUpdateFlags flags)
        {
            var db         = GetDatabase();
            var collection = db.GetCollection("friend_request");
            var queryDoc   = new QueryDocument();

            queryDoc.Add("OwnerUsername", ownerUsername.ToLower());
            queryDoc.Add("FriendUsername", friendUsername.ToLower());

            var cur = collection.Find(queryDoc);

            cur.Limit = 1;

            UpdateDocument updateDoc = new UpdateDocument();

            if (cur.Size() > 0)
            {
                foreach (var item in cur)
                {
                    updateDoc.Add(item);
                }
            }
            else
            {
                updateDoc.Add("OwnerUsername", ownerUsername.ToLower());
                updateDoc.Add("FriendUsername", friendUsername.ToLower());
            }

            if (flags == RequestAddFriendUpdateFlags.UpdateAll || (flags & RequestAddFriendUpdateFlags.UpdateRemark) ==
                RequestAddFriendUpdateFlags.UpdateRemark)
            {
                if (remark == null && updateDoc.Contains("Remark"))
                {
                    updateDoc.Remove("Remark");
                }
                else if (remark != null)
                {
                    updateDoc.Set("Remark", remark);
                }
            }
            if (flags == RequestAddFriendUpdateFlags.UpdateAll || (flags & RequestAddFriendUpdateFlags.UpdateMessage) ==
                RequestAddFriendUpdateFlags.UpdateMessage)
            {
                if (message == null && updateDoc.Contains("Message"))
                {
                    updateDoc.Remove("Message");
                }
                else if (message != null)
                {
                    updateDoc.Set("Message", message);
                }
            }
            if (flags == RequestAddFriendUpdateFlags.UpdateAll || (flags & RequestAddFriendUpdateFlags.UpdateGroup) ==
                RequestAddFriendUpdateFlags.UpdateGroup)
            {
                if (groupName == null && updateDoc.Contains("GroupName"))
                {
                    updateDoc.Remove("GroupName");
                }
                else if (groupName != null)
                {
                    updateDoc.Set("GroupName", groupName);
                }
            }
            updateDoc.Set("Time", DateTime.Now);
            collection.Update(queryDoc, updateDoc, UpdateFlags.Upsert);
        }
Example #13
0
        /// <summary>
        /// This method stores a order.
        /// </summary>
        /// <param name="o">The order object to store</param>
        /// <returns>Success/Failure</returns>
        public Boolean storeOrder(Order o)
        {
            dLog.Info("Entering method storeOrder | ID: " + o.id);
            Boolean result = false;

            try
            {
                MongoServer   server = MongoServer.Create();
                MongoDatabase db     = server.GetDatabase("neatoBurrito");
                //MongoCredentials credentials = new MongoCredentials("username", "password");
                //MongoDatabase salaries = server.GetDatabase("salaries", credentials);

                using (server.RequestStart(db))
                {
                    MongoCollection <BsonDocument> coll = db.GetCollection("order");
                    var query = new QueryDocument("id", o.id);

                    dLog.Debug("Finding if order exists");
                    BsonDocument myDoc = coll.FindOne(query);

                    query.Add("isComplete", o.isComplete);
                    query.Add("isSubmitted", o.isSubmitted);
                    query.Add("orderDate", o.orderDate);
                    query.Add("totalCost", o.totalCost.ToString());

                    //ensure we were passed a valid object before attempting to write
                    if (myDoc == null)
                    {
                        dLog.Debug("Inserting order");
                        coll.Insert(query);

                        result = true;
                    }
                    else
                    {
                        var update = new UpdateDocument();
                        update.Add(query.ToBsonDocument());
                        dLog.Debug("Updating order");
                        dLog.Debug("myDoc: " + myDoc.ToString());
                        dLog.Debug("update Query: " + update.ToString());

                        SafeModeResult wr = coll.Update(new QueryDocument("id", o.id), update, SafeMode.True);

                        dLog.Debug("SafeModeResult: " + wr.Ok);
                        if (wr.LastErrorMessage == null && wr.Ok)
                        {
                            result = true;
                        }
                        else
                        {
                            dLog.Debug("SafeModeResult: " + wr.LastErrorMessage);
                        }
                    }

                    //now insert the burritos
                    if (result)
                    {
                        dLog.Debug("Trying to insert " + o.burritos.Count + " burritos");

                        var index = 0;
                        foreach (Burrito b in o.burritos)
                        {
                            b.orderID = o.id;

                            dLog.Debug("Set order ID " + o.id + " for burrito: " + index);
                            if (b.validate())
                            {
                                dLog.Debug("Storing burrito: " + index);
                                result = burritoSvc.storeBurrito(b);
                            }
                            index++;
                        }
                    }
                }
            }
            catch (Exception e2)
            {
                dLog.Error("Exception in storeBurrito: " + e2.Message);
            }
            finally
            {
                //using statement above already calls RequestDone()
            }

            return(result);
        }
Example #14
0
    public virtual void Save()
    {
        //修正持仓周期
        if (HasPosition && this.holdingPeriod < 1)
        {
            this.holdingPeriod = 1;                                         //当天入场的
        }
        if (this.holdingPeriod < 1)
        {
            return;
        }

        //提取日线,分线数据,还有大盘的数据
        string     symbol    = this.instrument.Symbol;
        Instrument indexInst = null;

        if (symbol.IndexOf("SHSE.") >= 0)
        {
            indexInst = InstrumentManager.Instruments["SHSE.000001"];
        }
        else if (symbol.IndexOf("SZSE.3") >= 0)
        {
            indexInst = InstrumentManager.Instruments["SZSE.399006"];
        }
        else
        {
            indexInst = InstrumentManager.Instruments["SZSE.399001"];
        }
        //指数的日线和分线
        BarSeries indexDaily = this.getDailySeries(indexInst);

        if (indexDaily.Count <= 0)
        {
            this.readLastNDailys(indexInst, this.indexDailyPeriod - 1);
            this.addTodayDaily(indexInst);
        }
        BarSeries indexMin5 = this.getMin5Series(indexInst);

        if (indexMin5.Count <= 0)
        {
            this.readLastNMin5s(indexInst, this.indexMin5Period);
        }
        //股票的日线和分线
        BarSeries stockDaily = this.getDailySeries(this.instrument);

        if (stockDaily.Count <= 0)
        {
            this.readLastNDailys(this.instrument, this.dailyPeriod - 1);
        }
        BarSeries stockMin5 = this.getMin5Series(this.instrument);

        if (stockMin5.Count <= 0)
        {
            this.readLastNMin5s(this.instrument, this.min5Period);
        }

        if (stockDaily.Count < 1)
        {
            return;                            //没有日线的不记录
        }
        //计算当天的奖赏
        double rewardForInside  = 0.0;     //在场内的奖赏
        double rewardForOutside = 0.0;     //在场外的奖赏

        if (this.holdingPeriod == 1)
        {
            rewardForInside = Math.Log(this.lastPrice / Position.EntryPrice);
        }
        else if (this.holdingPeriod > 1)
        {
            rewardForInside  = Math.Log(this.lastPrice / stockDaily.Last.Close);
            rewardForOutside = Math.Log(this.lastPriceWhenDeal / stockDaily.Last.Close);
        }
        //Console.WriteLine("symbol:{0} --- last price is {1} --- entry Price is {2},has {3} ticks",
        //	this.instrument.Symbol,this.lastPrice,Position.EntryPrice,this.Trades[this.instrument].Count);
        //当天的日线,交易决断前一刻的数据
        this.addTodayDaily(this.instrument);
        //正规化数据
        List <NormalizedBar> indexNormalizedDaily = this.NormalizeBars(indexDaily);
        List <NormalizedBar> indexNormalizedMin5  = this.NormalizeBars(indexMin5);
        List <NormalizedBar> stockNormalizedDaily = this.NormalizeBars(stockDaily);
        List <NormalizedBar> stockNormalizedMin5  = this.NormalizeBars(stockMin5);

        //写入数据库
        try{
            this.initDB();
            string curDateString = Clock.Now.Date.ToString("yyyy-MM-dd");
            //周期大于1且当天停盘没有交易的,不插入新记录,但要修改之前记录的下一个交易日期
            TradeArray trades = this.Trades[this.instrument];
            if (this.holdingPeriod > 1 &&
                (trades.Count <= 0 || trades.LastDateTime < Clock.Now.Date))
            {
                Console.WriteLine("证券{0}:今日没有交易", this.instrument.Symbol);
                BsonElement[] eleArray2 = new BsonElement[3];
                eleArray2[0] = new BsonElement("NextTradeDate", curDateString);
                eleArray2[1] = new BsonElement("Symbol", this.instrument.Symbol);
                eleArray2[2] = new BsonElement("Inside", 1);
                QueryDocument  query2 = new QueryDocument(eleArray2);
                UpdateDocument update = new UpdateDocument();
                update.Add(new BsonElement("$set", new QueryDocument(new BsonElement("NextTradeDate", (string)this.strategy.Global["NextTradeDate"]))));
                this.collection.Update(query2, update);
                return;
            }
            //如果当天已写入记录,先删除
            BsonElement[] eleArray = new BsonElement[2];
            eleArray[0] = new BsonElement("Date", curDateString);
            eleArray[1] = new BsonElement("Symbol", this.instrument.Symbol);
            QueryDocument query = new QueryDocument(eleArray);
            this.collection.Remove(query);
            //写入在场外的记录,如果是第一天,则是假设没有买入,如果是第二天及以后,则是假设卖出
            //此情况下,下一交易日为空
            BsonElement[] eleArray1 = new BsonElement[12];
            eleArray1[0] = new BsonElement("Date", curDateString);
            eleArray1[1] = new BsonElement("Symbol", this.instrument.Symbol);
            eleArray1[2] = new BsonElement("HoldingPeriod", this.holdingPeriod);
            eleArray1[3] = new BsonElement("Inside", 0);          //当前是否在场内
            eleArray1[4] = new BsonElement("IndexDaily", this.GetBsonArrayFromBars(indexNormalizedDaily));
            eleArray1[5] = new BsonElement("IndexMin5", this.GetBsonArrayFromBars(indexNormalizedMin5));
            eleArray1[6] = new BsonElement("StockDaily", this.GetBsonArrayFromBars(stockNormalizedDaily));
            eleArray1[7] = new BsonElement("StockMin5", this.GetBsonArrayFromBars(stockNormalizedMin5));
            eleArray1[8] = new BsonElement("Reward", rewardForOutside);
            eleArray1[9] = new BsonElement("NextTradeDate", "");
            BsonDocument insert = new BsonDocument(eleArray1);
            this.collection.Insert(insert);
            //写入在场内的记录,如果是第一天,则是买入,如果是第二天及以后,则是继续持有
            eleArray1    = new BsonElement[10];
            eleArray1[0] = new BsonElement("Date", curDateString);
            eleArray1[1] = new BsonElement("Symbol", this.instrument.Symbol);
            eleArray1[2] = new BsonElement("HoldingPeriod", this.holdingPeriod);
            eleArray1[3] = new BsonElement("Inside", 1);          //当前是否在场内
            eleArray1[4] = new BsonElement("IndexDaily", this.GetBsonArrayFromBars(indexNormalizedDaily));
            eleArray1[5] = new BsonElement("IndexMin5", this.GetBsonArrayFromBars(indexNormalizedMin5));
            eleArray1[6] = new BsonElement("StockDaily", this.GetBsonArrayFromBars(stockNormalizedDaily));
            eleArray1[7] = new BsonElement("StockMin5", this.GetBsonArrayFromBars(stockNormalizedMin5));
            eleArray1[8] = new BsonElement("Reward", rewardForInside);
            //已到了持仓周期限制,并且确实已卖出的,下一交易日为空
            if (this.holdingPeriod >= this.holdingPeriodLimit && (!HasPosition))
            {
                eleArray1[9] = new BsonElement("NextTradeDate", "");
            }
            else
            {
                eleArray1[9] = new BsonElement("NextTradeDate", (string)this.strategy.Global["NextTradeDate"]);
            }
            insert = new BsonDocument(eleArray1);
            this.collection.Insert(insert);
        }catch (Exception ex) {
            Console.WriteLine(ex.Message);
        }
    }
Example #15
0
        protected override FrameDLRObject ParseExpress(FrameDLRObject obj)
        {
            var            rtn            = FrameDLRObject.CreateInstance();
            var            query          = new QueryDocument(true);
            var            update         = new UpdateDocument(true);
            FrameDLRObject insert         = FrameDLRObject.CreateInstance(FrameDLRFlags.SensitiveCase);
            var            fields         = new FieldsBuilder();
            var            collectionname = "";

            foreach (var k in obj.Keys)
            {
                if (k.StartsWith("$"))
                {
                    if (k.ToLower() == "$where")
                    {
                        WhereExpress((FrameDLRObject)obj.GetValue(k), query, fields);
                    }
                    else if (k.ToLower() == "$table")
                    {
                        if (obj.GetValue(k) is string)
                        {
                            collectionname = ComFunc.nvl(obj.GetValue(k));
                        }
                    }
                }
                else
                {
                    var v = obj.GetValue(k);
                    if (this.CurrentAct == ActType.Query)
                    {
                        if (v is bool)
                        {
                            var bisinclude = (bool)v;
                            if (bisinclude)
                            {
                                fields.Include(k);
                            }
                            else
                            {
                                fields.Exclude(k);
                            }
                        }
                    }
                    else if (this.CurrentAct == ActType.Insert)
                    {
                        insert.SetValue(k, v);
                    }
                    else
                    {
                        if (!(v is FrameDLRObject))
                        {
                            update.Add(k, BsonValue.Create(v));
                        }
                    }
                }
            }
            rtn.query  = query;
            rtn.update = update;
            rtn.insert = insert;
            rtn.fields = fields;
            rtn.table  = collectionname;
            return(rtn);
        }
Example #16
0
        /// <summary>
        /// This method stores a employee.
        /// </summary>
        /// <param name="e">The employee object to store</param>
        /// <returns>Success/Failure</returns>
        public Boolean storeEmployee(Employee e)
        {
            dLog.Info("Entering method storeEmployee | ID: " + e.id);
            Boolean result = false;

            try
            {
                MongoServer   server = MongoServer.Create();
                MongoDatabase db     = server.GetDatabase("neatoBurrito");
                //MongoCredentials credentials = new MongoCredentials("username", "password");
                //MongoDatabase salaries = server.GetDatabase("salaries", credentials);

                using (server.RequestStart(db))
                {
                    MongoCollection <BsonDocument> coll = db.GetCollection("employee");
                    var query = new QueryDocument("id", e.id);

                    dLog.Debug("Finding if employee exists");
                    BsonDocument myDoc = coll.FindOne(query);

                    query.Add("firstName", e.firstName);
                    query.Add("isManager", e.isManager);
                    query.Add("lastName", e.lastName);

                    //ensure we were passed a valid object before attempting to write
                    if (myDoc == null)
                    {
                        dLog.Debug("Inserting employee");
                        coll.Insert(query);

                        result = true;
                    }
                    else
                    {
                        var update = new UpdateDocument();
                        update.Add(query.ToBsonDocument());
                        dLog.Debug("Updating employee");
                        dLog.Debug("myDoc: " + myDoc.ToString());
                        dLog.Debug("update Query: " + update.ToString());

                        SafeModeResult wr = coll.Update(new QueryDocument("id", e.id), update, SafeMode.True);

                        dLog.Debug("SafeModeResult: " + wr.Ok);
                        if (wr.LastErrorMessage == null && wr.Ok)
                        {
                            result = true;
                        }
                        else
                        {
                            dLog.Debug("SafeModeResult: " + wr.LastErrorMessage);
                        }
                    }
                }
            }
            catch (Exception e2)
            {
                dLog.Error("Exception in storeEmployee: " + e2.Message);
            }
            finally
            {
                //using statement above already calls RequestDone()
            }

            return(result);
        }
Example #17
0
    static void Main(string[] args)
    {
        // TO DO: Add your code here

        int dailyPeriod        = 40; //日线周期
        int min5Period         = 10; //分线周期
        int indexDailyPeriod   = 10;
        int indexMin5Period    = 10;
        int holdingPeriodLimit = 5;      //持仓周期限制

        MongoClient   client   = new MongoClient("mongodb://localhost:27017");
        MongoServer   server   = client.GetServer();
        MongoDatabase database = server.GetDatabase("FinanceLast");
        //读取交易日期
        List <DateTime> dates = new List <DateTime>();
        MongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>("TradeDates");

        foreach (BsonDocument record in collection.FindAll())
        {
            DateTime date = DateTime.Parse(record["Date"].ToString());
            dates.Add(date);
        }
        //
        collection = database.GetCollection <BsonDocument>("RandomTradeStatistics");
        SimulationDataProvider sdp           = (SimulationDataProvider)ProviderManager.MarketDataSimulator;
        List <string>          activeSymbols = new List <String>();

        activeSymbols.AddRange(sdp.GetSymbols("SHSE", 1));
        activeSymbols.AddRange(sdp.GetSymbols("SZSE", 1));

        DateTime beginDate = new DateTime(2017, 12, 11);
        DateTime endDate   = new DateTime(2017, 12, 31);
        DateTime curDate   = beginDate;
        Dictionary <string, RandomTradeRecord> randomTradeRecordDict = new Dictionary <string, RandomTradeRecord>();

        while (curDate <= endDate)
        {
            //sdp.Connect();
            string curDateString = curDate.ToString("yyyy-MM-dd");
            Console.WriteLine("当前日期是{0}", curDateString);
            int i = dates.IndexOf(curDate);
            if (i < 0)
            {
                Console.WriteLine("今天不是交易日。");
            }
            else
            {
                DateTime nextTradeDate = curDate.AddDays(1);
                if (i + 1 < dates.Count)
                {
                    nextTradeDate = dates[i + 1];
                }
                string nextTradeDateString = nextTradeDate.ToString("yyyy-MM-dd");

                DateTime dealTime  = curDate.Add(new TimeSpan(10, 20, 0));
                DateTime closeTime = curDate.Add(new TimeSpan(15, 3, 0));

                //处理已有的头寸
                QueryDocument query = new QueryDocument(new BsonElement("NextTradeDate", curDateString));
                foreach (BsonDocument record in collection.Find(query))
                {
                    RandomTradeRecord aTradeRecord = new RandomTradeRecord();
                    aTradeRecord._id           = record["_id"].ToString();
                    aTradeRecord.Symbol        = record["Symbol"].ToString();
                    aTradeRecord.HoldingPeriod = (int)record["HoldingPeriod"] + 1;
                    randomTradeRecordDict.Add(aTradeRecord.Symbol, aTradeRecord);
                }

                //获取最新价格,排序,然后随机选择入场

                Dictionary <String, Trade> lastTrades = sdp.GetLastTrades(activeSymbols.ToArray(), dealTime);

                List <string> symbols = new List <string>();
                foreach (KeyValuePair <String, Trade> kvp in lastTrades)
                {
                    if (kvp.Value == null)
                    {
                        continue;
                    }
                    GMTrade gmTrade = (GMTrade)kvp.Value;
                    if (gmTrade.Price <= 0)
                    {
                        continue;
                    }
                    if (gmTrade.Price == gmTrade.UpperLimit)
                    {
                        continue;
                    }
                    if (gmTrade.Price / gmTrade.LastClose - 1 < 0)
                    {
                        continue;
                    }
                    if (randomTradeRecordDict.ContainsKey(kvp.Key))
                    {
                        continue;
                    }
                    symbols.Add(kvp.Key);
                }
                int total = symbols.Count;

                Random randomer      = new Random((int)DateTime.Now.Ticks);
                int[]  randomNumbers = new int[100];
                for (int k = 0; k < 100; k++)
                {
                    randomNumbers[k] = randomer.Next(total);
                }
                foreach (int r in randomNumbers)
                {
                    string symbol = symbols[r];
                    if (!randomTradeRecordDict.ContainsKey(symbol))
                    {
                        RandomTradeRecord aTradeRecord = new RandomTradeRecord();
                        aTradeRecord.Symbol        = symbol;
                        aTradeRecord.HoldingPeriod = 1;
                        randomTradeRecordDict.Add(aTradeRecord.Symbol, aTradeRecord);
                    }
                }
                symbols.Clear();
                //如果当天已写入记录,先删除
                query = new QueryDocument(new BsonElement("Date", curDateString));
                collection.Remove(query);

                foreach (RandomTradeRecord aTradeRecord in randomTradeRecordDict.Values)
                {
                    //读取交易价格和收盘价格
                    Trade nextTrade = sdp.GetNextTrade(aTradeRecord.Symbol, dealTime);
                    if (nextTrade == null || nextTrade.DateTime.Date > curDate)
                    {
                        Console.WriteLine("Symbol {0} 在 {1} 时无法在下一笔成交", aTradeRecord.Symbol, dealTime);
                        aTradeRecord.PriceWhenDeal = 0.0;
                    }
                    else
                    {
                        aTradeRecord.PriceWhenDeal = nextTrade.Price;
                    }

                    Trade closeTrade = sdp.GetLastTrade(aTradeRecord.Symbol, closeTime);
                    if (closeTrade == null || closeTrade.DateTime.Date < curDate)
                    {
                        Console.WriteLine("Symbol {0} 今天没有收盘价", aTradeRecord.Symbol);
                        aTradeRecord.PriceWhenClose = 0.0;
                    }
                    else
                    {
                        aTradeRecord.PriceWhenClose = closeTrade.Price;
                    }

                    //没有交易价格和收盘价格则认为是停盘
                    if (aTradeRecord.PriceWhenDeal <= 0 && aTradeRecord.PriceWhenClose <= 0)
                    {
                        Console.WriteLine("证券{0}:今日没有交易", aTradeRecord.Symbol);
                        if (aTradeRecord.HoldingPeriod > 1)
                        {
                            query = new QueryDocument(new BsonElement("_id", aTradeRecord._id));
                            UpdateDocument update = new UpdateDocument();
                            update.Add(new BsonElement("$set", new BsonDocument(new BsonElement("NextTradeDate", nextTradeDateString))));
                            collection.Update(query, update);
                        }
                        continue;
                    }
                    //读取应指数的日线和5分线,证券的日线和分线
                    string indexSymbol = "";
                    if (aTradeRecord.Symbol.IndexOf("SHSE.") >= 0)
                    {
                        indexSymbol = "SHSE.000001";
                    }
                    else if (aTradeRecord.Symbol.IndexOf("SZSE.3") >= 0)
                    {
                        indexSymbol = "SZSE.399006";
                    }
                    else
                    {
                        indexSymbol = "SZSE.399001";
                    }

                    List <Daily> indexDailys = sdp.GetLastNDailys(indexSymbol, indexDailyPeriod, curDate);
                    List <Bar>   indexMin5s  = sdp.GetLastNBars(indexSymbol, 300, indexMin5Period, dealTime);


                    //***这里多加了当天日线,便于向前复权
                    List <Daily> stockDailys = sdp.GetLastNDailys(aTradeRecord.Symbol, dailyPeriod, curDate);
                    AdjustDailys(stockDailys);
                    List <Bar> stockMin5s = sdp.GetLastNBars(aTradeRecord.Symbol, 300, min5Period, dealTime);
                    //去掉当天日线后,获取昨日收盘价
                    int m = stockDailys.Count;
                    if (m < dailyPeriod)
                    {
                        continue;
                    }
                    if (stockDailys[m - 1].DateTime == curDate)
                    {
                        stockDailys.RemoveAt(m - 1);
                    }
                    else
                    {
                        stockDailys.RemoveAt(0);
                    }
                    double lastClose = stockDailys[stockDailys.Count - 1].Close;
                    //加入当天决断时刻的日线
                    Trade trade = lastTrades[aTradeRecord.Symbol];
                    if (trade == null)
                    {
                        continue;
                    }
                    Daily todayDaily = BuildDailyFormTrade((GMTrade)trade);
                    stockDailys.Add(todayDaily);

                    //正规化数据
                    List <NormalizedBar> indexNormalizedDailys = NormalizeBars(indexDailys);
                    List <NormalizedBar> indexNormalizedMin5s  = NormalizeBars(indexMin5s);
                    List <NormalizedBar> stockNormalizedDailys = NormalizeBars(stockDailys);
                    List <NormalizedBar> stockNormalizedMin5s  = NormalizeBars(stockMin5s);

                    //计算当天的奖赏
                    double rewardForInside  = 0.0;                 //在场内的奖赏
                    double rewardForOutside = 0.0;                 //在场外的奖赏

                    if (aTradeRecord.HoldingPeriod == 1)
                    {
                        rewardForInside = Math.Log(aTradeRecord.PriceWhenClose / aTradeRecord.PriceWhenDeal);
                    }
                    else if (aTradeRecord.HoldingPeriod > 1)
                    {
                        rewardForInside  = Math.Log(aTradeRecord.PriceWhenClose / lastClose);
                        rewardForOutside = Math.Log(aTradeRecord.PriceWhenDeal / lastClose);
                    }
                    //Console.WriteLine("{0},{1},{2}",aTradeRecord.PriceWhenDeal,aTradeRecord.PriceWhenClose,lastClosePrice);
                    //写入在场外的记录,如果是第一天,则是假设没有买入,如果是第二天及以后,则是假设卖出
                    //此情况下,下一交易日为空
                    BsonElement[] eleArray = new BsonElement[9];
                    eleArray[0] = new BsonElement("Date", curDateString);
                    eleArray[1] = new BsonElement("Symbol", aTradeRecord.Symbol);
                    eleArray[2] = new BsonElement("HoldingPeriod", aTradeRecord.HoldingPeriod);
                    eleArray[3] = new BsonElement("IndexDaily", GetBsonArrayFromBars(indexNormalizedDailys));
                    eleArray[4] = new BsonElement("IndexMin5", GetBsonArrayFromBars(indexNormalizedMin5s));
                    eleArray[5] = new BsonElement("StockDaily", GetBsonArrayFromBars(stockNormalizedDailys));
                    eleArray[6] = new BsonElement("StockMin5", GetBsonArrayFromBars(stockNormalizedMin5s));
                    BsonArray bsonArray = new BsonArray(2);
                    bsonArray.Add(rewardForInside);
                    bsonArray.Add(rewardForOutside);
                    eleArray[7] = new BsonElement("Reward", bsonArray);
                    //已到了持仓周期限制,卖出,下一交易日为空
                    if (aTradeRecord.HoldingPeriod >= holdingPeriodLimit)
                    {
                        eleArray[8] = new BsonElement("NextTradeDate", "");
                    }
                    else
                    {
                        eleArray[8] = new BsonElement("NextTradeDate", nextTradeDateString);
                    }
                    BsonDocument insert = new BsonDocument(eleArray);
                    collection.Insert(insert);
                    indexDailys.Clear();
                    indexMin5s.Clear();
                    stockDailys.Clear();
                    stockMin5s.Clear();
                    indexNormalizedDailys.Clear();
                    indexNormalizedMin5s.Clear();
                    stockNormalizedDailys.Clear();
                    stockNormalizedMin5s.Clear();
                }
                lastTrades.Clear();
                randomTradeRecordDict.Clear();
                Console.WriteLine("统计完毕。");
            }
            sdp.FlushAllSeries();
            //sdp.Disconnect();
            //为了防止内存溢出
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForFullGCApproach();
            GC.WaitForFullGCComplete();
            curDate = curDate.AddDays(1);
        }
    }