Exemplo n.º 1
0
        public ActionResult AddEntrust(AddEntrust addEntrust)
        {
            Response _res = new Response();
            int      id   = int.Parse(Session["UserID"].ToString());

            if (string.IsNullOrEmpty(payCoin))
            {
                payCoin = "TTG"; sellCoin = "ETH";
            }
            addEntrust.EPayCoin  = payCoin;
            addEntrust.ESellCoin = sellCoin;

            double personCoinAmount = _walletManager.GetWallet(id, addEntrust.ESellCoin).Amount;

            if (personCoinAmount <= 0 || (addEntrust.EAmount > personCoinAmount))
            {
                ViewBag.Success = "-1";
                return(View("Index"));
            }

            if (ModelState.IsValid)
            {
                Entrust entrust = new Entrust();
                entrust.CoinName    = addEntrust.ESellCoin;
                entrust.PayCoinName = addEntrust.EPayCoin;
                entrust.IsSuccess   = 0;

                entrust.FUserID = int.Parse(Session["UserID"].ToString());
                entrust.Price   = addEntrust.Eprice;

                entrust.Amount       = addEntrust.EAmount;
                entrust.EnstructTime = DateTime.Now;
                entrust.SucOrDefTime = DateTime.Now;
                _res = _entrustManager.Add(entrust);
                //减少币
                Wallet _wallet = _walletManager.GetWallet(id, addEntrust.ESellCoin);
                _wallet.Amount -= addEntrust.EAmount;
                _walletManager.Update(_wallet);
                ViewBag.Success = 1;
            }
            //if (!ModelState.IsValid)
            //{
            //    List<string> sb = new List<string>();
            //    //获取所有错误的Key
            //    List<string> Keys = ModelState.Keys.ToList();
            //    //获取每一个key对应的ModelStateDictionary
            //    foreach (var key in Keys)
            //    {
            //        var errors = ModelState[key].Errors.ToList();
            //        //将错误描述添加到sb中
            //        foreach (var error in errors)
            //        {
            //            sb.Add(error.ErrorMessage);
            //        }
            //    }
            //    return Json("0");
            //}
            return(View("Index"));
            //return Json(_res);
        }
Exemplo n.º 2
0
        public ActionResult CancelEntrust(int id, double amount, string coinname)
        {   //更新撤销后的委托情况
            Entrust en = _entrustManager.Find(id);

            en.IsSuccess = -1;
            _entrustManager.Update(en);
            //更新撤销后的钱包
            int i = 0;

            while (i < coinname.Length)
            {
                if (coinname[i] != '/')
                {
                    i++;
                }
                else
                {
                    break;
                }
            }
            coinname = coinname.Substring(0, i);//出售的
            Wallet wa = _wallet.GetWallet(int.Parse(Session["UserID"].ToString()), coinname);

            wa.Amount += amount;
            _wallet.Update(wa);
            return(null);
        }
Exemplo n.º 3
0
        public int PostEntrust(Entrust entrust)
        {
            int dealedCount = 0;

            CreateEntrust(entrust);

            return(dealedCount);
        }
Exemplo n.º 4
0
        private void Form1_Load(object sender, EventArgs e)
        {
            Entrust callback = new Entrust(doKeboadrdEvent);
            Thread  th       = new Thread(ThreadChild);

            th.IsBackground = true;
            th.Start();
            label1.Text = "服务运行中";
        }
Exemplo n.º 5
0
        private void btnExit_Click(object sender, EventArgs e)
        {
            btnExit.Enabled = false;

            loadControl.Visible = true;

            Entrust callback = new Entrust(CallBack);                                      //委托之后要执行的方法
            Thread  th       = new Thread(new ParameterizedThreadStart(UninstallService)); //线程要执行的方法

            th.IsBackground = true;
            th.Start(callback);//启动线程 委托给线程
        }
Exemplo n.º 6
0
 public Client(Entrust callb, string ipString = null, int port = -1)
 {
     //print = new myPrintPrint(print1);
     this.callback = callb;
     if (ipString != null)
     {
         this.ipString = ipString;
     }
     if (port >= 0)
     {
         this.port = port;
     }
 }
Exemplo n.º 7
0
        private void UninstallService(object obj)
        {
            string serviceFilePath = Environment.CurrentDirectory + "\\AGEService.exe";
            string serviceName     = "AGEService";

            if (AGEService.IsServiceExisted(serviceName))
            {
                AGEService.UninstallService(serviceFilePath);
            }

            Entrust callback = obj as Entrust; //强转为委托

            callback();
        }
Exemplo n.º 8
0
 //连接服务器
 public void ConnetServer()
 {
     if (client == null)
     {
         Entrust callback = new Entrust(CallBack); //把方法赋值给委托
         client        = new Client(callback, "127.0.0.1", "8888");
         client.print += new myPrint(ClientPrint);
     }
     if (!client.connected)
     {
         client.start();
     }
     // if (client != null) thi = "客户端 " + client.localIpPort;
 }
