예제 #1
0
 void OnClosed(object sender, EventArgs e)
 {
     Kit.Msg($"{Title} - 关闭后事件");
 }
예제 #2
0
        private void BtAdd_Click(object sender, EventArgs e)
        {
            using (Form newKitForm = new Form())
            {
                Kit result = null;

                newKitForm.Text = "Aparat ekle";
                newKitForm.Size = new Size(320, 240);
                newKitForm.Font = new System.Drawing.Font("Century Gothic", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162)));


                Label lbName = new Label();
                lbName.Text = "Aparat İsmi";
                newKitForm.Controls.Add(lbName);
                lbName.Location = new Point(12, 9);
                lbName.AutoSize = true;

                TextBox tbName = new TextBox();
                tbName.Location = new Point(13, 9 + 19 + 9);
                tbName.Size     = new Size(200, 27);
                newKitForm.Controls.Add(tbName);

                Label lbUnitPrice = new Label();
                lbUnitPrice.Text = "Aparat Birim fiyatı";
                newKitForm.Controls.Add(lbUnitPrice);
                lbUnitPrice.Location = new Point(12, 9 + 19 + 9 + 27 + 9);
                lbUnitPrice.AutoSize = true;

                TextBox tbUnitPrice = new TextBox();
                tbUnitPrice.Location = new Point(13, 9 + 19 + 9 + 27 + 9 + 19 + 9);
                newKitForm.Controls.Add(tbUnitPrice);
                tbUnitPrice.Size = new Size(200, 27);

                Button saveButton = new Button();
                saveButton.Text     = "Kaydet";
                saveButton.Location = new Point(12, 9 + 19 + 9 + 27 + 9 + 19 + 9 + 27 + 9);
                saveButton.AutoSize = true;
                saveButton.Click   += (s, e2) =>
                {
                    try
                    {
                        result                  = new Kit();
                        result.Name             = tbName.Text;
                        result.UnitPrice        = Convert.ToDecimal(tbUnitPrice.Text.Replace(".", ","));
                        newKitForm.DialogResult = DialogResult.OK;
                        newKitForm.Close();
                    }
                    catch (Exception aa)
                    {
                        MessageBox.Show("Kaydedilemedi : " + aa.Message);
                    }
                };

                newKitForm.Controls.Add(saveButton);


                Button cancelButton = new Button();
                cancelButton.Text     = "İptal";
                cancelButton.AutoSize = true;
                cancelButton.Location = new Point(12 + 12 + saveButton.Width, 9 + 19 + 9 + 27 + 9 + 19 + 9 + 27 + 9);
                cancelButton.Click   += (s, e2) =>
                {
                    try
                    {
                        result = null;
                        newKitForm.DialogResult = DialogResult.Cancel;
                        newKitForm.Close();
                    }
                    catch (Exception aa)
                    {
                        MessageBox.Show("Kaydedilemedi : " + aa.Message);
                    }
                };

                newKitForm.Controls.Add(cancelButton);


                if (newKitForm.ShowDialog() == DialogResult.OK)
                {
                    Kit.Add(result);
                    listKits.Items.Add(result);
                }
            }
        }
예제 #3
0
 public EnvDTE.vsCommandStatus GetCommandStatus()
 {
     return(Kit.GetCommandStatusForModel());
 }