Exemplo n.º 9
0
        public Client(Entrust callb, string ipString = null, string port = "-1")
        {
            //   print = new Print(print1);
            this.callback = callb;
            if (ipString != null)
            {
                this.ipString = ipString;
            }

            int port_int = Int32.Parse(port);

            if (port_int >= 0)
            {
                this.port = port_int;
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// 根据C的持仓获取P的追买量
        /// </summary>
        /// <returns></returns>
        private Entrust GetBuyPutEntrust()
        {
            Entrust curEntrust = null;

            //判断是否存在C单腿的品种,有则需要追买P
            for (int i = 0; i < m_PositionList.Count; i++)
            {
                Position callPosition = m_PositionList[i];
                if (callPosition.PositionContract.Right == ContractRight.Call)
                {
                    //寻找Call持仓对应的Put持仓
                    for (int k = 0; k < m_PositionList.Count; k++)
                    {
                        Position putPosition = m_PositionList[k];
                        if (putPosition.PositionContract.Strike == callPosition.PositionContract.Strike && putPosition.PositionContract.Expiry == callPosition.PositionContract.Expiry && putPosition.PositionContract.Right == ContractRight.Put)
                        {
                            //计算AB差值时
                            int offsetAB = Math.Abs(putPosition.PositionNum) - callPosition.PositionNum;

                            if (offsetAB > 0)
                            {
                                curEntrust = new Entrust();
                                curEntrust.EntrustContract = putPosition.PositionContract;
                                Order order = new Order();
                                order.Action        = "BUY";
                                order.OrderType     = "LMT";
                                order.TotalQuantity = offsetAB;
                                order.Account       = StrategyPool.Account;

                                //遍历得到委托价格
                                for (int j = 0; j < m_ContractList.Length; j++)
                                {
                                    if (m_ReportList[j][0].AskPrice > 0 && m_ReportList[j][0].MdContract.Strike == putPosition.PositionContract.Strike && m_ReportList[j][0].MdContract.Expiry == callPosition.PositionContract.Expiry && m_ReportList[j][0].MdContract.Right == ContractRight.Put)
                                    {
                                        order.LmtPrice = m_ReportList[j][0].AskPrice;
                                        break;
                                    }
                                }
                                curEntrust.EntrustOrder = order;
                            }
                            break;
                        }
                    }
                }
            }
            return(curEntrust);
        }
Exemplo n.º 11
0
        /// <summary>
        /// 根据P的持仓获取C的追卖量
        /// </summary>
        /// <returns></returns>
        private Entrust GetSellCallEntrust()
        {
            Entrust curEntrust = null;

            //判断是否存在P单腿的品种,有则需要追卖C
            for (int i = 0; i < m_PositionList.Count; i++)
            {
                Position putPosition = m_PositionList[i];
                if (putPosition.PositionContract.Right == ContractRight.Put)
                {
                    //寻找Put持仓对应的Call持仓
                    Position callPosition = null;
                    for (int k = 0; k < m_PositionList.Count; k++)
                    {
                        if (m_PositionList[k].PositionContract.Strike == putPosition.PositionContract.Strike && m_PositionList[k].PositionContract.Expiry == putPosition.PositionContract.Expiry && m_PositionList[k].PositionContract.Right == ContractRight.Call)
                        {
                            callPosition = m_PositionList[k];

                            int offsetAB = callPosition.PositionNum - Math.Abs(putPosition.PositionNum);

                            if (offsetAB > 0)
                            {
                                curEntrust = new Entrust();
                                curEntrust.EntrustContract = callPosition.PositionContract;
                                Order order = new Order();
                                order.Action            = OrderActionType.Sell;
                                order.OrderType         = "LMT";
                                order.TotalQuantity     = offsetAB;
                                order.Account           = StrategyPool.Account;
                                curEntrust.EntrustOrder = order;
                                //遍历得到委托价格
                                for (int j = 0; j < m_ContractList.Length; j++)
                                {
                                    if (m_ReportList[j][0].BidPrice > 0 && m_ReportList[j][0].MdContract.Strike == callPosition.PositionContract.Strike && m_ReportList[j][0].MdContract.Expiry == putPosition.PositionContract.Expiry && m_ReportList[j][0].MdContract.Right == ContractRight.Call)
                                    {
                                        order.LmtPrice = m_ReportList[j][0].BidPrice;
                                        break;
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
            }
            return(curEntrust);
        }
Exemplo n.º 12
0
        public ActionResult Index(C2CViewModel c2c)

        {
            string _psd   = null;
            int    id     = int.Parse(Session["UserID"].ToString());
            string traPsd = _userManager.Find(id).UserIdenty.Password;

            ViewBag.Success = 0;
            if (c2c.Amount > _wallet.GetWallet(id, "CNYX").Amount)
            {
                ModelState.AddModelError("Amount", "持有货币量不足"); return(View());
            }
            try { _psd = Security.SHA256(c2c.C2CPassword); }
            catch { ModelState.AddModelError("C2CPassword", "请先输入交易密码"); }
            try
            {
                if (traPsd == null)
                {
                }
            }
            catch
            {
                ModelState.AddModelError("C2CPassword", "请先设置交易密码");
                return(View());
            }
            if (_psd != traPsd)
            {
                ModelState.AddModelError("C2CPassword", "交易密码错误");
                return(View());
            }
            if (ModelState.IsValid)
            {
                Entrust en = new Entrust();
                en.Amount       = c2c.Amount;
                en.CoinName     = "CNYX";
                en.EnstructTime = DateTime.Now;
                en.FUserID      = id;
                en.IsSuccess    = 0;
                en.PayCoinName  = "CNY";
                en.Price        = 0.99;
                en.SucOrDefTime = DateTime.Now;
                _entrust.Add(en);
                ViewBag.Success = 1;
            }

            return(View());
        }
Exemplo n.º 13
0
        public void CancelEntrust(Entrust entrust)
        {
            if (entrust != null)
            {
                if (entrust.Status == 0)
                {
                    entrust.Status = 9;
                }
                else if (entrust.Status == 2)
                {
                    entrust.Status = 3;
                }

                entrust.Cancelled = true;
                new EntrustRepository().Update(entrust);
            }
        }
Exemplo n.º 14
0
 private void CreateDigitalModelToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (zedGraphControl.GraphPane.CurveList.Count != 0)
     {
         initBMP();
         Entrust callback = new Entrust(SaveVToFile);
         Thread  thread   = new Thread(GetVThread)
         {
             IsBackground = true
         };
         thread.SetApartmentState(ApartmentState.STA);
         thread.Start(callback);
     }
     else
     {
         MessageBox.Show("无地层!");
     }
 }
Exemplo n.º 15
0
        //یک دسته بندی با عنوان شعر و ادبیات در فهرست دسته بندی ها وجود دارد
        //و یک کتاب به نویسندگی فروغ فرخزاد با عنوان دیوان اشعار فروغ و رده سنی بالای 15 سال در فهرست کتاب ها و در دسته شعر و ادبیات وجود دارد
        //و یک عضو با نام ونام خانوادگی امید جمالی و سن 31 سال و آدرس بلوار محراب در فهرست اعضا وجود دارد
        //و فقط یک امانت کتاب با عنوان دیوان اشعار فروغ به نویسندگی
        //فروغ فرخزاد و رده سنی بالای 15 سال برای فردی با نام و نام خانوادگی امید جمالی و سن 31 سال
        //و آدرس بلوار محراب و تاریخ برگشت مورد انتظار30/02/1400 در فهرست کتاب های امانت داده شده وجود دارد.
        private void Given()
        {
            var bookCategory = BookCategoryFactory.GenerateBookCategory("شعروادبیات");

            _context.Manipulate(_ => _.BookCategories.Add(bookCategory));
            var book = new BookBuilder()
                       .BuildBookWithCategoryId(bookCategory.Id)
                       .BuildBookWithAgeRange(15)
                       .BuildBookWithAuthor("فروغ فرخزاد")
                       .BuildBookWithName("دیوان اشعارفروغ")
                       .Build();

            _context.Manipulate(_ => _.Books.Add(book));
            var member = MemberFactory.GenerateMember("بلوارمحراب", 31, "امیدجمالی");

            _context.Manipulate(_ => _.Add(member));
            _determinateShamsiToMiladiDate = new DateTime(1400, 2, 30, new PersianCalendar());
            _entrust = EntrustFactory.GenerateEntrust(book.Id, member.Id, _determinateShamsiToMiladiDate);
            _context.Manipulate(_ => _.Entrusts.Add(_entrust));
        }
Exemplo n.º 16
0
        public async Task <int> AddEntrust(AddEntrustDto dto)
        {
            var   book             = _entrustRepository.FindBookById(dto.BookId);
            var   member           = _memberRepository.FindMemberById(dto.MemberId);
            short bookMinAgeNeeded = (short)book.MinAgeNeed;

            if (member.Age < bookMinAgeNeeded)
            {
                throw new FailedAddEntrustWhenMemberAgeIsNotInValidRanegException();
            }
            Entrust entrust = new Entrust
            {
                BookId   = dto.BookId,
                MemberId = dto.MemberId,
                DeterminateReturnDate = dto.BookReturnDate
            };

            _entrustRepository.Add(entrust);
            await _unitOfWork.Complete();

            return(entrust.Id);
        }
Exemplo n.º 17
0
        public IActionResult Post([FromBody] Entrust entrust)
        {
            MsgResponse msgResponse = new MsgResponse();

            if (entrust != null)
            {
                if (entrust.message != "" && entrust.to != "" && entrust.from != "" && entrust.timeToLifeSec > 0)
                {
                    msgResponse.message = "Hello " + entrust.to + " your message will be send";
                    return(new OkObjectResult(msgResponse));
                }
                else
                {
                    msgResponse.message = "Datos Incompletos, Request ERROR ";
                    return(new OkObjectResult(msgResponse));
                }
            }
            else
            {
                var run = " ERROR ";
                return(new OkObjectResult(run));
            }
        }
Exemplo n.º 18
0
 public void UpdateEntrust(Entrust entrust)
 {
     Conn.Update <Entrust>(entrust);
 }
Exemplo n.º 19
0
 public int CreateEntrust(Entrust entrust)
 {
     return(new EntrustRepository().Create(entrust));
 }
Exemplo n.º 20
0
        /// <summary>
        /// 生成买卖订单
        /// </summary>
        /// <returns>返回买卖信息,先卖后买</returns>
        private Entrust[] GetEntrustList()
        {
            Entrust[] entrustList = null;
            Entrust   oneEntrust  = null;
            Entrust   twoEntrust  = null;

            double curDis = m_ReportList[0][0].BidPrice - m_ReportList[1][0].AskPrice;

            if (curDis - m_BasePriceDis >= m_WheeledPriceDis)//卖一号合约买二号合约条件满足
            {
                oneEntrust = new Entrust();
                oneEntrust.EntrustContract = m_ReportList[0][0].MdContract;
                Order oneOrder = new Order();
                oneOrder.Action         = OrderActionType.Sell;
                oneOrder.OrderType      = "LMT";
                oneOrder.Account        = StrategyPool.Account;
                oneOrder.LmtPrice       = m_ReportList[0][0].BidPrice;
                oneOrder.TotalQuantity  = 1;
                oneEntrust.EntrustOrder = oneOrder;

                twoEntrust = new Entrust();
                twoEntrust.EntrustContract = m_ReportList[1][0].MdContract;
                Order twoOrder = new Order();
                twoOrder.Action         = OrderActionType.Buy;
                twoOrder.OrderType      = "LMT";
                twoOrder.Account        = StrategyPool.Account;
                twoOrder.LmtPrice       = m_ReportList[1][0].AskPrice;
                twoOrder.TotalQuantity  = 1;
                twoEntrust.EntrustOrder = twoOrder;

                entrustList    = new Entrust[2];
                entrustList[0] = oneEntrust;
                entrustList[1] = twoEntrust;
            }
            else
            {
                curDis = m_ReportList[0][0].AskPrice - m_ReportList[1][0].BidPrice;
                if (m_BasePriceDis - curDis >= m_WheeledPriceDis)//卖二号合约买一号合约条件满足
                {
                    oneEntrust = new Entrust();
                    oneEntrust.EntrustContract = m_ReportList[1][0].MdContract;
                    Order oneOrder = new Order();
                    oneOrder.Action         = OrderActionType.Sell;
                    oneOrder.OrderType      = "LMT";
                    oneOrder.Account        = StrategyPool.Account;
                    oneOrder.LmtPrice       = m_ReportList[1][0].BidPrice;
                    oneOrder.TotalQuantity  = 1;
                    oneEntrust.EntrustOrder = oneOrder;

                    twoEntrust = new Entrust();
                    twoEntrust.EntrustContract = m_ReportList[0][0].MdContract;
                    Order twoOrder = new Order();
                    twoOrder.Action         = OrderActionType.Buy;
                    twoOrder.OrderType      = "LMT";
                    twoOrder.Account        = StrategyPool.Account;
                    twoOrder.LmtPrice       = m_ReportList[0][0].AskPrice;
                    twoOrder.TotalQuantity  = 1;
                    twoEntrust.EntrustOrder = twoOrder;

                    entrustList    = new Entrust[2];
                    entrustList[0] = oneEntrust;
                    entrustList[1] = twoEntrust;
                }
            }

            return(entrustList);
        }
Exemplo n.º 21
0
 /// <summary>
 /// 根据现有的委托信号确定是否取消活动委托单
 /// </summary>
 /// <param name="sellPutEntrust"></param>
 /// <param name="buyPutEntrust"></param>
 /// <param name="entrusts"></param>
 private void CancelQueueingOrder(Entrust sellPutEntrust, Entrust buyPutEntrust, Entrust sellCallEntrust, Entrust buyCallEntrust, Entrust[] entrusts)
 {
     if (sellPutEntrust != null || buyPutEntrust != null || sellCallEntrust != null || buyCallEntrust != null)
     {
         Entrust curEntrust = null;
         if (sellPutEntrust != null)
         {
             curEntrust = sellPutEntrust;
         }
         else if (buyPutEntrust != null)
         {
             curEntrust = buyPutEntrust;
         }
         else if (sellCallEntrust != null)
         {
             curEntrust = sellCallEntrust;
         }
         else if (buyCallEntrust != null)
         {
             curEntrust = buyCallEntrust;
         }
         for (int i = 0; i < m_OrderReportList.Count; i++)
         {
             if (IsEqual(m_OrderReportList[i].OrderContract, curEntrust.EntrustContract))
             {
                 if ((m_OrderReportList[i].CurOrder.Action == OrderActionType.Sell && m_OrderReportList[i].CurOrder.LmtPrice > curEntrust.EntrustOrder.LmtPrice) ||
                     (m_OrderReportList[i].CurOrder.Action == OrderActionType.Buy && m_OrderReportList[i].CurOrder.LmtPrice < curEntrust.EntrustOrder.LmtPrice))
                 {
                     CancelOrder(m_OrderReportList[i].OrderId);
                 }
             }
             else
             {
                 CancelOrder(m_OrderReportList[i].OrderId);
             }
         }
     }
     else if (entrusts != null)
     {
         for (int i = 0; i < m_OrderReportList.Count; i++)
         {
             bool isContain = false;
             for (int j = 0; j < entrusts.Length; j++)
             {
                 if (IsEqual(m_OrderReportList[i].OrderContract, entrusts[j].EntrustContract))
                 {
                     isContain = true;
                     if ((m_OrderReportList[i].CurOrder.Action == OrderActionType.Sell && m_OrderReportList[i].CurOrder.LmtPrice > entrusts[j].EntrustOrder.LmtPrice) ||
                         (m_OrderReportList[i].CurOrder.Action == OrderActionType.Buy && m_OrderReportList[i].CurOrder.LmtPrice < entrusts[j].EntrustOrder.LmtPrice))
                     {
                         CancelOrder(m_OrderReportList[i].OrderId);
                     }
                 }
             }
             if (!isContain)
             {
                 CancelOrder(m_OrderReportList[i].OrderId);
             }
         }
     }
 }
Exemplo n.º 22
0
        /// <summary>
        /// 获取轮动买卖Put的订单,根据对价、排队价、挂单价依次判断
        /// </summary>
        /// <returns></returns>
        private Entrust[] GetPutOrders(double[] optValues, int maxValueIndex)
        {
            List <Entrust> entrustList = null;
            Entrust        oneEntrust  = null;
            Entrust        twoEntrust  = null;

            //遍历得到溢价最高的持仓
            Position closePosition = null;            //卖出价值最低的持仓
            double   closeValue1   = double.MaxValue; //对价平仓价值
            double   closeValue2   = double.MaxValue; //排队价平仓价值
            double   closeValue3   = double.MaxValue; //委托价平仓价值
            int      closeIndex    = -1;              //低卖出价值对应的品种索引
            MdReport closeReport   = null;
            double   orderLmtPrice = 0;               //记录需要平仓的持仓委托价格

            for (int j = 0; j < m_PositionList.Count; j++)
            {
                Position curPosition = m_PositionList[j];
                if (curPosition.PositionContract.Right == ContractRight.Put && Math.Abs(curPosition.PositionNum) > 0)
                {
                    for (int i = 0; i < m_ContractList.Length / 2; i++)
                    {
                        if (m_ReportList[i * 2 + 1][0].MdContract.Strike == curPosition.PositionContract.Strike)//m_Reports[i * 2 + 1]是Put
                        {
                            double curValue = m_ReportList[i * 2 + 1][0].AskPrice - m_ReportList[i * 2][0].BidPrice - curPosition.PositionContract.Strike;
                            if (curValue < closeValue1)
                            {
                                closePosition = curPosition;
                                closeValue1   = curValue;
                                closeValue2   = m_ReportList[i * 2 + 1][0].BidPrice - m_ReportList[i * 2][0].BidPrice - curPosition.PositionContract.Strike;
                                closeIndex    = i;
                                closeReport   = m_ReportList[i * 2 + 1][0];
                                //如果活动委托中有此持仓,通过委托价算出平仓价值
                                for (int k = 0; k < m_OrderReportList.Count; k++)
                                {
                                    if (m_OrderReportList[k].OrderContract.Strike == curPosition.PositionContract.Strike && m_OrderReportList[k].OrderContract.Right == curPosition.PositionContract.Right)
                                    {
                                        closeValue3   = m_OrderReportList[k].CurOrder.LmtPrice - m_ReportList[i * 2][0].BidPrice - curPosition.PositionContract.Strike;
                                        orderLmtPrice = m_OrderReportList[k].CurOrder.LmtPrice;
                                        break;
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
            }

            if (optValues[maxValueIndex] - m_WheeledThreshold > closeValue1 || optValues[maxValueIndex] - m_WheeledThreshold > closeValue2 || optValues[maxValueIndex] - m_WheeledThreshold > closeValue3)//可以轮动
            {
                oneEntrust = new Entrust();
                oneEntrust.EntrustContract = closePosition.PositionContract;
                Order oneOrder = new Order();
                oneOrder.Action        = OrderActionType.Buy;
                oneOrder.OrderType     = "LMT";
                oneOrder.TotalQuantity = closePosition.PositionNum;
                oneOrder.Account       = StrategyPool.Account;
                double sellValue = closeValue1;
                if (optValues[maxValueIndex] - m_WheeledThreshold > closeValue1)
                {
                    oneOrder.LmtPrice = closeReport.AskPrice;;
                }
                else if (optValues[maxValueIndex] - m_WheeledThreshold > closeValue2)
                {
                    oneOrder.LmtPrice = closeReport.BidPrice;
                    sellValue         = closeValue2;
                }
                else if (optValues[maxValueIndex] - m_WheeledThreshold > closeValue3)
                {
                    oneOrder.LmtPrice = orderLmtPrice;
                    sellValue         = closeValue2;
                }
                oneEntrust.EntrustOrder = oneOrder;

                twoEntrust = new Entrust();
                twoEntrust.EntrustContract = m_ReportList[maxValueIndex * 2][0].MdContract;
                Order twoOrder = new Order();
                twoOrder.Action         = OrderActionType.Sell;
                twoOrder.OrderType      = "LMT";
                twoOrder.TotalQuantity  = closePosition.PositionNum;
                twoOrder.Account        = StrategyPool.Account;
                twoOrder.LmtPrice       = m_ReportList[maxValueIndex * 2][0].BidPrice;
                twoEntrust.EntrustOrder = twoOrder;

                entrustList = new List <Entrust>();
                entrustList.Add(oneEntrust);
                entrustList.Add(twoEntrust);
                Log.WriteLine(DateTime.Now.ToString() + "  卖出持仓行权价 " + closePosition.PositionContract.Strike + "   卖出价格    " + oneOrder.LmtPrice + "   卖出价值    " + sellValue + " 买入行权价  " + m_ReportList[maxValueIndex * 2][0].MdContract.Strike + "   买入价格  " + m_ReportList[maxValueIndex * 2][0].AskPrice + "   买入价值  " + optValues[maxValueIndex]);
            }
            if (entrustList != null)
            {
                return(entrustList.ToArray());
            }
            return(null);
        }
Exemplo n.º 23
0
        protected override void RunStrategy()
        {
            #region 计算总持仓手数
            //持仓总手数
            int totalMktQty = 0;

            //各个行权价的持仓
            int[] mktQty = new int[m_ContractList.Length];
            for (int i = 0; i < m_ContractList.Length; i++)
            {
                for (int j = 0; j < m_PositionList.Count; j++)
                {
                    Position curPosition = m_PositionList[j];
                    if (curPosition.PositionContract.Expiry == m_ContractList[i].Expiry)
                    {
                        int postionNum = Math.Abs(curPosition.PositionNum);
                        mktQty[i]   += postionNum;
                        totalMktQty += postionNum;
                    }
                }
            }
            #endregion

            #region 持仓异常检测,如有持仓异常,中断程序执行
            if (totalMktQty > m_BasePosition)
            {
                Log.WriteLine("持仓异常,持仓数超过最大持仓值:" + totalMktQty);
                Thread.Sleep(60000);
                return;
            }
            #endregion
            if (m_ReportList[0].Count > 0 && m_ReportList[0][0].AskPrice != 0 && m_ReportList[0][0].BidPrice != 0 &&
                m_ReportList[1].Count > 0 && m_ReportList[1][0].AskPrice != 0 && m_ReportList[1][0].BidPrice != 0)
            {
                Entrust[] entrustList = GetEntrustList();

                if (totalMktQty == m_BasePosition)//满仓状态下只处理平仓信号
                {
                    if (m_OrderReportList.Count > 0)
                    {
                        CancelQueueingOrder(entrustList);
                    }
                    else
                    {
                        DateTime curTime = m_ReportList[0][0].Time;
                        //在交易的最后1分钟,禁止减仓
                        if (curTime.Hour != 16 || (curTime.Hour == 16 && curTime.Minute < 29))
                        {
                            //只平仓
                            if (entrustList != null)
                            {
                                Entrust curOrder = entrustList[0];
                                for (int i = 0; i < m_PositionList.Count; i++)
                                {
                                    if (m_PositionList[i].PositionContract.Expiry == curOrder.EntrustContract.Expiry)
                                    {
                                        ReqOrderInsert(m_StrategyPool.GetValidId(), curOrder.EntrustContract, curOrder.EntrustOrder);
                                        Log.WriteStrategySignal(m_StrategyName, DateTime.Now.ToString() + "  卖出品种  " + entrustList[0].EntrustContract.Expiry
                                                                + "  卖出价格   " + entrustList[0].EntrustOrder.LmtPrice + "  买入价格  " + entrustList[1].EntrustOrder.LmtPrice);

                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                else if (totalMktQty < m_BasePosition)//仓位不够时生成开仓信号
                {
                    if (m_OrderReportList.Count > 0)
                    {
                        CancelQueueingOrder(entrustList);
                    }
                    else
                    {
                        if (entrustList != null)
                        {
                            Entrust curOrder = entrustList[1];
                            ReqOrderInsert(m_StrategyPool.GetValidId(), curOrder.EntrustContract, curOrder.EntrustOrder);
                            Log.WriteStrategySignal(m_StrategyName, DateTime.Now.ToString() + "  卖出品种  " + entrustList[0].EntrustContract.Expiry
                                                    + "  卖出价格   " + entrustList[0].EntrustOrder.LmtPrice + "  买入价格  " + entrustList[1].EntrustOrder.LmtPrice);
                        }
                    }
                }
            }
        }
Exemplo n.º 24
0
 public void Add(Entrust entrust)
 {
     _context.Entrusts.Add(entrust);
 }
Exemplo n.º 25
0
        private void GetVThread(object obj)
        {
            double Nz = zedGraphControl.GraphPane.YAxis.Scale.Max - zedGraphControl.GraphPane.YAxis.Scale.Min;
            double Nx = zedGraphControl.GraphPane.XAxis.Scale.Max - zedGraphControl.GraphPane.XAxis.Scale.Min;

            float[,] v = new float[(int)Nx, (int)Nz];
            Invoke(new EventHandler(() =>
            {
                DigitalModelProgressBar.Visible = true;
                DigitalModelProgressBar.Value   = 0;
                DigitalModelProgressBar.Minimum = 0;
                DigitalModelProgressBar.Maximum = (int)Nx;
                progressTip.Visible             = true;
                progressTip.Text   = "正在转化为数字模型...";
                toolStrip.Enabled  = false;
                menuStrip1.Enabled = false;
            }));

            for (int ix = 0; ix < Nx; ix++)
            {
                for (int iz = 0; iz < Nz; iz++)
                {
                    if (GetV(ix, iz) == -1)
                    {
                        Invoke(new EventHandler(() =>
                        {
                            DigitalModelProgressBar.Visible = false;
                            progressTip.Visible             = false;
                        }));
                        MessageBox.Show("图形中存在空缺!");
                        Invoke(new EventHandler(() =>
                        {
                            DigitalModelProgressBar.Visible = false;
                            progressTip.Visible             = false;
                            toolStrip.Enabled  = true;
                            menuStrip1.Enabled = true;
                        }));
                        return;
                    }
                    else
                    {
                        v[ix, iz] = GetV(ix, iz);
                    }
                    Invoke(new EventHandler(() =>
                    {
                        DigitalModelProgressBar.Value = ix + 1;
                    }));
                }
            }
            Invoke(new EventHandler(() =>
            {
                DigitalModelProgressBar.Visible = false;
                progressTip.Visible             = false;
                toolStrip.Enabled  = true;
                menuStrip1.Enabled = true;
                ForwardCalculationToolStripMenuItem.Enabled = true;
            }));
            Entrust callback = obj as Entrust;//强转为委托

            callback(v);
        }
Exemplo n.º 26
0
        public JsonResult AddJson(AddSale addSale)
        {
            Response _res             = new Response();
            int      id               = int.Parse(Session["UserID"].ToString());
            double   personCoinAmount = 0.00;

            try
            {
                personCoinAmount = _walletManager.GetWallet(id, addSale.PayCoin).Amount;
            }
            catch
            {
            }
            string _psd = null;

            if (Amount < addSale.Amount)
            {
                _res.Code    = 0;
                _res.Message = "超过该委托寄售的货币数量";
                return(Json(_res));
            }
            int identyId = _userManager.Find(id).FKIdentyID;

            if (string.IsNullOrEmpty(_identy.Find(identyId).Password))
            {
                _res.Code    = 0;
                _res.Message = "请先设置交易密码";
                return(Json(_res));
            }
            try { _psd = Security.SHA256(addSale.Password); }
            catch { _res.Code = 0; _res.Message = "请先输入交易密码"; return(Json(_res)); }

            if (_psd != _userManager.Find(id).UserIdenty.Password)
            {
                _res.Code    = 0;
                _res.Message = "交易密码错误";
                return(Json(_res));
            }
            if (personCoinAmount == 0.00 || (addSale.price * Amount) > personCoinAmount)
            {
                _res.Code    = 0;
                _res.Message = "钱包余额不足,请前往充值";
                return(Json(_res));
            }
            if (ModelState.IsValid)
            {
                string cointocoin = addSale.SellCoin + "/" + addSale.PayCoin;
                //减少支付货币
                Wallet _wallet = _walletManager.GetWallet(id, addSale.PayCoin);
                _wallet.Amount -= addSale.Amount * addSale.price;
                _walletManager.Update(_wallet);
                //委托方增加货币
                Wallet _entrustWallet = _walletManager.GetWallet(EntrusterID, addSale.PayCoin);
                _entrustWallet.Amount += addSale.Amount * addSale.price;
                _walletManager.Update(_entrustWallet);

                //更新委托 如果委托数量为零 则标记委托成功 记1,添加成功时间
                Entrust _entrust = new Entrust();
                _entrust = _entrustManager.Find(ID);
                if (Amount - addSale.Amount == 0)
                {
                    _entrust.IsSuccess    = 1;
                    _entrust.SucOrDefTime = DateTime.Now;
                    _entrustManager.Update(_entrust);
                }

                //添加委托详情表
                EntrustDetails _entrustDetails = new EntrustDetails();
                _entrustDetails.Amount    = addSale.Amount;
                _entrustDetails.BuyerID   = id;
                _entrustDetails.SellID    = _entrustManager.Find(ID).FUserID;
                _entrustDetails.EntrustID = EntrustID;
                _entrustsDetailsManager.Add(_entrustDetails);

                //一笔交易成功 添加一日中每一笔的价格表
                PriceInADeal _priceInADeal = new PriceInADeal();
                _priceInADeal.DealTime = DateTime.Now;
                _priceInADeal.Amount   = addSale.Amount;
                _priceInADeal.Price    = addSale.price;
                PriceInDay pd = _priceInDayManager.Find(u => u.CoinToCoin == cointocoin);
                _priceInADeal.PriceInDayID = pd.ID;
                _priceInADealManager.Add(_priceInADeal);



                //一笔交易进来判断是否为第一笔(总表内是否有该天的数据)
                try    //不为空 不是第一笔 更新该数据,设置priceinday的 up volumeInday等属性
                {
                    DateTime   time = _priceInADeal.DealTime;
                    PriceTable pt   = _priceTableManager.IfFirstOrNo(cointocoin, time);
                    pt.Amount += _priceInADeal.Amount;
                    if (pt.MaxPrice < _priceInADeal.Price)
                    {
                        pt.MaxPrice = _priceInADeal.Price;
                    }
                    if (pt.MinPrice > _priceInADeal.Price)
                    {
                        pt.MinPrice = _priceInADeal.Price;
                    }
                    pt.ClosingPrice = _priceInADeal.Price;
                    _priceTableManager.Update(pt);
                    //更新PriceInADay
                    if (pd.MaxInDay < _priceInADeal.Price)
                    {
                        pd.MaxInDay = _priceInADeal.Price;
                    }
                    if (pd.MinInDay > _priceInADeal.Price)
                    {
                        pd.MinInDay = _priceInADeal.Price;
                    }
                    pd.Up           = (_priceInADeal.Price - pd.Price) / pd.Price;
                    pd.Price        = _priceInADeal.Price;
                    pd.VolumeInDay += _priceInADeal.Price * _priceInADeal.Amount;
                    pd.AmountInDay += _priceInADeal.Amount;
                }
                catch    //为空 总表添加该天的数据
                {
                    PriceTable pt = new PriceTable()
                    {
                        KDateTime    = DateTime.Now,
                        CoinToCoin   = cointocoin,
                        OpeningPrice = _priceInADeal.Price,
                        ClosingPrice = _priceInADeal.Price,
                        MaxPrice     = _priceInADeal.Price,
                        MinPrice     = _priceInADeal.Price,
                        Amount       = _priceInADeal.Amount,
                    };
                    _priceTableManager.Add(pt);
                    //更新priceInADay
                    pd.MaxInDay    = _priceInADeal.Price;
                    pd.MinInDay    = _priceInADeal.Price;
                    pd.Price       = _priceInADeal.Price;
                    pd.Up          = 0;
                    pd.VolumeInDay = _priceInADeal.Price * _priceInADeal.Amount;
                    pd.AmountInDay = _priceInADeal.Amount;
                }
                //更新priceInDay
                _priceInDayManager.Update(pd);



                //增加购买的货币
                Wallet _wallet2 = _walletManager.GetWallet(id, addSale.SellCoin);
                _wallet2.Amount += addSale.Amount;
                _walletManager.Update(_wallet2);
                //委托方减少货币,发布委托时已经减少了
                //Wallet _entrustWallet2 = _walletManager.GetWallet(EntrusterID, addSale.SellCoin);
                //_entrustWallet2.Amount -= addSale.Amount;
                //_walletManager.Update(_entrustWallet2);
            }
            else
            {
                _res.Code    = 0;
                _res.Message = General.GetModelErrorString(ModelState);
                return(Json(_res));
            }
            _res.Code    = 1;
            _res.Message = "购买成功";
            return(Json(_res));
        }
Exemplo n.º 27
0
 public ActionResult PostEntrust(Entrust entrust)
 {
     return(View());
 }
Exemplo n.º 28
0
        public ActionResult Detail(string id, string submitType)
        {
            bool     buy   = false;
            DateTime start = DateTime.Parse(DateTime.Today.ToString("yyyy-MM-dd 0:0:0"));
            DateTime end   = DateTime.Parse(DateTime.Today.ToString("yyyy-MM-dd 23:59:59"));

            switch (submitType)
            {
            case "BUY":
            {
                buy = true;
                int     count   = int.Parse(Request.Form["BuyCount"]);
                int     pid     = int.Parse(Request.Form["pid"]);
                decimal price   = decimal.Parse(Request.Form["BuyPrice"]);
                var     entrust = new Entrust()
                {
                    IsBuy       = buy,
                    Price       = price,
                    Count       = count,
                    DealedCount = 0,
                    UserId      = CurrentUser.Id,
                    ProductId   = pid,
                    CreateTime  = DateTime.Now
                };


                int     eid          = mr.CreateEntrust(entrust);
                decimal dealedAmount = 0M;

                //冻结用户委托金额
                CurrentUser.FrozenScore += (count * price);

                #region 处理交易
                var saleEntrusts = mr.GetEntrusts(new MarketCriteria {
                        IsBuy = 0, ProductId = pid, Cancelled = 0, StartDate = start, EndDate = end
                    })
                                   .Where(e => e.Price <= price).OrderBy(e => e.Price).ThenByDescending(e => e.Id);

                if (saleEntrusts != null && saleEntrusts.Any())
                {
                    bool dealed = false;
                    foreach (var e in saleEntrusts)
                    {
                        if (dealed)
                        {
                            break;
                        }
                        decimal amount      = 0M;
                        Guid    tid         = Guid.NewGuid();
                        int     acutalCount = 0;
                        // 80,  100 - 30 or 0
                        if ((e.Count - e.DealedCount) >= (entrust.Count - entrust.DealedCount))         //此笔交易可完成
                        {
                            acutalCount           = entrust.Count - entrust.DealedCount;
                            amount                = (acutalCount) * e.Price;
                            e.DealedAmount       += (acutalCount) * e.Price;
                            dealedAmount         += e.DealedAmount;
                            e.DealedCount        += (acutalCount);
                            entrust.DealedAmount += (acutalCount) * e.Price;
                            entrust.DealedCount   = entrust.Count;
                            entrust.Status        = 1;
                            if (e.DealedCount == e.Count)
                            {
                                e.Status = 1;
                            }
                            else
                            {
                                e.Status = 2;
                            }

                            mr.UpdateEntrust(e);
                            dealed = true;
                            // break;
                        }
                        else         //需更多笔交易
                        {
                            acutalCount           = e.Count - e.DealedCount;
                            amount                = (acutalCount) * e.Price;
                            entrust.DealedAmount += acutalCount * e.Price;
                            dealedAmount         += acutalCount * e.Price;
                            entrust.DealedCount  += acutalCount;
                            e.DealedAmount       += acutalCount * e.Price;
                            e.DealedCount         = e.Count;

                            e.Status       = 1;
                            entrust.Status = 2;

                            mr.UpdateEntrust(e);
                        }
                        var user = ur.Get(e.UserId);
                        if (user != null)
                        {
                            user.TotalScore += amount;
                            ur.Update(user);
                            var uup = ur.GetProductByUser(e.ProductId, e.UserId);
                            uup.FrozenCount -= acutalCount;
                            uup.TotalCount  -= acutalCount;

                            ur.UpdateUserProduct(uup);

                            var score = new UserScore
                            {
                                TypeId     = (int)ScoreType.出售,
                                UserId     = user.Id,
                                ChargeFee  = 0,
                                Score      = amount,
                                CreateTime = DateTime.Now,
                                Status     = 1,
                                UserPath   = user.RefUserPath
                            };
                            new UserScoreRepository().Create(score);
                        }


                        var tbuy = new Transaction
                        {
                            Count         = acutalCount,
                            IsBuy         = true,
                            UserId        = entrust.UserId,
                            CreateTime    = DateTime.Now,
                            Date          = DateTime.Today,
                            Price         = e.Price,
                            ProductId     = e.ProductId,
                            ChargeFee     = 0,
                            TransactionId = tid
                        };
                        var tsell = new Transaction
                        {
                            Count         = acutalCount,
                            IsBuy         = false,
                            UserId        = e.UserId,
                            CreateTime    = DateTime.Now,
                            Date          = DateTime.Today,
                            Price         = e.Price,
                            ProductId     = e.ProductId,
                            ChargeFee     = 0,
                            TransactionId = tid
                        };
                        mr.CreateTransaction(tbuy);
                        mr.CreateTransaction(tsell);
                    }
                    mr.UpdateEntrust(entrust);
                }
                if (entrust.Status == 1)
                {
                    CurrentUser.FrozenScore -= (count * price);
                }
                else
                {
                    CurrentUser.FrozenScore -= dealedAmount;
                }
                var up = ur.GetProductByUser(entrust.ProductId, CurrentUser.Id);
                if (up == null)
                {
                    up = new UserProduct
                    {
                        ProductId   = entrust.ProductId,
                        FrozenCount = 0,
                        UserId      = CurrentUser.Id,
                        TotalCount  = entrust.DealedCount,
                        CreateTime  = DateTime.Now,
                        UpdateTime  = DateTime.Now
                    };
                    ur.CreateUserProduct(up);
                }
                else
                {
                    up.TotalCount += entrust.DealedCount;
                    up.UpdateTime  = DateTime.Now;
                    ur.UpdateUserProduct(up);
                }
                #endregion

                CurrentUser.TotalScore -= dealedAmount;
                ur.Update(CurrentUser);
                RefreshCurrentUser();

                if (dealedAmount > 0)
                {
                    var score = new UserScore
                    {
                        TypeId     = (int)ScoreType.购买,
                        UserId     = CurrentUser.Id,
                        ChargeFee  = 0,
                        Score      = dealedAmount,
                        CreateTime = DateTime.Now,
                        Status     = 1,
                        UserPath   = CurrentUser.RefUserPath
                    };
                    new UserScoreRepository().Create(score);
                }
            }
            break;

            case "SALE":
            {
                int     count        = int.Parse(Request.Form["SaleCount"]);
                int     pid          = int.Parse(Request.Form["pid"]);
                decimal price        = decimal.Parse(Request.Form["SalePrice"]);
                int     dealedCount  = 0;
                decimal dealedAmount = 0M;
                var     entrust      = new Entrust()
                {
                    IsBuy       = buy,
                    Price       = price,
                    Count       = count,
                    DealedCount = 0,
                    UserId      = CurrentUser.Id,
                    ProductId   = pid,
                    CreateTime  = DateTime.Now
                };
                //冻结用户委托产品
                var up = ur.GetProductsByUser(CurrentUser.Id).First(p => p.Product.ProductCode == id);
                up.FrozenCount += count;

                int eid = mr.CreateEntrust(entrust);

                #region 处理交易

                var buyEntrusts = mr.GetEntrusts(new MarketCriteria {
                        IsBuy = 1, ProductId = pid, Cancelled = 0, StartDate = start, EndDate = end
                    })
                                  .Where(e => e.Price >= price).OrderByDescending(e => e.Price).ThenByDescending(e => e.Id);

                if (buyEntrusts != null && buyEntrusts.Any())
                {
                    bool dealed = false;
                    foreach (var e in buyEntrusts)
                    {
                        if (dealed)
                        {
                            break;
                        }
                        decimal amount      = 0M;
                        Guid    tid         = Guid.NewGuid();
                        int     acutalCount = 0;
                        // 80,  100 - 30 or 0
                        if ((e.Count - e.DealedCount) >= (entrust.Count - entrust.DealedCount))         //此笔交易可完成
                        {
                            acutalCount           = entrust.Count - entrust.DealedCount;
                            amount                = (acutalCount) * e.Price;
                            e.DealedAmount       += (acutalCount) * e.Price;
                            dealedCount          += acutalCount;
                            e.DealedCount        += (acutalCount);
                            entrust.DealedAmount += (acutalCount) * e.Price;
                            entrust.DealedCount   = entrust.Count;
                            entrust.Status        = 1;
                            if (e.DealedCount == e.Count)
                            {
                                e.Status = 1;
                            }
                            else
                            {
                                e.Status = 2;
                            }
                            dealedAmount += amount;
                            mr.UpdateEntrust(e);
                            dealed = true;
                            //break;
                        }
                        else         //需更多笔交易
                        {
                            acutalCount           = e.Count - e.DealedCount;
                            amount                = (acutalCount) * e.Price;
                            entrust.DealedAmount += acutalCount * e.Price;
                            dealedCount          += acutalCount;
                            entrust.DealedCount  += acutalCount;
                            e.DealedAmount       += acutalCount * e.Price;
                            e.DealedCount         = e.Count;

                            e.Status       = 1;
                            entrust.Status = 2;

                            mr.UpdateEntrust(e);
                            dealedAmount += amount;
                        }
                        var user = ur.Get(e.UserId);
                        if (user != null)
                        {
                            user.FrozenScore -= amount;
                            user.TotalScore  -= amount;
                            ur.Update(user);
                            var uup = ur.GetProductByUser(e.ProductId, e.UserId);
                            //uup.FrozenCount -= acutalCount;
                            uup.TotalCount += acutalCount;
                            ur.UpdateUserProduct(uup);

                            var score = new UserScore
                            {
                                TypeId     = (int)ScoreType.购买,
                                UserId     = user.Id,
                                ChargeFee  = 0,
                                Score      = amount,
                                CreateTime = DateTime.Now,
                                Status     = 1,
                                UserPath   = user.RefUserPath
                            };
                            new UserScoreRepository().Create(score);
                        }
                        var tbuy = new Transaction
                        {
                            Count         = acutalCount,
                            IsBuy         = true,
                            UserId        = e.UserId,
                            CreateTime    = DateTime.Now,
                            Date          = DateTime.Today,
                            Price         = e.Price,
                            ProductId     = e.ProductId,
                            ChargeFee     = 0,
                            TransactionId = tid
                        };
                        var tsell = new Transaction
                        {
                            Count         = acutalCount,
                            IsBuy         = false,
                            UserId        = entrust.UserId,
                            CreateTime    = DateTime.Now,
                            Date          = DateTime.Today,
                            Price         = e.Price,
                            ProductId     = e.ProductId,
                            ChargeFee     = 0,
                            TransactionId = tid
                        };
                        mr.CreateTransaction(tbuy);
                        mr.CreateTransaction(tsell);
                    }
                    mr.UpdateEntrust(entrust);
                }

                #endregion
                if (dealedCount > 0)
                {
                    var score = new UserScore
                    {
                        TypeId     = (int)ScoreType.出售,
                        UserId     = CurrentUser.Id,
                        ChargeFee  = 0,
                        Score      = dealedAmount,
                        CreateTime = DateTime.Now,
                        Status     = 1,
                        UserPath   = CurrentUser.RefUserPath
                    };
                    new UserScoreRepository().Create(score);
                    up.FrozenCount -= dealedCount;
                    up.TotalCount  -= dealedCount;
                    ur.UpdateUserProduct(up);
                    ur.Update(CurrentUser);
                    RefreshCurrentUser();
                }
            }
            break;

            case "REVOKE":
            {
                int eid = int.Parse(Request.Form["eid"]);
                var e   = mr.GetEntrustById(eid);
                //解冻用户委托金额
                if (e.IsBuy)
                {
                    CurrentUser.FrozenScore -= (e.Count - e.DealedCount) * e.Price;
                    ur.Update(CurrentUser);
                    RefreshCurrentUser();
                }
                //冻结用户委托产品
                else
                {
                    var up = ur.GetProductsByUser(CurrentUser.Id).First(p => p.ProductId == e.ProductId);
                    up.FrozenCount += (e.Count - e.DealedCount);
                    ur.UpdateUserProduct(up);
                }
                mr.CancelEntrust(e);
                if (Request.IsAjaxRequest())
                {
                    return(Content("1"));
                }
            }
            break;

            default: break;
            }

            return(RedirectToAction("Detail", new { id = id }));
        }
Exemplo n.º 29
0
        protected override void RunStrategy()
        {
            int strikeCount = m_ContractList.Length / 2;

            #region 计算总持仓手数
            //持仓总手数
            int totalMktQty = 0;

            //各个行权价的持仓
            int[] optMktQty = new int[strikeCount];
            for (int i = 0; i < strikeCount; i++)
            {
                for (int j = 0; j < m_PositionList.Count; j++)
                {
                    Position curPosition = m_PositionList[j];
                    if (curPosition.PositionContract.Right == m_BasePostionRight && curPosition.PositionContract.Strike == m_ContractList[i * 2].Strike)
                    {
                        int postionNum = Math.Abs(curPosition.PositionNum);
                        optMktQty[i] += postionNum;
                        totalMktQty  += postionNum;
                    }
                }
            }
            #endregion

            #region 通过买入对手价计算每对期权对应的价值,并找到价值最高的品种

            double[] optValues     = new double[strikeCount];
            int      maxValueIndex = -1;
            double   maxValue      = double.MinValue;
            for (int i = 0; i < strikeCount; i++)
            {
                optValues[i] = double.MinValue;
                //C、P期权无价格或持仓市值达到上限时,不参与最低价格的计算
                if (m_ReportList[i * 2][0].AskPrice != 0 && m_ReportList[i * 2 + 1][0].BidPrice != 0)
                {
                    if (optMktQty[i] < m_BaseMktQty)
                    {
                        optValues[i] = m_ReportList[i * 2 + 1][0].BidPrice - m_ReportList[i * 2][0].AskPrice - m_ContractList[i * 2].Strike;
                        if (optValues[i] > maxValue)
                        {
                            maxValue      = optValues[i];
                            maxValueIndex = i;
                        }
                    }
                }
                else
                {
                    return;//如果行情还没有准备好,不用继续跑策略的逻辑
                }
            }

            #endregion

            //优先考虑单腿的情况
            Entrust sellPutEntrust  = null; //卖出看跌期权订单
            Entrust buyPutEntrust   = null; //买入看涨期权订单
            Entrust sellCallEntrust = null;
            Entrust buyCallEntrust  = null;

            #region 根据基准持仓方向获取单腿订单,同时在不需要单腿处理的时候根据买卖价差调整基准买卖方向

            if (m_BasePostionRight == ContractRight.Call)
            {
                sellPutEntrust = GetSellPutEntrust();
                if (sellPutEntrust == null)
                {
                    buyPutEntrust = GetBuyPutEntrust();
                }
                //当不存在单腿且不用开新仓时,通过持仓品种的买卖价差确定基准持仓方向
                if (sellPutEntrust == null && buyPutEntrust == null && m_BaseMktQty <= totalMktQty)
                {
                    for (int j = 0; j < m_PositionList.Count; j++)
                    {
                        Position callPosition = m_PositionList[j];
                        if (callPosition.PositionContract.Right == ContractRight.Call && callPosition.PositionNum > 0)
                        {
                            //遍历得到Call的买卖价差
                            double callBidAskOffset = double.MaxValue;
                            for (int i = 0; i < m_ContractList.Length / 2; i++)
                            {
                                if (m_ReportList[i * 2][0].MdContract.Strike == callPosition.PositionContract.Strike)//m_Reports[i * 2]是Call
                                {
                                    callBidAskOffset = m_ReportList[i * 2][0].AskPrice - m_ReportList[i * 2][0].BidPrice;
                                    break;
                                }
                            }
                            //寻找Call持仓对应的Put持仓并遍历得到Put的买卖价差
                            Position putPosition     = null;
                            double   putBidAskOffset = double.MaxValue;
                            for (int k = 0; k < m_PositionList.Count; k++)
                            {
                                if (m_PositionList[k].PositionContract.Strike == callPosition.PositionContract.Strike && m_PositionList[k].PositionContract.Expiry == callPosition.PositionContract.Expiry && m_PositionList[k].PositionContract.Right == ContractRight.Put)
                                {
                                    putPosition = m_PositionList[k];
                                    for (int i = 0; i < m_ContractList.Length / 2; i++)
                                    {
                                        if (m_ReportList[i * 2 + 1][0].MdContract.Strike == callPosition.PositionContract.Strike)//m_Reports[i * 2 + 1]是Put
                                        {
                                            putBidAskOffset = m_ReportList[i * 2 + 1][0].AskPrice - m_ReportList[i * 2 + 1][0].BidPrice;
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                            if (callBidAskOffset < putBidAskOffset)
                            {
                                m_BasePostionRight = ContractRight.Put;
                                break;
                            }
                        }
                    }
                }
            }
            else
            {
                sellCallEntrust = GetSellCallEntrust();
                if (sellCallEntrust == null)
                {
                    buyCallEntrust = GetBuyCallEntrust();
                }
                //当不存在单腿且不用开新仓时,通过持仓品种的买卖价差确定基准持仓方向
                if (sellCallEntrust == null && buyCallEntrust == null && m_BaseMktQty <= totalMktQty)
                {
                    for (int j = 0; j < m_PositionList.Count; j++)
                    {
                        Position putPosition = m_PositionList[j];
                        if (putPosition.PositionContract.Right == ContractRight.Put && putPosition.PositionNum > 0)
                        {
                            //遍历得到Put的买卖价差
                            double putBidAskOffset = double.MaxValue;
                            for (int i = 0; i < m_ContractList.Length / 2; i++)
                            {
                                if (m_ReportList[i * 2 + 1][0].MdContract.Strike == putPosition.PositionContract.Strike)//m_Reports[i * 2 + 1]是Put
                                {
                                    putBidAskOffset = m_ReportList[i * 2 + 1][0].AskPrice - m_ReportList[i * 2 + 1][0].BidPrice;
                                    break;
                                }
                            }
                            //寻找Put持仓对应的Call持仓并遍历得到Call的买卖价差
                            Position callPosition     = null;
                            double   callBidAskOffset = double.MaxValue;
                            for (int k = 0; k < m_PositionList.Count; k++)
                            {
                                if (m_PositionList[k].PositionContract.Strike == putPosition.PositionContract.Strike && m_PositionList[k].PositionContract.Expiry == putPosition.PositionContract.Expiry && m_PositionList[k].PositionContract.Right == ContractRight.Call)
                                {
                                    callPosition = m_PositionList[k];
                                    for (int i = 0; i < m_ContractList.Length / 2; i++)
                                    {
                                        if (m_ReportList[i * 2][0].MdContract.Strike == putPosition.PositionContract.Strike)//m_Reports[i * 2]是Call
                                        {
                                            callBidAskOffset = m_ReportList[i * 2][0].AskPrice - m_ReportList[i * 2][0].BidPrice;
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                            if (putBidAskOffset < callBidAskOffset)
                            {
                                m_BasePostionRight = ContractRight.Call;
                                break;
                            }
                        }
                    }
                }
            }

            #endregion

            Entrust[] entrusts = null;//轮动的买卖Call订单
            if (sellPutEntrust == null && buyPutEntrust == null && sellCallEntrust == null && buyCallEntrust == null)
            {
                if (m_BasePostionRight == ContractRight.Call)
                {
                    entrusts = GetCallOrders(optValues, maxValueIndex);
                }
                else
                {
                    entrusts = GetPutOrders(optValues, maxValueIndex);
                }
                if (m_BaseMktQty > totalMktQty)//需要开仓
                {
                    int offsetPosition = m_BaseMktQty - totalMktQty;
                    if (entrusts == null)
                    {
                        entrusts    = new Entrust[1];
                        entrusts[0] = new Entrust();
                        Order entrustOrder = new Order();
                        entrustOrder.OrderType     = "LMT";
                        entrustOrder.TotalQuantity = offsetPosition;
                        entrustOrder.Account       = StrategyPool.Account;
                        if (m_BasePostionRight == ContractRight.Call)
                        {
                            entrustOrder.Action         = OrderActionType.Buy;
                            entrustOrder.LmtPrice       = m_ReportList[maxValueIndex * 2][0].AskPrice;
                            entrusts[0].EntrustContract = m_ReportList[maxValueIndex * 2][0].MdContract;
                        }
                        else
                        {
                            entrustOrder.Action         = OrderActionType.Sell;
                            entrustOrder.LmtPrice       = m_ReportList[maxValueIndex * 2 + 1][0].BidPrice;
                            entrusts[0].EntrustContract = m_ReportList[maxValueIndex * 2 + 1][0].MdContract;
                        }
                        entrusts[0].EntrustOrder = entrustOrder;
                    }
                    Log.WriteLine(DateTime.Now.ToString() + " 买入行权价  " + m_ReportList[maxValueIndex * 2][0].MdContract.Strike + "   买入C价格  " + m_ReportList[maxValueIndex * 2][0].AskPrice + "   卖出P价格  " + m_ReportList[maxValueIndex * 2 + 1][0].BidPrice + " 价值  " + maxValue);
                }
            }

            if (sellPutEntrust != null || buyPutEntrust != null || sellCallEntrust != null || buyCallEntrust != null || entrusts != null)
            {
                if (m_OrderReportList.Count > 0)
                {
                    CancelQueueingOrder(sellPutEntrust, buyPutEntrust, sellCallEntrust, buyCallEntrust, entrusts);
                }
                else
                {
                    if (sellPutEntrust != null)
                    {
                        ReqOrderInsert(m_StrategyPool.GetValidId(), sellPutEntrust.EntrustContract, sellPutEntrust.EntrustOrder);
                    }
                    else if (buyPutEntrust != null)
                    {
                        ReqOrderInsert(m_StrategyPool.GetValidId(), buyPutEntrust.EntrustContract, buyPutEntrust.EntrustOrder);
                    }
                    else if (sellCallEntrust != null)
                    {
                        ReqOrderInsert(m_StrategyPool.GetValidId(), sellCallEntrust.EntrustContract, sellCallEntrust.EntrustOrder);
                    }
                    else if (buyCallEntrust != null)
                    {
                        ReqOrderInsert(m_StrategyPool.GetValidId(), buyCallEntrust.EntrustContract, buyCallEntrust.EntrustOrder);
                    }
                    else if (entrusts != null)
                    {
                        if (m_BaseMktQty > totalMktQty)//需要开仓
                        {
                            for (int i = 0; i < entrusts.Length; i++)
                            {
                                if ((m_BasePostionRight == ContractRight.Call && entrusts[i].EntrustOrder.Action == OrderActionType.Buy) ||
                                    (m_BasePostionRight == ContractRight.Put && entrusts[i].EntrustOrder.Action == OrderActionType.Sell))
                                {
                                    ReqOrderInsert(m_StrategyPool.GetValidId(), entrusts[i].EntrustContract, entrusts[i].EntrustOrder);
                                    break;
                                }
                            }
                        }
                        else//需要平仓
                        {
                            for (int i = 0; i < entrusts.Length; i++)
                            {
                                if ((m_BasePostionRight == ContractRight.Call && entrusts[i].EntrustOrder.Action == OrderActionType.Sell) ||
                                    (m_BasePostionRight == ContractRight.Put && entrusts[i].EntrustOrder.Action == OrderActionType.Buy))

                                {
                                    ReqOrderInsert(m_StrategyPool.GetValidId(), entrusts[i].EntrustContract, entrusts[i].EntrustOrder);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                CancelAllQueueingOrder();
            }
            //通过卖出对手价计算持仓对应的平价价格,如果可以轮动则轮动
            //if (tempPositionIndex != minValueIndex)
            //{
            //    if (m_Reports[tempPositionIndex * 2].BidPrice != 0 && m_Reports[tempPositionIndex * 2 + 1].AskPrice != 0)
            //    {
            //        double positionValue = m_Reports[tempPositionIndex * 2 + 1].AskPrice - m_Reports[tempPositionIndex * 2].BidPrice - m_ContractList[tempPositionIndex * 2].Strike;
            //        if (positionValue > minValue)
            //        {
            //            Log.WriteLine(DateTime.Now.ToString() +  "  卖出持仓行权价 " + m_ContractList[tempPositionIndex*2].Strike + "   卖出平价价格    " + positionValue + " 买入行权价  " + m_ContractList[minValueIndex * 2].Strike + "   买入平价价格  " + minValue);
            //            tempPositionIndex = minValueIndex;
            //        }
            //    }
            //}
        }