예제 #4
0
        public void compute()
        {
            SortedDictionary <DateTime, Dictionary <string, PositionsWithDetail> > positions = new SortedDictionary <DateTime, Dictionary <string, PositionsWithDetail> >();
            //初始化Account信息
            BasicAccount myAccount = new BasicAccount(initialAssets: initialCapital, totalAssets: initialCapital, freeCash: initialCapital);
            //记录历史账户信息
            List <BasicAccount> accountHistory = new List <BasicAccount>();
            List <double>       benchmark      = new List <double>();
            //标记当日跨式组合多空信号。1表示多头,0表示无信号,-1表示空头。
            double   orignalSignal = 0;
            Straddle holdingStatus = new Straddle();

            //统计历史波动率分位数,从回测期开始前一天,统计到最后一天
            double[][] fractile = new double[backTestingDuration + 1][];
            fractile = computeRollingFractile(startIndex - 1, etfDailyData.Count() - 1, 100);
            //统计隐含波动率
            computeImpv();
            //统计隐含波动率和历史波动率之差 epsilon=max[E(IV-HV),0]
            computeEpsilon();
            //按时间遍历,2015年02月09日50ETF期权上市开始,2月10日开始昨日收盘的隐含波动率数据。
            for (int i = startIndex + 1; i < startIndex + backTestingDuration; i++)
            {
                DateTime today = etfDailyData[i].time;
                //获取当日上市的期权合约列表
                var optionInfoList = OptionUtilities.getUnmodifiedOptionInfoList(this.optionInfoList, today);
                //若当日发生50ETF分红派息,myAccount要加上分红的钱,并且需要调整持有头寸的strike
                if (today == timeOf50ETFDividend2016 && positions.Count > 0 && positions.Last().Value.ContainsKey("510050.SH"))
                {
                    //50ETF的头寸中记入分红
                    positions.Last().Value["510050.SH"].totalCashFlow += positions.Last().Value["510050.SH"].volume * bonusOf50ETFDividend2016;
                    //期权持仓行权价调整
                    foreach (var item in optionInfoList)
                    {
                        if (item.optionCode == holdingStatus.callCode)
                        {
                            holdingStatus.strike        = item.strike;
                            holdingStatus.callPosition *= item.contractMultiplier / standardContractMultiplier;
                            holdingStatus.putPosition  *= item.contractMultiplier / standardContractMultiplier;
                        }
                    }
                }
                Dictionary <string, MinuteSignal> signal = new Dictionary <string, MinuteSignal>();
                double fractile90Yesterday = fractile[i - 1][9]; //昨日历史波动率90分位数
                double fractile70Yesterday = fractile[i - 1][7]; //昨日历史波动率70分位数
                double fractile50Yesterday = fractile[i - 1][5]; //昨日历史波动率50分位数
                double fractile30Yesterday = fractile[i - 1][3]; //昨日历史波动率30分位数
                double volYesterday        = etfVol[i - 1];      //昨日历史波动率
                double impvYesterday       = optionVol[i - 1];   //昨日隐含波动率
                //获取当日ATM期权合约代码

                double etfPrice = etfDailyData[i].close;
                double duration;
                //获取当日期限结构,选取当月合约,若当日合约到日期小于等于3天,直接开仓下月合约
                List <double> dateStructure = OptionUtilities.getDurationStructure(optionInfoList, today);
                double        duration0     = dateStructure[0] <= 3 ? dateStructure[1] : dateStructure[0];
                duration = duration0;
                var call      = OptionUtilities.getOptionListByOptionType(OptionUtilities.getOptionListByDuration(optionInfoList, today, duration), "认购").OrderBy(x => Math.Abs(x.strike - etfPrice)).Where(x => x.startDate <= today).ToList();
                var callATM   = call[0];
                var callPrice = Platforms.container.Resolve <OptionMinuteRepository>().fetchFromLocalCsvOrWindAndSave(callATM.optionCode, today);
                // double callImpv = ImpliedVolatilityUtilities.ComputeImpliedVolatility(callATM.strike, duration / 252.0, 0.04, 0, callATM.optionType, callPrice[0].close, etfPrice);
                var put      = OptionUtilities.getOptionListByOptionType(OptionUtilities.getOptionListByDuration(optionInfoList, today, duration), "认沽").OrderBy(x => Math.Abs(x.strike - callATM.strike)).ToList();
                var putATM   = put[0];
                var putPrice = Platforms.container.Resolve <OptionMinuteRepository>().fetchFromLocalCsvOrWindAndSave(putATM.optionCode, today);
                //double putImpv = ImpliedVolatilityUtilities.ComputeImpliedVolatility(putATM.strike, duration / 252.0, 0.04, 0, putATM.optionType, putPrice[0].close, etfPrice);
                //整合当日分钟线数据
                Dictionary <string, List <KLine> > dataToday = new Dictionary <string, List <KLine> >();
                var etfData = Platforms.container.Resolve <StockMinuteRepository>().fetchFromLocalCsvOrWindAndSave("510050.SH", today);
                dataToday.Add("510050.SH", etfData.Cast <KLine>().ToList());
                dataToday.Add(callATM.optionCode, callPrice.Cast <KLine>().ToList());
                dataToday.Add(putATM.optionCode, putPrice.Cast <KLine>().ToList());

                //策略信号处理
                //信号1
                //orignalSignal = 0;
                //if (volYesterday >= fractile70Yesterday)
                //{
                //    //卖出跨式期权
                //    orignalSignal = -1;
                //}
                //else if (impvYesterday < volYesterday)
                //{
                //    //买入跨式期权
                //    orignalSignal = 1;
                //}
                //else if (impvYesterday - volYesterday > epsilon[i - 1])
                //{
                //    //卖出跨式期权
                //    orignalSignal = -1;
                //}
                //信号2
                orignalSignal = 0;
                if (volYesterday - impvYesterday > 0 && volYesterday <= fractile50Yesterday)
                {
                    //买入跨式期权
                    orignalSignal = 1;
                }
                else if (impvYesterday - volYesterday > epsilon[i - 1])
                {
                    //卖出跨式期权
                    orignalSignal = -1;
                }

                //指定平仓时间为开盘第一个分钟。
                int      openIndex = 0;
                DateTime now       = TimeListUtility.IndexToMinuteDateTime(Kit.ToInt_yyyyMMdd(today), openIndex);
                Console.WriteLine("time: {0}, 昨日历史波动率: {1}, 历史波动率70分位数: {2}, 昨日隐含波动率: {3}", now, volYesterday.ToString("N"), fractile70Yesterday.ToString("N"), optionVol[i - 1].ToString("N"));
                //如果有持仓先判断持仓状态和信号方向是否相同,如果不同先平仓
                if (holdingStatus.callPosition != 0)
                {
                    if (dataToday.ContainsKey(holdingStatus.callCode) == false)
                    {
                        var callLastDay = Platforms.container.Resolve <OptionMinuteRepository>().fetchFromLocalCsvOrWindAndSave(holdingStatus.callCode, today);
                        dataToday.Add(holdingStatus.callCode, callLastDay.Cast <KLine>().ToList());
                    }
                    if (dataToday.ContainsKey(holdingStatus.putCode) == false)
                    {
                        var putLastDay = Platforms.container.Resolve <OptionMinuteRepository>().fetchFromLocalCsvOrWindAndSave(holdingStatus.putCode, today);
                        dataToday.Add(holdingStatus.putCode, putLastDay.Cast <KLine>().ToList());
                    }
                    if (holdingStatus.callPosition * orignalSignal < 0) //仓位和信号相反,强制平仓
                    {
                        Console.WriteLine("平仓!");

                        MinuteCloseAllWithBar.CloseAllPosition(dataToday, ref positions, ref myAccount, now, openIndex, slipPoint);
                        holdingStatus = new Straddle();
                    }
                    if (DateUtils.GetSpanOfTradeDays(today, holdingStatus.endDate) <= 3) //有仓位无信号,判断是否移仓
                    {
                        Console.WriteLine("平仓!");
                        MinuteCloseAllWithBar.CloseAllPosition(dataToday, ref positions, ref myAccount, now, openIndex, slipPoint);
                        holdingStatus = new Straddle();
                    }
                }
                //指定开仓时间为开盘第10分钟。错开开平仓的时间。
                openIndex = 10;
                now       = TimeListUtility.IndexToMinuteDateTime(Kit.ToInt_yyyyMMdd(today), openIndex);
                if (holdingStatus.callPosition == 0 && orignalSignal != 0) //无仓位有信号,开仓
                {
                    if (orignalSignal == 1)                                //做多跨式期权
                    {
                        MinuteSignal openSignalCall = new MinuteSignal()
                        {
                            code = callATM.optionCode, volume = optionVolume, time = now, tradingVarieties = "option", price = callPrice[openIndex].open, minuteIndex = openIndex
                        };
                        MinuteSignal openSignalPut = new MinuteSignal()
                        {
                            code = putATM.optionCode, volume = optionVolume, time = now, tradingVarieties = "option", price = putPrice[openIndex].open, minuteIndex = openIndex
                        };
                        Console.WriteLine("做多跨式期权!");
                        signal.Add(callATM.optionCode, openSignalCall);
                        signal.Add(putATM.optionCode, openSignalPut);
                        //变更持仓状态
                        holdingStatus.callCode           = callATM.optionCode;
                        holdingStatus.putCode            = putATM.optionCode;
                        holdingStatus.callPosition       = optionVolume;
                        holdingStatus.putPosition        = optionVolume;
                        holdingStatus.etfPrice_open      = etfData[openIndex].open;
                        holdingStatus.straddlePrice_open = callPrice[openIndex].close + putPrice[openIndex].open;
                        holdingStatus.straddleOpenDate   = today;
                        holdingStatus.endDate            = callATM.endDate;
                        holdingStatus.strike             = callATM.strike;
                    }
                    else if (orignalSignal == -1) //做空跨式期权
                    {
                        MinuteSignal openSignalCall = new MinuteSignal()
                        {
                            code = callATM.optionCode, volume = -optionVolume, time = now, tradingVarieties = "option", price = callPrice[openIndex].open, minuteIndex = openIndex
                        };
                        MinuteSignal openSignalPut = new MinuteSignal()
                        {
                            code = putATM.optionCode, volume = -optionVolume, time = now, tradingVarieties = "option", price = putPrice[openIndex].open, minuteIndex = openIndex
                        };
                        Console.WriteLine("做空跨式期权!");
                        signal.Add(callATM.optionCode, openSignalCall);
                        signal.Add(putATM.optionCode, openSignalPut);
                        //变更持仓状态
                        holdingStatus.callCode           = callATM.optionCode;
                        holdingStatus.putCode            = putATM.optionCode;
                        holdingStatus.callPosition       = -optionVolume;
                        holdingStatus.putPosition        = -optionVolume;
                        holdingStatus.etfPrice_open      = etfData[openIndex].open;
                        holdingStatus.straddlePrice_open = callPrice[openIndex].open + putPrice[openIndex].open;
                        holdingStatus.straddleOpenDate   = today;
                        holdingStatus.endDate            = callATM.endDate;
                        holdingStatus.strike             = callATM.strike;
                    }
                    MinuteTransactionWithBar.ComputePosition(signal, dataToday, ref positions, ref myAccount, slipPoint: slipPoint, now: now, nowIndex: openIndex);
                }
                //每日收盘前,整理持仓情况
                int    thisIndex = 239;
                double delta     = 0;
                var    thisTime  = TimeListUtility.IndexToMinuteDateTime(Kit.ToInt_yyyyMMdd(today), thisIndex);
                if (today >= timeOf50ETFDividend2016)
                {
                    benchmark.Add(etfData[thisIndex].close + bonusOf50ETFDividend2016);
                }
                else
                {
                    benchmark.Add(etfData[thisIndex].close);
                }
                if (holdingStatus.callPosition != 0)
                {
                    if (dataToday.ContainsKey(holdingStatus.callCode) == false)
                    {
                        var callLastDay = Platforms.container.Resolve <OptionMinuteRepository>().fetchFromLocalCsvOrWindAndSave(holdingStatus.callCode, today);
                        dataToday.Add(holdingStatus.callCode, callLastDay.Cast <KLine>().ToList());
                    }
                    if (dataToday.ContainsKey(holdingStatus.putCode) == false)
                    {
                        var putLastDay = Platforms.container.Resolve <OptionMinuteRepository>().fetchFromLocalCsvOrWindAndSave(holdingStatus.putCode, today);
                        dataToday.Add(holdingStatus.putCode, putLastDay.Cast <KLine>().ToList());
                    }
                    //计算期权delta值,并用50ETF对冲
                    var positionLast = positions.Last().Value;
                    delta = computeOptionDelta(positionLast, holdingStatus, today, dataToday, thisIndex);
                    double       etfChangeVolume = Math.Round(-delta - holdingStatus.etfPosition);
                    MinuteSignal openSignalETF   = new MinuteSignal()
                    {
                        code = "510050.SH", volume = etfChangeVolume, time = thisTime, tradingVarieties = "stock", price = dataToday["510050.SH"][thisIndex].open, minuteIndex = thisIndex
                    };
                    signal = new Dictionary <string, MinuteSignal>();
                    signal.Add("510050.SH", openSignalETF);
                    MinuteTransactionWithBar.ComputePosition(signal, dataToday, ref positions, ref myAccount, slipPoint: slipPoint, now: thisTime, nowIndex: thisIndex);
                    holdingStatus.etfPosition += etfChangeVolume;
                    // AccountUpdatingForMinute.computeAccountUpdating(ref myAccount, positions, thisTime, dataToday);
                }

                //更新当日属性信息
                AccountUpdatingWithMinuteBar.computeAccount(ref myAccount, positions, thisTime, thisIndex, dataToday);

                //记录历史仓位信息
                accountHistory.Add(new BasicAccount(myAccount.time, myAccount.totalAssets, myAccount.freeCash, myAccount.positionValue, myAccount.margin, myAccount.initialAssets));
                //在控制台上数据每日持仓信息
                if (holdingStatus.callPosition != 0)
                {
                    Console.WriteLine("time: {0},etf: {1}, strike: {2}, position: {3}, call: {4}, put: {5}, endDate: {6}, delta: {7}, etfVolume: {8}", thisTime, etfData[thisIndex].close, holdingStatus.strike, holdingStatus.callPosition, dataToday[holdingStatus.callCode][thisIndex].close, dataToday[holdingStatus.putCode][thisIndex].close, holdingStatus.endDate, delta, holdingStatus.etfPosition);
                }
                //Console.WriteLine("time: {0}, total: {1}, cash: {2}, option: {3}, margin: {4}", thisTime, myAccount.totalAssets, myAccount.freeCash, myAccount.positionValue, myAccount.margin);
            }
            //策略绩效统计及输出
            PerformanceStatisics myStgStats = new PerformanceStatisics();

            myStgStats = PerformanceStatisicsUtils.compute(accountHistory, positions, benchmark.ToArray());
            //画图
            Dictionary <string, double[]> line = new Dictionary <string, double[]>();

            double[] netWorth = accountHistory.Select(a => a.totalAssets / initialCapital).ToArray();
            line.Add("NetWorth", netWorth);
            //记录净值数据
            RecordUtil.recordToCsv(accountHistory, GetType().FullName, "account", parameters: "straddle", performance: myStgStats.anualSharpe.ToString("N").Replace(".", "_"));
            //记录持仓变化
            var positionStatus = OptionRecordUtil.Transfer(positions);

            RecordUtil.recordToCsv(positionStatus, GetType().FullName, "positions", parameters: "straddle", performance: myStgStats.anualSharpe.ToString("N").Replace(".", "_"));
            //记录统计指标
            var performanceList = new List <PerformanceStatisics>();

            performanceList.Add(myStgStats);
            RecordUtil.recordToCsv(performanceList, GetType().FullName, "performance", parameters: "straddle", performance: myStgStats.anualSharpe.ToString("N").Replace(".", "_"));
            //统计指标在console 上输出
            Console.WriteLine("--------Strategy Performance Statistics--------\n");
            Console.WriteLine(" netProfit:{0,5:F4} \n totalReturn:{1,-5:F4} \n anualReturn:{2,-5:F4} \n anualSharpe :{3,-5:F4} \n winningRate:{4,-5:F4} \n PnLRatio:{5,-5:F4} \n maxDrawDown:{6,-5:F4} \n maxProfitRatio:{7,-5:F4} \n informationRatio:{8,-5:F4} \n alpha:{9,-5:F4} \n beta:{10,-5:F4} \n averageHoldingRate:{11,-5:F4} \n", myStgStats.netProfit, myStgStats.totalReturn, myStgStats.anualReturn, myStgStats.anualSharpe, myStgStats.winningRate, myStgStats.PnLRatio, myStgStats.maxDrawDown, myStgStats.maxProfitRatio, myStgStats.informationRatio, myStgStats.alpha, myStgStats.beta, myStgStats.averageHoldingRate);
            Console.WriteLine("-----------------------------------------------\n");
            //benchmark净值
            List <double> netWorthOfBenchmark = benchmark.Select(x => x / benchmark[0]).ToList();

            line.Add("Base", netWorthOfBenchmark.ToArray());
            string[] datestr = accountHistory.Select(a => a.time.ToString("yyyyMMdd")).ToArray();
            Application.Run(new PLChart(line, datestr));
        }
예제 #5
0
        public DebuggerDialog(DebuggerStopEventArgs e)
        {
            _InvocationInfo = e.InvocationInfo;

            int maxLine = 0;

            string[] lines = null;
            if (!string.IsNullOrEmpty(e.InvocationInfo.ScriptName) && File.Exists(e.InvocationInfo.ScriptName))
            {
                try
                {
                    lines = File.ReadAllLines(e.InvocationInfo.ScriptName, Encoding.Default);
                    foreach (string s in lines)
                    {
                        if (s.Length > maxLine)
                        {
                            maxLine = s.Length;
                        }
                    }
                }
                catch (IOException) { }
            }

            int dw = Math.Max(Math.Min(Far.Api.UI.WindowSize.X - 7, maxLine + 12), 73);
            int dh = 22;

            string title;
            int    h1;

            if (e.Breakpoints.Count > 0)
            {
                title = "DEBUG: Hit breakpoint(s)";
                h1    = e.Breakpoints.Count + 2;
            }
            else
            {
                title = "DEBUG: Step";
                h1    = 2;
            }

            _Dialog           = Far.Api.CreateDialog(-1, -1, dw, dh);
            _Dialog.HelpTopic = Far.Api.GetHelpTopic("DebuggerDialog");
            _Dialog.AddBox(3, 1, dw - 4, dh - 2, title);

            _List1          = _Dialog.AddListBox(4, 2, dw - 5, h1 + 1, null);
            _List1.Disabled = true;
            _List1.NoBox    = true;
            _List1.NoClose  = true;
            _List1.NoFocus  = true;
            if (e.Breakpoints.Count > 0)
            {
                foreach (Breakpoint bp in e.Breakpoints)
                {
                    CommandBreakpoint bpc = bp as CommandBreakpoint;
                    if (bpc != null && Kit.Equals(bpc.Command, Commands.AssertFarCommand.MyName))
                    {
                        A.InvokeCode("Remove-PSBreakpoint -Breakpoint $args[0]", bpc);
                    }
                }
            }
            foreach (string s in e.InvocationInfo.PositionMessage.Trim().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
            {
                _List1.Add(s);
            }

            _Dialog.AddText(0, -_List1.Rect.Height, 0, null).Separator = 1;

            _List2         = _Dialog.AddListBox(4, _List1.Rect.Bottom + 2, dw - 5, dh - 5, null);
            _List2.NoBox   = true;
            _List2.NoClose = true;
            if (lines != null)
            {
                foreach (string s in lines)
                {
                    _List2.Add(s);
                }
                int i = e.InvocationInfo.ScriptLineNumber - 1;
                _List2.Items[i].Checked = true;
            }

            _Dialog.AddText(0, -_List2.Rect.Height, 0, null).Separator = 1;

            _Step             = _Dialog.AddButton(0, -1, BtnStep);
            _Step.CenterGroup = true;

            _Over             = _Dialog.AddButton(0, 0, BtnOver);
            _Over.CenterGroup = true;

            _Out             = _Dialog.AddButton(0, 0, BtnOut);
            _Out.CenterGroup = true;

            _Console             = _Dialog.AddButton(0, 0, BtnInteractive);
            _Console.CenterGroup = true;
            _Console.NoBrackets  = true;

            _Edit             = _Dialog.AddButton(0, 0, BtnEdit);
            _Edit.CenterGroup = true;
            _Edit.NoBrackets  = true;

            // to be completed on show
            _View             = _Dialog.AddButton(0, 0, BtnView);
            _View.CenterGroup = true;
            _View.NoBrackets  = true;
            _View.NoClose     = true;

            _Goto                = _Dialog.AddButton(0, 0, BtnLine);
            _Goto.CenterGroup    = true;
            _Goto.NoBrackets     = true;
            _Goto.NoClose        = true;
            _Goto.ButtonClicked += OnGoto;

            _Quit             = _Dialog.AddButton(0, 0, BtnQuit);
            _Quit.CenterGroup = true;
            _Quit.NoBrackets  = true;

            _Dialog.Initialized += OnInitialized;
        }
예제 #6
0
파일: Kits.cs 프로젝트: SteveKnowless/Rust
        object CanRedeemKit(BasePlayer player, string kitname)
        {
            if (!isKit(kitname))
            {
                return("This kit doesn't exist");
            }

            object thereturn = Interface.GetMod().CallHook("canRedeemKit", new object[1] {
                player
            });

            if (thereturn != null)
            {
                if (thereturn is string)
                {
                    return(thereturn);
                }
                return("You are not allowed to redeem a kit at the moment");
            }

            Kit kit = storedData.Kits[kitname];

            if (kit.authlevel != null)
            {
                if (player.net.connection.authLevel < int.Parse(kit.authlevel))
                {
                    return("You don't have the level to use this kit");
                }
            }

            if (kit.permission != null)
            {
                if (player.net.connection.authLevel < 2 && !permission.UserHasPermission(player.userID.ToString(), kit.permission))
                {
                    return("You don't have the permissions to use this kit");
                }
            }

            if (kit.max != null)
            {
                if (int.Parse(GetData(player, kitname, "max")) >= int.Parse(kit.max))
                {
                    return("You already redeemed all of those kits");
                }
            }

            if (kit.cooldown != null)
            {
                double cd = double.Parse(GetData(player, kitname, "cooldown"));
                double ct = CurrentTime();
                if (cd > ct && cd != 0.0)
                {
                    return(string.Format("You need to wait {0} seconds to use this kit", Math.Abs(Math.Ceiling(cd - ct)).ToString()));
                }
            }

            if (kit.npconly != null)
            {
                bool foundNPC  = false;
                var  neededNpc = new List <string>();
                foreach (KeyValuePair <string, object> pair in GUIKits)
                {
                    var listkits = pair.Value as List <object>;
                    if (listkits.Contains(kitname))
                    {
                        neededNpc.Add(pair.Key);
                    }
                }
                foreach (Collider col in Physics.OverlapSphere(player.transform.position, 3f, playerLayer))
                {
                    BasePlayer targetplayer = col.GetComponentInParent <BasePlayer>();
                    if (targetplayer == null)
                    {
                        continue;
                    }

                    if (neededNpc.Contains(targetplayer.userID.ToString()))
                    {
                        foundNPC = true;
                        break;
                    }
                }
                if (!foundNPC)
                {
                    return("You must found the NPC that gives this kit to redeem it.");
                }
            }
            return(true);
        }
예제 #7
0
파일: Stub.cs 프로젝트: Daoting/dt
 /// <summary>
 /// 自定义请求处理或定义请求管道的中间件
 /// </summary>
 /// <param name="p_app"></param>
 /// <param name="p_handlers">注册自定义请求处理</param>
 public void Configure(IApplicationBuilder p_app, IDictionary <string, RequestDelegate> p_handlers)
 {
     Kit.GetObj <SqliteModelHandler>().Init(p_handlers);
 }
예제 #8
0
        async void OnShowExtPanel(object sender, RoutedEventArgs e)
        {
#if UWP
            // 直接选择文件
            var files = await Kit.PickFiles();

            if (files != null && files.Count > 0)
            {
                Owner.SendFiles(files);
            }
#elif WASM
            if (_menu == null)
            {
                _menu = new Menu {
                    IsContextMenu = true
                };
                Mi mi = new Mi {
                    ID = "视频通话", Icon = Icons.视频
                };
                mi.Click += OnWebRtc;
                _menu.Items.Add(mi);

                mi = new Mi {
                    ID = "文件", Icon = Icons.文件
                };
                mi.Click += OnAddFile;
                _menu.Items.Add(mi);
                if (!Kit.IsPhoneUI)
                {
                    _menu.Placement = MenuPosition.OuterTop;
                }
            }
            await _menu.OpenContextMenu((Button)sender);
#else
#if IOS
            ResetTransform();
#endif
            if (_menu == null)
            {
                _menu = new Menu {
                    IsContextMenu = true
                };
                Mi mi = new Mi {
                    ID = "照片", Icon = Icons.图片
                };
                mi.Click += OnAddPhoto;
                _menu.Items.Add(mi);

                mi = new Mi {
                    ID = "拍照", Icon = Icons.拍照
                };
                mi.Click += OnTakePhoto;
                _menu.Items.Add(mi);

                mi = new Mi {
                    ID = "录视频", Icon = Icons.录像
                };
                mi.Click += OnTakeVideo;
                _menu.Items.Add(mi);

                mi = new Mi {
                    ID = "文件", Icon = Icons.文件
                };
                mi.Click += OnAddFile;
                _menu.Items.Add(mi);
            }
            await _menu.OpenContextMenu();
#endif
        }
예제 #9
0
 void OnTimerHandler(ThreadPoolTimer p_timer)
 {
     Kit.RunAsync(() => CloseInternal());
 }
예제 #10
0
파일: Startup.cs 프로젝트: Daoting/dt
 /// <summary>
 /// 取消自启动
 /// </summary>
 internal static void DelAutoStart()
 {
     AtState.DelAutoStart();
     Kit.Msg("已取消自启动设置!");
 }
예제 #11
0
파일: WfRollbackCmd.cs 프로젝트: Daoting/dt
        async Task Rollback()
        {
            // 活动执行者多于一人时,不允许进行回退
            if (_info.AtvInst.InstCount > 1)
            {
                Kit.Msg("该活动执行者多于一人,不允许回退!");
                return;
            }

            // 获得前一活动实例
            var pre = await _info.AtvInst.GetRollbackAtv();

            if (pre == null)
            {
                Kit.Msg("该活动不允许回退!");
                return;
            }

            if (!await Kit.Confirm("确认要回退吗?"))
            {
                return;
            }

            DateTime time       = Kit.Now;
            var      newAtvInst = new WfiAtv(
                ID: await AtCm.NewID(),
                PrciID: _info.PrcInst.ID,
                AtvdID: pre.AtvdID,
                Status: WfiAtvStatus.活动,
                InstCount: 1,
                Ctime: time,
                Mtime: time);

            // 创建迁移实例
            var newTrs = await _info.CreateAtvTrs(pre.AtvdID, newAtvInst.ID, time, true);

            // 当前活动完成状态
            _info.AtvInst.Finished();

            // 当前工作项置成完成状态
            _info.WorkItem.Finished();

            Dict dict = new Dict();

            dict["name"] = await GetSender();

            long userId = await AtCm.GetScalar <long>("流程-获取用户ID", dict);

            var newItem = await WfiItem.Create(newAtvInst.ID, time, false, userId, null, true);

            List <object> ls = new List <object>();

            if (_info.AtvInst.IsChanged)
            {
                ls.Add(_info.AtvInst);
            }
            ls.Add(_info.WorkItem);
            ls.Add(newAtvInst);
            ls.Add(newItem);
            ls.Add(newTrs);

            if (await AtCm.BatchSave(ls, false))
            {
                Kit.Msg("回退成功!");
                _info.CloseWin();
            }
            else
            {
                Kit.Msg("回退失败!");
            }
        }
예제 #12
0
파일: Startup.cs 프로젝트: Daoting/dt
        /// <summary>
        /// 更新打开模型文件
        /// 1. 与本地不同时下载新模型文件;
        /// 2. 打开模型库;
        /// </summary>
        /// <returns></returns>
        public static async Task <bool> OpenModelDb()
        {
            // 获取全局参数
            Dict cfg;

            try
            {
                cfg = await new UnaryRpc(_svcName, "ModelMgr.GetConfig").Call <Dict>();
                Kit.SyncTime(cfg.Date("now"));
            }
            catch
            {
                ShowTip("服务器连接失败!");
                return(false);
            }

            // 更新模型文件
            string modelVer = Path.Combine(Kit.DataPath, $"model-{cfg.Str("ver")}.ver");

            if (!File.Exists(modelVer))
            {
                string modelFile = Path.Combine(Kit.DataPath, "model.db");

                // 删除旧版的模型文件和版本号文件
                try { File.Delete(modelFile); } catch { }
                foreach (var file in new DirectoryInfo(Kit.DataPath).GetFiles($"model-*.ver"))
                {
                    try { file.Delete(); } catch { }
                }

                try
                {
                    // 下载模型文件,下载地址如 https://localhost/app/cm/.model
                    using (var response = await BaseRpc.Client.GetAsync($"{Kit.Stub.ServerUrl}/{_svcName}/.model"))
                        using (var stream = await response.Content.ReadAsStreamAsync())
                            using (var gzipStream = new GZipStream(stream, CompressionMode.Decompress))
                                using (var fs = File.Create(modelFile, 262140, FileOptions.WriteThrough))
                                {
                                    gzipStream.CopyTo(fs);
                                    fs.Flush();
                                }

                    // 版本号文件
                    File.Create(modelVer);
                }
                catch (Exception ex)
                {
                    try
                    {
                        File.Delete(modelFile);
                    }
                    catch { }
                    ShowTip("下载模型文件失败!" + ex.Message);
                    return(false);
                }
            }

            // 打开模型库
            try
            {
                AtModel.OpenDb();
            }
            catch (Exception ex)
            {
                ShowTip("打开模型库失败!" + ex.Message);
                return(false);
            }
            return(true);
        }
예제 #13
0
 static void OnIsSelectedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
 {
     // uno中Arrange中修改IsSelected时有多次布局警告
     Kit.RunAsync(() => VisualStateManager.GoToState((GroupHeaderCell)d, ((bool)e.NewValue) ? "Selected" : "Normal", true));
 }
예제 #14
0
 public Kit Create(Kit newKit)
 {
     return(_repo.Create(newKit));
 }
예제 #15
0
 void OnRpcException(object sender, RoutedEventArgs e)
 {
     Kit.Trace(TraceOutType.RpcException, "远程调用异常信息", "异常信息详细内容");
 }
예제 #16
0
        public async Task <int> InvokeAsync(InvocationContext context)
        {
            var console = context.Console.Out;
            var kit     = context.ParseResult.ValueForOption <int>("kit");
            var file    = context.ParseResult.ValueForOption <string>("file");

            var(client, schema) = await DeviceDetection.DetectDeviceAsync(console);

            if (client == null)
            {
                return(1);
            }

            var moduleData = new ModuleData();

            using (client)
            {
                if (!schema.KitRoots.TryGetValue(kit, out var kitRoot))
                {
                    console.WriteLine($"Kit {kit} out of range");
                    return(1);
                }
                ;

                // Allow up to 30 seconds in total, and 1 second per container.
                var overallToken = new CancellationTokenSource(TimeSpan.FromSeconds(30)).Token;
                try
                {
                    Stopwatch sw         = Stopwatch.StartNew();
                    var       containers = kitRoot.Context.AnnotateDescendantsAndSelf().Where(c => c.Container.Loadable).ToList();
                    console.WriteLine($"Loading {containers.Count} containers from device {schema.Identifier.Name}");
                    foreach (var container in containers)
                    {
                        await PopulateSegment(moduleData, container, overallToken);
                    }
                    console.WriteLine($"Finished loading in {(int) sw.Elapsed.TotalSeconds} seconds");
                    var clonedData = kitRoot.Context.CloneData(moduleData, schema.KitRoots[1].Context.Address);
                    var kitToSave  = new Kit(schema, clonedData, kit);
                    using (var stream = File.Create(file))
                    {
                        kitToSave.Save(stream);
                    }
                    console.WriteLine($"Saved kit to {file}");
                }
                catch (OperationCanceledException)
                {
                    console.WriteLine("Data loading from device was cancelled");
                    return(1);
                }
                catch (Exception ex)
                {
                    console.WriteLine($"Error loading data from device: {ex}");
                    return(1);
                }
            }
            return(0);

            async Task PopulateSegment(ModuleData data, AnnotatedContainer annotatedContainer, CancellationToken token)
            {
                var timerToken     = new CancellationTokenSource(TimeSpan.FromSeconds(1)).Token;
                var effectiveToken = CancellationTokenSource.CreateLinkedTokenSource(token, timerToken).Token;

                try
                {
                    var segment = await client.RequestDataAsync(annotatedContainer.Context.Address.Value, annotatedContainer.Container.Size, effectiveToken);

                    data.Populate(annotatedContainer.Context.Address, segment);
                }
                catch (OperationCanceledException) when(timerToken.IsCancellationRequested)
                {
                    console.WriteLine($"Device didn't respond for container {annotatedContainer.Path}; skipping.");
                }
            }
        }
예제 #17
0
 void OnUnhandled(object sender, RoutedEventArgs e)
 {
     Kit.Trace(TraceOutType.UnhandledException, "未处理异常信息", "异常信息详细内容!");
 }
예제 #18
0
 void OnNormal(object sender, RoutedEventArgs e)
 {
     Kit.Trace("普通信息标题", "信息内容!");
 }
예제 #19
0
        /// <summary>
        /// 加载默认菜单,自动绑定命令
        /// </summary>
        async void LoadMenu(WfFormInfo p_info)
        {
            var fv = ((FrameworkElement)_form).FindChildByType <Fv>();

            if (fv == null)
            {
                Kit.Warn($"未找到流程表单【{p_info.PrcDef.Name}】!");
                return;
            }

            Menu m = new Menu();

            if (p_info.Usage == WfFormUsage.Edit)
            {
                m.Items.Add(new Mi {
                    ID = "发送", Icon = Icons.发出, Cmd = p_info.CmdSend
                });

                if (await p_info.AllowRollback())
                {
                    m.Items.Add(new Mi {
                        ID = "回退", Icon = Icons.追回, Cmd = p_info.CmdRollback
                    });
                }

                if (!p_info.IsStartItem)
                {
                    Mi mi = new Mi {
                        ID = "签收", Icon = Icons.锁卡, IsCheckable = true, Cmd = p_info.CmdAccept
                    };
                    if (p_info.WorkItem.IsAccept)
                    {
                        mi.IsChecked = true;
                    }
                    m.Items.Add(mi);
                }

                // 合并IsDirty属性
                p_info.CmdSave.AllowExecute = fv.IsDirty;
                fv.Dirty += (s, b) => p_info.CmdSave.AllowExecute = b;
                m.Items.Add(new Mi {
                    ID = "保存", Icon = Icons.保存, Cmd = p_info.CmdSave
                });
                m.Items.Add(new Mi {
                    ID = "撤消", Icon = Icons.撤消, Cmd = fv.CmdUndo
                });

                if (p_info.AtvDef.CanDelete || p_info.AtvDef.Type == WfdAtvType.Start)
                {
                    m.Items.Add(new Mi {
                        ID = "删除", Icon = Icons.垃圾箱, Cmd = p_info.CmdDelete
                    });
                }
            }
            else if (p_info.Usage == WfFormUsage.Manage)
            {
                m.Items.Add(new Mi {
                    ID = "删除", Icon = Icons.垃圾箱, Cmd = p_info.CmdDelete
                });
                fv.IsReadOnly = true;
            }
            else
            {
                fv.IsReadOnly = true;
            }
            m.Items.Add(new Mi {
                ID = "日志", Icon = Icons.审核, Cmd = p_info.CmdLog
            });

            p_info.Menu = m;
            _tab.Menu   = m;

            _form.Init(p_info);
        }
예제 #20
0
 void OnRequest(object sender, RoutedEventArgs e)
 {
     Kit.Trace(TraceOutType.RpcCall, "Http请求信息", "Rpc请求内容!", "服务名称");
 }
예제 #21
0
 private List <StockDaily> getETFHistoricalDailyData()
 {
     return(Platforms.container.Resolve <StockDailyRepository>().fetchFromLocalCsvOrWindAndSave("510050.SH", Kit.ToDate(20130101), endDate));
 }
예제 #22
0
 void OnResponse(object sender, RoutedEventArgs e)
 {
     Kit.Trace(TraceOutType.RpcRecv, "Http响应信息", "服务器端返回的内容!", "服务名称");
 }
예제 #23
0
        public Tagge.Common.Models.ProductVariantResponse ConvertToResponse(string companyId, IMongoDatabase db)
        {
            var response = new Tagge.Common.Models.ProductVariantResponse();

            response.Id           = Id;
            response.Sku          = Sku;
            response.DefaultPrice = DefaultPrice;
            response.MSRP         = MSRP;
            response.SalePrice    = SalePrice;
            response.Barcode      = Barcode;
            response.Width        = Width;
            response.Height       = Height;
            response.Depth        = Depth;
            response.Weight       = Weight;
            response.Status       = Status;

            // Collections
            // Kit
            if (Kit != null && Kit.IsActive)
            {
                response.Kit = Kit.ConvertToResponse(companyId, "PC_VariantKit", db);
            }


            // Inventory - Managed in PC_Inventory

            // Categories
            if (Categories != null)
            {
                response.Categories = new List <Tagge.Common.Models.CategoryAssignmentResponse>();
                foreach (var category in Categories)
                {
                    if (category.IsActive)
                    {
                        response.Categories.Add(category.ConvertToGenericResponse());
                    }
                }
            }

            // Options
            if (Options != null)
            {
                response.Options = new List <Tagge.Common.Models.OptionValueResponse>();
                foreach (var option in Options)
                {
                    if (option.IsActive)
                    {
                        response.Options.Add(option.ConvertToResponse(companyId, "PC_ProductVariantOption", db));
                    }
                }
            }

            // AlternateIds
            if (AlternateIds != null)
            {
                response.AlternateIds = new List <Tagge.Common.Models.ProductAlternateIdResponse>();
                foreach (var alternateId in AlternateIds)
                {
                    if (alternateId.IsActive)
                    {
                        response.AlternateIds.Add(alternateId.ConvertToResponse(companyId, "PC_ProductVariantAlternateId", db));
                    }
                }
            }

            // Custom Fields
            if (CustomFields != null)
            {
                response.CustomFields = new List <Tagge.Common.Models.GenericCustomFieldResponse>();
                foreach (var customField in CustomFields)
                {
                    response.CustomFields.Add(customField.ConvertToResponse());
                }
            }

            // ExternalIds - Managed in PC_ExternalId

            return(response);
        }
예제 #24
0
 void OnWsRequest(object sender, RoutedEventArgs e)
 {
     Kit.Trace(TraceOutType.WsCall, "Ws请求信息", "WebSocket请求内容!");
 }
예제 #25
0
 public object Convert(object value, Type targetType, object parameter, string language)
 {
     return(Kit.GetFileSizeDesc((ulong)value));
 }
예제 #26
0
 void OnWsResponse(object sender, RoutedEventArgs e)
 {
     Kit.Trace(TraceOutType.WsRecv, "Ws响应信息", "WebSocket返回内容!");
 }
예제 #27
0
        private void DoInitDownload(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = (BackgroundWorker)sender;

            String languageCode = (String)e.Argument;

            int currentProgress = 0;

            worker.ReportProgress(currentProgress, Resources.I_DOWNLOADING_TYPES);

            if (worker.CancellationPending)
            {
                e.Cancel = true;
                return;
            }

            // get types
            TypeItem[] types = Web.getTypeList(languageCode, mGetNew, null);
            SettingFiles.SaveTypeListToFile(types);

            // get brands
            int progressPartForBrand    = 40 / types.Length;
            int progressPartForKey      = 40 / types.Length;
            int progressPartForIrReader = 20;

            BrandItem[] brands;
            Dictionary <String, KeyName> keyMap = new Dictionary <String, KeyName>();

            for (int i = 0; i < types.Length; i++)
            {
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }

                currentProgress += progressPartForBrand;
                worker.ReportProgress(currentProgress,
                                      String.Format(Resources.I_DOWNLOADING_BRANDS + " {0}/{1}", i + 1, types.Length));

                brands = Web.getBrandList(types[i].Id, 0, 2000, languageCode, null, mGetNew, null);
                if (null != brands)
                {
                    SettingFiles.SaveBrandListToFile(types[i].Id, brands);
                }
                else
                {
                    e.Result = false;
                    return;
                }

                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }

                currentProgress += progressPartForKey;
                worker.ReportProgress(currentProgress,
                                      String.Format(Resources.I_DOWNLOADING_KEYS + "  {0}/{1}", i + 1, types.Length));

                KeyName[] keys = Web.getKeyName(types[i].Id, languageCode, mGetNew, null);
                if (null != keys)
                {
                    foreach (KeyName key in keys)
                    {
                        if (!keyMap.ContainsKey(key.Id))
                        {
                            keyMap.Add(key.Id, key);
                        }
                    }
                }
                else
                {
                    e.Result = false;
                    return;
                }
            }

            if (worker.CancellationPending)
            {
                e.Cancel = true;
                return;
            }

            currentProgress += progressPartForIrReader / 2;
            worker.ReportProgress(currentProgress, Resources.I_DOWNLOADING_FORMATS);
            // IRReader
            IRReader irReader = Kit.createIRReader(mGetNew);

            if (null == irReader)
            {
                e.Result = false;
                return;
            }
            worker.ReportProgress(100, Resources.COMPLETED);

            List <KeyName> keyList = new List <KeyName>();

            foreach (KeyValuePair <String, KeyName> entry in keyMap)
            {
                keyList.Add(entry.Value);
            }

            if (keyList.Count > 0)
            {
                SettingFiles.SaveKeyListToFile(keyList.ToArray());
            }
            else
            {
                e.Result = false;
                return;
            }

            e.Result = true;
        }
예제 #28
0
 void OnServerPush(object sender, RoutedEventArgs e)
 {
     Kit.Trace(TraceOutType.ServerPush, "服务器推送", "详细内容");
 }
예제 #29
0
 void OnChanged(object sender, object e)
 {
     Kit.Msg("文件列表变化");
 }
예제 #30
0
 public bool Draw(GUIStyle style = null) => Valid && Kit.Draw(style);