예제 #1
0
        /// <summary>
        /// Called when [active step changed].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void OnActiveStepChanged(object sender, EventArgs e)
        {
            if (CheckoutWizard.ActiveStepIndex == CheckoutWizard.WizardSteps.IndexOf(this.ShippingOptionsStep))
            {
                CheckoutWizard.StepNextButtonText = RM.GetString("CHECKOUT_SHIPPINGOPTIONS_NEXT");
            }
            else if (CheckoutWizard.ActiveStepIndex == CheckoutWizard.WizardSteps.IndexOf(this.PaymentStep))
            {
                CheckoutWizard.StepNextButtonText = RM.GetString("CHECKOUT_PAYMENT_PLACE_ORDER");
            }
            else if (CheckoutWizard.ActiveStepIndex == CheckoutWizard.WizardSteps.IndexOf(this.FinalStep))
            {
                CheckoutWizard.StepNextButtonText = RM.GetString("CHECKOUT_ORDER_CONFIRMATION_BUTTON");
            }

            // Set default button
            if (CheckoutWizard.ActiveStepIndex == CheckoutWizard.WizardSteps.IndexOf(this.FinalStep))
            {
                Page.Form.DefaultButton = CheckoutWizard.FindControl("FinishNavigationTemplateContainerID$FinishButton").UniqueID;
            }
            else
            {
                Page.Form.DefaultButton = CheckoutWizard.FindControl("StepNavigationTemplateContainerID$StepNextButton").UniqueID;
            }

            CheckWizardState();
        }
예제 #2
0
        protected void EMailButton_Click(object sender, EventArgs e)
        {
            bool error = false;

            MembershipUser user = ProfileContext.Current.User;

            if (user != null)
            {
                user.Email = tbEMail.Text;

                try
                {
                    Membership.UpdateUser(user);
                }
                catch (Exception ex)
                {
                    ErrorManager.GenerateError(ex.Message);
                    error = true;
                }
            }
            else
            {
                ErrorManager.GenerateError("Current user not found!");
                error = true;
            }

            if (!error)
            {
                ErrorLabel.Text = RM.GetString("ACCOUNT_EMAIL_SUCCESSFULLY_CHANGED");
            }
        }
예제 #3
0
        /// <summary>
        /// Applies the localization.
        /// </summary>
        private void ApplyLocalization()
        {
            /*
             *          ToolBarItem1.Caption = RM.GetString("ATTRIBUTEEDIT_TOOLBAR_VIEW_CLASSES");
             *          ToolBarItem2.Caption = RM.GetString("ATTRIBUTEEDIT_TOOLBAR_NEW_ATTRIBUTE");
             *          ToolBarItem3.Caption = RM.GetString("ATTRIBUTEEDIT_TOOLBAR_VIEW_ATTRIBUTES");
             * */

            MetaLabelCtrl.Text    = RM.GetString("ATTRIBUTEEDIT_NEW_VALUE");
            AllValuesLabel.Text   = RM.GetString("ATTRIBUTEEDIT_ALL_VALUES");
            LinkButtonRemove.Text = RM.GetString("ATTRIBUTEEDIT_REMOVE");
            AddValue.Text         = RM.GetString("ATTRIBUTEEDIT_ADD_VALUE");
            RequiredFieldValidator1.ErrorMessage = RM.GetString("ATTRIBUTEEDIT_ERROR_EMPTY_NAME");
            //DeleteButton.Text = RM.GetString("ATTRIBUTEEDIT_DELETE_ATTRIBUTE");
            //SaveButton.Text = RM.GetString("GENERAL_SAVEBUTTON");

            chkAllowNulls.Text     = RM.GetString("ATTRIBUTEEDIT_FIELDALLOWNULLS");
            chkSaveHistory.Text    = RM.GetString("ATTRIBUTEEDIT_FIELDSAVEHISTORY");
            chkAllowSearch.Text    = RM.GetString("ATTRIBUTEEDIT_FIELDALLOWSEARCH");
            chkIsEncrypted.Text    = RM.GetString("ATTRIBUTEEDIT_FIELDISENCRYPTED");
            chkEditable.Text       = RM.GetString("ATTRIBUTEEDIT_EDITABLE");
            chkMultiline.Text      = RM.GetString("ATTRIBUTEEDIT_MULTILINE");
            chkClientOption.Text   = RM.GetString("ATTRIBUTEEDIT_CLIENTOPTION");
            chkUseInComparing.Text = RM.GetString("ATTRIBUTEEDIT_USE_IN_COMPARING");
            chkMultiLanguage.Text  = "Supports Multiple Languages";

            //CustomValidatiorPrecision.ErrorMessage = RM.GetString("ATTRIBUTEEDIT_ERROR_PRECISION_SCALE") + "38";

            chkAutoResizeImage.Text       = RM.GetString("ATTRIBUTEEDIT_AUTO_RESIZE_IMAGE");
            chkStretchImage.Text          = RM.GetString("ATTRIBUTEEDIT_STRETCH_IMAGE");
            chkAutoGenerateThumbnail.Text = RM.GetString("ATTRIBUTEEDIT_AUTO_CREATE_THUMBNAIL_IMAGE");
            chkStretchThumbnail.Text      = RM.GetString("ATTRIBUTEEDIT_STRETCH_THUMBNAIL");

            LinkButtonRemove.Text = RM.GetString("ATTRIBUTEEDIT_REMOVE_VALUE");
        }
예제 #4
0
    /// <summary>
    /// Renders the start in line.
    /// </summary>
    /// <param name="writer">The writer.</param>
    public void RenderStartInLine(HtmlTextWriter writer)
    {
        if (Product != null)
        {
            MetaClass mc = Product.GetEntryMetaClass();
            if (mc == null)
            {
                ErrorManager.GenerateError("Could not load Product's MetaClass");
                return;
            }

            bool added2Compare       = CommonHelper.GetCompareProductsIds(mc.Name).Contains(Product.CatalogEntryId);
            HtmlInputCheckBox chkbox = new HtmlInputCheckBox();
            chkbox.Attributes.Add("onclick", String.Format("javascript:CallServer{0}(this.checked);", Product.CatalogEntryId));
            chkbox.ID = GetCompareButtonId();
            if (added2Compare)
            {
                chkbox.Checked = true;
            }
            phCompareCheckbox.Controls.Add(chkbox);

            HtmlGenericControl span = new HtmlGenericControl("span");
            span.InnerHtml = "&nbsp;";
            phCompareCheckbox.Controls.Add(span);

            HtmlAnchor lnkCompare = new HtmlAnchor();
            lnkCompare.HRef      = String.Format("javascript:CSCompareProducts.OpenCompareView('{0}');", mc.Name);
            lnkCompare.InnerHtml = RM.GetString("COMPAREBUTTONMODULE_COMPARE_PRODUCTS");
            phCompareCheckbox.Controls.Add(lnkCompare);
        }
        else
        {
            this.Visible = false;
        }
    }
예제 #5
0
        /// <summary>
        /// Binds the data.
        /// </summary>
        private void BindData()
        {
            SearchFilter.Items.Clear();
            SearchFilter.Items.Add(new ListItem(RM.GetString("GENERAL_ALL_PRODUCTS"), ""));

            string cacheKey = CatalogCache.CreateCacheKey("mc-catalogentry-list");

            // check cache first
            object cachedObject = CatalogCache.Get(cacheKey);


            MetaClassCollection metaClasses = null;

            MetaClass catalogEntry = MetaHelper.LoadMetaClassCached(CatalogContext.MetaDataContext, "CatalogEntry");

            if (catalogEntry != null)
            {
                metaClasses = catalogEntry.ChildClasses;
            }

            if (metaClasses != null)
            {
                foreach (MetaClass metaClass in metaClasses)
                {
                    SearchFilter.Items.Add(new ListItem(metaClass.FriendlyName, metaClass.Name));
                }
            }

            SearchFilter.DataBind();
            Search.Text = Request.QueryString["search"];
            CommonHelper.SelectListItem(SearchFilter, Request.QueryString["filter"]);
        }
예제 #6
0
        private void tsmiAssignDesktopFiles_Click(object sender, EventArgs e)
        { //"C:\PATH\WinYourDesktop.exe" "%1"
            if (MessageBox.Show(RM.GetString("DialogAssignFile"),
                                RM.GetString("DialogAssignFileTitle"),
                                MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    string file = System.IO.Path.GetFileNameWithoutExtension(
                        System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName
                        );

                    //TODO: Properly make default
                    // https://msdn.microsoft.com/en-us/library/windows/desktop/cc144154(v=vs.85).aspx
                    Registry.SetValue(
                        @"HKEY_CLASSES_ROOT\desktop_auto_file\shell\open\command",
                        "",                    // Default value name
                        $@"""{file}"" ""%1""", // "C:\e.exe" "%1"
                        RegistryValueKind.String);

                    MessageBox.Show(RM.GetString("DialogAssignFileSuccess"),
                                    "OK!",
                                    MessageBoxButtons.OK);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message,
                                    ex.ToString(),
                                    MessageBoxButtons.OK);
                }
            }
        }
예제 #7
0
        /// <summary>
        /// Applies the localization.
        /// </summary>
        private void ApplyLocalization()
        {
            AddStringDictionaryItemButton.Text = RM.GetString("STRINGDICTIONARYCONTROL_ADD_ITEM");

            ItemsGrid.Columns[0].HeaderText = RM.GetString("STRINGDICTIONARYCONTROL_HDR_KEY");
            ItemsGrid.Columns[1].HeaderText = RM.GetString("STRINGDICTIONARYCONTROL_HDR_VALUE");
            ItemsGrid.Columns[2].HeaderText = RM.GetString("GENERAL_OPTIONS");
        }
예제 #8
0
파일: Confirm.cs 프로젝트: enrique-thedy/bz
        public Confirm(string message, bool?defaultValue, string warning)
        {
            _message      = message;
            _defaultValue = defaultValue;
            _warning      = warning;

            _yesOptions = RM.GetString("yesValidOptionsLower");
            _noOptions  = RM.GetString("noValidOptionsLower");
        }
예제 #9
0
        private void CropsPanel_VisibleChanged(object sender, EventArgs e)
        {
            if (Config != null && Visible)
            {
                _cropsView.Enabled = Config.IsImageEditorEnabled();

                _cropsView.Columns["WidthColumn"].HeaderText  = string.Format(RM.GetString("WidthColumnHeader"), RM.GetString(Config.PaperSizeUnits.Value));
                _cropsView.Columns["HeightColumn"].HeaderText = string.Format(RM.GetString("HeightColumnHeader"), RM.GetString(Config.PaperSizeUnits.Value));
            }
        }
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, System.EventArgs e)
        {
            lblCountries.Text = RM.GetString("SHIPPINGMETHODEDIT_RESTRICTED_COUNTRIES");
            lblRegions.Text   = RM.GetString("SHIPPINGMETHODEDIT_RESTRICTED_REGIONS");

            if (!this.IsPostBack)
            {
                BindForm();
            }
        }
예제 #11
0
        public override string ToString()
        {
            string format = RM.GetString(Name, CultureInfo.CurrentUICulture);

            Object[] array = Params;
            if (array != null)
            {
                return(string.Format(CultureInfo.CurrentCulture, format, array));
            }
            return(format);
        }
예제 #12
0
        protected override ITradeStatisticsWithKind InternalExecute(ISecurity security)
        {
            var           timeFrame = TimeFrameFactory.Create(TimeFrame, TimeFrameUnit);
            int           topTimeFrameNumber;
            TimeFrameUnit topTimeFrameUnit;
            TimeSpan      topTimeFrame;

            if (UseTopTimeFrame)
            {
                topTimeFrameNumber = TopTimeFrame;
                topTimeFrameUnit   = TopTimeFrameUnit;
                topTimeFrame       = TimeFrameFactory.Create(topTimeFrameNumber, topTimeFrameUnit);

                if (topTimeFrame.Ticks % timeFrame.Ticks != 0)
                {
                    throw new InvalidOperationException(string.Format(RM.GetString("TopTimeFrameMustBeDivisableByTimeFrame"), ToString(TopTimeFrame, topTimeFrameUnit), ToString(TimeFrame, TimeFrameUnit)));
                }
            }
            else
            {
                var maxTimeSpan = TimeSpan.FromSeconds(int.MaxValue);
                switch (TimeFrameUnit)
                {
                case TimeFrameUnit.Second:
                    topTimeFrameNumber = (int)maxTimeSpan.TotalSeconds;
                    break;

                case TimeFrameUnit.Minute:
                    topTimeFrameNumber = (int)maxTimeSpan.TotalMinutes;
                    break;

                case TimeFrameUnit.Hour:
                    topTimeFrameNumber = (int)maxTimeSpan.TotalHours;
                    break;

                case TimeFrameUnit.Day:
                    topTimeFrameNumber = (int)maxTimeSpan.TotalDays;
                    break;

                default:
                    throw new InvalidEnumArgumentException(nameof(TimeFrameUnit), (int)TimeFrameUnit, TimeFrameUnit.GetType());
                }
                topTimeFrameNumber = topTimeFrameNumber / TimeFrame * TimeFrame;
                topTimeFrameUnit   = TimeFrameUnit;
                topTimeFrame       = TimeFrameFactory.Create(topTimeFrameNumber, topTimeFrameUnit);
            }
            var runTime = Context.Runtime;
            var id      = runTime != null?string.Join(".", runTime.TradeName, runTime.IsAgentMode, VariableId) : VariableId;

            var stateId         = string.Join(".", security.Symbol, security.Interval, security.IsAligned, CombinePricesCount, TimeFrameKind, TimeFrame, TimeFrameUnit, topTimeFrameNumber, topTimeFrameUnit);
            var tradeStatistics = Context.GetTradeStatistics(stateId, () => new TradeStatistics(id, stateId, GetTradeHistogramsCache(security), TimeFrameKind, timeFrame, TimeFrameUnit, topTimeFrame));

            return(new TradeStatisticsWithKind(tradeStatistics, Kind, WidthPercent));
        }
예제 #13
0
        /// <summary>
        /// Applies the localization.
        /// </summary>
        private void ApplyLocalization()
        {
            //SaveButton.Text = RM.GetString("GENERAL_SAVEBUTTON");
            NameRequired.ErrorMessage = RM.GetString("ATTRIBUTECLASSEDIT_ERROR_EMPTY_NAME");
            RequiredFieldValidatorFriendlyName.ErrorMessage = RM.GetString("ATTRIBUTECLASSEDIT_ERROR_EMPTY_FRIENDLYNAME");

            /*
             *          ItemsGrid.Columns[0].HeaderText = RM.GetString("ATTRIBUTECLASSEDIT_SELECT");
             *          ItemsGrid.Columns[1].HeaderText = RM.GetString("ATTRIBUTECLASSEDIT_SORT");
             *          ItemsGrid.Columns[2].HeaderText = RM.GetString("ATTRIBUTECLASSEDIT_NAME");
             * */
        }
예제 #14
0
 /// <summary>
 /// Binds the types.
 /// </summary>
 private void BindTypes()
 {
     ddlType.Items.Clear();
     MetaType[] coll = GetMetaTypeList();
     foreach (MetaType type in coll)
     {
         if (!IsDictionaryType(type.MetaDataType))
         {
             ddlType.Items.Add(new ListItem(type.FriendlyName, type.Id.ToString()));
         }
     }
     ddlType.Items.Add(new ListItem(RM.GetString("ATTRIBUTEEDIT_DICTIONARY"), "0"));
 }
예제 #15
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            SaveChangesButton.Click += new EventHandler(OnSaveChanges);
            CancelButton.Click      += new EventHandler(OnCancel);
            DeleteButton.Click      += new EventHandler(OnDelete);
            DeleteButton.Visible     = ShowDeleteButton;

            if (!this.IsPostBack)
            {
                string confirm = "return confirm('" + RM.GetString("DeleteSelectedItemsConfirmation") + "')";
                DeleteButton.Attributes.Add("onclick", confirm);
            }
        }
예제 #16
0
        /// <summary>
        /// Binds the class names.
        /// </summary>
        private void BindClassNames()
        {
            this.ddlClassName.Items.Clear();
            ddlClassName.Items.Add(new ListItem(RM.GetString("GENERAL_NONE"), ""));

            foreach (string cls in ReflectionHelper.GetClassesBasedOnTypeInSiteDir(typeof(IPaymentGateway)))
            {
                string className = cls.Split(new char[] { ',' })[0];
                ddlClassName.Items.Add(new ListItem(className, className + "," + cls.Split(new char[] { ',' })[1]));
            }

            ddlClassName.DataBind();
        }
예제 #17
0
        private void ValidateCells(CancelEventArgs e)
        {
            for (int i = _cropsView.Rows.Count - 1; i >= 0; i--)
            {
                DataGridViewRow curRow = _cropsView.Rows[i];
                if (!curRow.IsNewRow)
                {
                    curRow.ErrorText = string.Empty;
                    curRow.Cells["WidthColumn"].ErrorText  = string.Empty;
                    curRow.Cells["HeightColumn"].ErrorText = string.Empty;

                    string curName = curRow.Cells["NameColumn"].Value != null ? curRow.Cells["NameColumn"].Value.ToString() : string.Empty;
                    if (!string.IsNullOrEmpty(curName))
                    {
                        foreach (DataGridViewRow row in _cropsView.Rows)
                        {
                            if (row != curRow && string.IsNullOrEmpty(row.ErrorText) && curName.Equals(row.Cells["NameColumn"].Value))
                            {
                                curRow.ErrorText = RM.GetString("CropFormatDuplicateError");
                            }
                        }
                    }
                    else
                    {
                        curRow.ErrorText = RM.GetString("CropFormatEmptyError");
                    }

                    float width = 0.0f;
                    if (curRow.Cells["WidthColumn"].Value == null || !float.TryParse(curRow.Cells["WidthColumn"].Value.ToString(), out width) || width < 0)
                    {
                        curRow.Cells["WidthColumn"].ErrorText = RM.GetString("CropWidthError");
                    }

                    float height = 0.0f;
                    if (curRow.Cells["HeightColumn"].Value == null || !float.TryParse(curRow.Cells["HeightColumn"].Value.ToString(), out height) || height < 0)
                    {
                        curRow.Cells["HeightColumn"].ErrorText = RM.GetString("CropHeightError");
                    }

                    if ((width == 0 && height > 0) || (width > 0 && height == 0))
                    {
                        curRow.ErrorText = RM.GetString("FreeCropError");
                    }
                }
            }

            if (BasePanel.HasErrors(_cropsView, false) && e != null)
            {
                e.Cancel = true;
            }
        }
예제 #18
0
        /// <summary>
        /// Binds the shopping cart.
        /// </summary>
        private void BindShoppingCart()
        {
            CartHelper cart = new CartHelper(Cart.DefaultName);

            decimal numberOfItems = cart.GetTotalItemCount();

            if (numberOfItems == 0)
            {
                ShoppingCartLink.Text = RM.GetString("BASKET_YOUR_LABEL");
            }
            else
            {
                ShoppingCartLink.Text = String.Format("{0} item(s) in your Wish List", (int)numberOfItems);
            }
        }
예제 #19
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            /*Type csType = this.GetType();
             * string csName = "SaveControl_DisableButtons";
             *
             * string csText = "alert('Here'); " +
             *              "if (document.all || document.getElementById) {" +
             *                      "alert('Here2'); " +
             *                      "for (i = 0; i < document.forms[0].length; i++) {" +
             *                              "var tempobj = document.forms[0].elements[i];" +
             *                              "if (tempobj.type.toLowerCase() == \"submit\")" +
             *                              "tempobj.disabled = true;}" +
             *                      "return true;" +
             *              "}";
             *
             * if (!this.Page.ClientScript.IsOnSubmitStatementRegistered(csType, csName))
             *      ScriptManager.RegisterOnSubmitStatement(this, csType, csName, csText);*/

            /*string validationtext = "if (typeof(Page_ClientValidate) == 'function') { " +
             *      "if (Page_ClientValidate('" + SaveChangesButton.ValidationGroup + "') == false) { return false; }} ";*/

            /*string scriptString = "javascript:" +
             *        SaveChangesButton.ClientID + ".disabled=true;" +
             *        CancelButton.ClientID + ".disabled=true;" +
             *        "if(document.getElementById('" + DeleteButton.ClientID + "')!=null) " + DeleteButton.ClientID + ".disabled=true;";
             *
             * SaveChangesButton.Attributes.Add("onclick", scriptString + this.Page.ClientScript.GetPostBackEventReference(SaveChangesButton, ""));
             * CancelButton.Attributes.Add("onclick", scriptString + this.Page.ClientScript.GetPostBackEventReference(CancelButton, ""));
             * if (DeleteButton.Visible)
             *      DeleteButton.Attributes.Add("onclick", scriptString + this.Page.ClientScript.GetPostBackEventReference(DeleteButton, ""));
             */

            if (String.IsNullOrEmpty(SavedMessage))
            {
                SavedMessage = RM.GetString("ChangesSavedMsg");
            }
            if (String.IsNullOrEmpty(CancelMessage))
            {
                CancelMessage = RM.GetString("ChangesDiscardedMsg");
            }
            if (String.IsNullOrEmpty(DeleteMessage))
            {
                DeleteMessage = RM.GetString("ItemDeletedMsg");
            }

            base.OnInit(e);
        }
예제 #20
0
 /// <summary>
 /// Applies the localization.
 /// </summary>
 protected void ApplyLocalization()
 {
     hlAddNewAddress.Text = RM.GetString("ACCOUNT_ADDRESS_NEW");
     foreach (DataListItem li in AddressList.Items)
     {
         Button btn = (Button)li.FindControl("btnEditAddress");
         if (btn != null)
         {
             btn.Text = RM.GetString("ACCOUNT_ADDRESS_EDIT");
         }
         btn = (Button)li.FindControl("btnDeleteAddress");
         if (btn != null)
         {
             btn.Text = RM.GetString("ACCOUNT_ADDRESS_DELETE");
         }
     }
 }
예제 #21
0
        /// <summary>
        /// Applies the localization.
        /// </summary>
        private void ApplyLocalization()
        {
            LblElement.Text = RM.GetString("ATTRIBUTECLASSES_ELEMENT");
            LblType.Text    = RM.GetString("ATTRIBUTECLASSES_TYPE");

            if (tblMetaClass != null && tblMetaClass.Visible)
            {
                RequiredFieldValidatorFriendlyName.ErrorMessage = RM.GetString("ATTRIBUTECLASSEDIT_ERROR_EMPTY_FRIENDLYNAME");

                if (ItemsGrid != null)
                {
                    ItemsGrid.Columns[0].HeaderText = RM.GetString("ATTRIBUTECLASSES_SELECT");
                    ItemsGrid.Columns[1].HeaderText = RM.GetString("ATTRIBUTECLASSES_SORT");
                    ItemsGrid.Columns[2].HeaderText = RM.GetString("ATTRIBUTECLASSES_HDR_NAME");
                }
            }
        }
예제 #22
0
        private void InteractiveSplineOnClickEvent(object sender, InteractiveActionEventArgs eventArgs)
        {
            OptionPxMode pxMode = m_isLong ? OptionPxMode.Ask : OptionPxMode.Bid;

            PositionsManager posMan = PositionsManager.GetManager(m_context);
            // Из практики торговли часто бывает ситуация, что торговля заблокирована, а снять задачу котирования УЖЕ хочется.
            //if (posMan.BlockTrading)
            //{
            //    //string msg = String.Format("[{0}] Trading is blocked. Please, change 'Block Trading' parameter.", m_optionPxMode);
            //    string msg = String.Format(RM.GetString("OptHandlerMsg.PositionsManager.TradingBlocked"), pxMode);
            //    m_context.Log(msg, MessageType.Info, true);
            //    return;
            //}

            InteractivePointActive tmp = eventArgs.Point;

            if ((tmp.Tag == null) || (!(tmp.Tag is PositionsManager.IvTargetInfo)))
            {
                string msg = String.Format("[{0}.ClickEvent] Denied #1", GetType().Name);
                m_context.Log(msg, MessageType.Warning, false);
                return;
            }

            {
                string msg = String.Format(CultureInfo.InvariantCulture, "[{0}.ClickEvent] Strike: {1}", GetType().Name, eventArgs.Point.ValueX);
                m_context.Log(msg, MessageType.Warning, false);
            }

            var ivTarget = tmp.Tag as PositionsManager.IvTargetInfo;

            // Передаю событие в PositionsManager
            //posMan.InteractiveSplineOnQuoteIvEvent(m_context, sender, eventArgs);
            // ОЧЕНЬ БОЛЬШОЙ ВОПРОС ЧТО БУДЕТ С КОНТЕКСТОМ ПРИ ЭТОМ???
            int res = posMan.CancelVolatility(m_context, ivTarget, "Left-click");

            if (res > 0)
            {
                string msg = String.Format(RM.GetString("OptHandlerMsg.PositionsManager.IvTargetCancelled"), pxMode, ivTarget);
                m_context.Log(msg, MessageType.Info, true, new Dictionary <string, object> {
                    { "VOLATILITY_ORDER_CANCELLED", msg }
                });

                // Вызываем принудительный пересчет агента, чтобы немедленно убрать заявку из стакана
                m_context.Recalc();
            }
        }
예제 #23
0
        private void panelDebugger_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
            {
                string file = ((string[])(e.Data.GetData(DataFormats.FileDrop)))[0];

                if (file.ToLower().EndsWith(".desktop"))
                {
                    MakeCurrentFile(file);
                }
                else
                {
                    MessageBox.Show("!",
                                    RM.GetString("Misc_ErrNotDesktopFile"),
                                    MessageBoxButtons.OK);
                }
            }
        }
예제 #24
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            LicenseManager.Validate(typeof(Mediachase.MetaDataPlus.MetaObject), null);

            Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "UpTemplate_SetPageTitle", String.Format("CSManagementClient.PageTitleControlId = '{0}';", this.lblPageTitle.ClientID), true);

            string userName = String.Empty;

            if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
            {
                ProfileContext context = FrameworkContext.Current.Profile;
                if (context != null && context.Profile != null && context.Profile.Account != null)
                {
                    userName = context.Profile.Account.Name;
                }

                if (String.IsNullOrEmpty(userName))
                {
                    userName = HttpContext.Current.User.Identity.Name;                 //FrameworkContext.Current.Profile;
                }
                lblUser.Text = String.Format("{0}, {1}", RM.GetString("UPTEMPLATE_WELCOME"), userName);
            }
            else
            {
                lblUser.Text = String.Empty;
            }


            lblUser.EnableViewState = false;

            // Remove any cached info
            CommerceLicenseInfo[] licenseInfo = CommerceLicensing.GetLicenseInfo();
            if (licenseInfo == null || licenseInfo.Length == 0)
            {
                lblLicenseInfo.Text      = "unlicensed version";
                lblLicenseInfo.ForeColor = Color.Red;
                lblLicenseInfo.Font.Bold = true;
            }
            else
            {
                lblLicenseInfo.Text = String.Format("{0} ({1})", licenseInfo[0].Edition, licenseInfo[0].Company);
            }
        }
예제 #25
0
        private void BindData()
        {
            if (MetaField != null && !MetaField.AllowNulls)
            {
                RequiredFieldValidator1.Enabled = true;
            }
            else
            {
                RequiredFieldValidator1.Enabled = false;
            }

            MetaLabelCtrl.Text = String.Format("{0} ({1})", MetaField.FriendlyName, LanguageCode);

            MetaDescriptionCtrl.Text             = MetaField.Description;
            RequiredFieldValidator1.ErrorMessage = String.Format("the {0} field is required", MetaField.FriendlyName);

            if (MetaField.AllowNulls)
            {
                DicSingleValueCtrl.Items.Add(new ListItem("[" + RM.GetString("SINGLEVALUECONTROL_EMPTY_VALUE") + "]", ""));
            }

            MetaDictionary dictionary = MetaField.Dictionary;

            if (dictionary != null)
            {
                foreach (MetaDictionaryItem item in dictionary)
                {
                    DicSingleValueCtrl.Items.Add(new ListItem(item.Value.ToString(), item.Value.ToString()));
                }
            }

            if (DicSingleValueCtrl.Items.Count > 0)
            {
                try
                {
                    ManagementHelper.SelectListItem(DicSingleValueCtrl, MetaObject.GetDictionaryItem(MetaField).Value);
                }
                catch
                {
                }
            }
        }
예제 #26
0
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, System.EventArgs e)
    {
        Page.ClientScript.RegisterClientScriptInclude(this.Page.GetType(), "CompareProducts_js", CommerceHelper.GetAbsolutePath("/Scripts/CompareProducts.js"));
        Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "CompareViewPageUrl", String.Format("CSCompareProducts.CompareViewPageUrl = \"{0}\";", CMSContext.Current.ResolveUrl("~/compare.aspx")), true);

        //if (!IsPostBack)
        {
            if (!String.IsNullOrEmpty(CurrentMetaClassName) && ProductsToCompare != null)
            {
                hfCurrentComparisonGroup.Value = CurrentMetaClassName;
                BindData();
                pnlCompareProducts.Visible = true;
                ClearCompareButton.Text    = RM.GetString("COMPAREPRODUCTSMODULE_CLEAR");
            }
            else
            {
                pnlCompareProducts.Visible = false;
            }
        }
    }
예제 #27
0
파일: Confirm.cs 프로젝트: enrique-thedy/bz
        protected override bool TryGetResult(out bool result)
        {
            var input = Renderer.ReadLine();

            if (string.IsNullOrEmpty(input))
            {
                if (_defaultValue != null)
                {
                    result = _defaultValue.Value;

                    return(true);
                }

                Renderer.SetValidationResult(new ValidationResult(RM.GetString("valueRequired")));
            }
            else
            {
                //  var lowerInput = input.ToLower();
                //  if (lowerInput == "y" || lowerInput == "yes" || lowerInput == "s" || lowerInput == "si")
                if (input.In(_yesOptions))
                {
                    result = true;

                    return(true);
                }

                //  if (lowerInput == "n" || lowerInput == "no")
                if (input.In(_noOptions))
                {
                    result = false;

                    return(true);
                }

                Renderer.SetValidationResult(new ValidationResult(RM.GetString("valueInvalid")));
            }

            result = default;

            return(false);
        }
예제 #28
0
        /// <summary>
        /// Binds the table.
        /// </summary>
        private void BindTable()
        {
            OrdersList.Columns[0].HeaderText = RM.GetString("ACCOUNT_ORDERS_ID_LABEL");
            OrdersList.Columns[1].HeaderText = RM.GetString("GENERAL_TOTAL_LABEL");
            OrdersList.Columns[3].HeaderText = RM.GetString("GENERAL_CREATED_LABEL");

            PurchaseOrder[] orders = OrderContext.Current.GetPurchaseOrders(ProfileContext.Current.UserId);

            if (orders != null)
            {
                // convert created time for every order from UTC to server time
                foreach (PurchaseOrder order in orders)
                {
                    order.Created = CommonHelper.GetUserDateTime(order.Created);
                }

                // bind orders table
                OrdersList.DataSource = orders;
                OrdersList.DataBind();
            }
        }
예제 #29
0
        /// <summary>
        /// Метод под флаг TemplateTypes.INTERACTIVESPLINE
        /// </summary>
        public InteractiveSeries Execute(InteractiveSeries smile, IOptionSeries optSer, double scaleMult, int barNum)
        {
            if ((smile == null) || (optSer == null))
            {
                return(Constants.EmptySeries);
            }

            int barsCount = m_context.BarsCount;

            if (!m_context.IsLastBarUsed)
            {
                barsCount--;
            }
            if (barNum < barsCount - 1)
            {
                return(Constants.EmptySeries);
            }

            SmileInfo oldInfo = smile.GetTag <SmileInfo>();

            if ((oldInfo == null) || (oldInfo.ContinuousFunction == null))
            {
                return(Constants.EmptySeries);
            }

            double futPx = oldInfo.F;
            double dT    = oldInfo.dT;

            if (m_executeCommand)
            {
                string msg = String.Format("[{0}.StartButton] Strike: {1}", GetType().Name, m_strike);
                m_context.Log(msg, MessageType.Info, false);
            }

            #region 1. Список страйков
            HashSet <string> serList = StrikeList;
            serList.Clear();

            IOptionStrikePair[] pairs;
            if (Double.IsNaN(m_strikeStep) || (m_strikeStep <= Double.Epsilon))
            {
                pairs = optSer.GetStrikePairs().ToArray();
            }
            else
            {
                // Выделяем страйки, которые нацело делятся на StrikeStep
                pairs = (from p in optSer.GetStrikePairs()
                         let test = m_strikeStep * Math.Round(p.Strike / m_strikeStep)
                                    where DoubleUtil.AreClose(p.Strike, test)
                                    select p).ToArray();

                // [2015-12-24] Если шаг страйков по ошибке задан совершенно неправильно,
                // то в коллекцию ставим все имеющиеся страйки.
                // Пользователь потом разберется
                if (pairs.Length <= 0)
                {
                    pairs = optSer.GetStrikePairs().ToArray();
                }
            }
            //if (pairs.Length < 2)
            //    return Constants.EmptyListDouble;

            foreach (IOptionStrikePair pair in pairs)
            {
                double k = pair.Strike;
                serList.Add(k.ToString(StrikeFormat, CultureInfo.InvariantCulture));
            }
            #endregion 1. Список страйков

            InteractiveSeries        res           = Constants.EmptySeries;
            List <InteractiveObject> controlPoints = new List <InteractiveObject>();

            #region 2. Формируем улыбку просто для отображения текущего положения потенциальной котировки
            // При нулевом рабочем объёме не утруждаемся рисованием лишних линий
            if (!DoubleUtil.IsZero(m_qty))
            {
                for (int j = 0; j < pairs.Length; j++)
                {
                    var    pair  = pairs[j];
                    double sigma = oldInfo.ContinuousFunction.Value(pair.Strike) + m_shiftIv;
                    if (!DoubleUtil.IsPositive(sigma))
                    {
                        //string msg = String.Format("[DEBUG:{0}] Invalid sigma:{1} for strike:{2}", GetType().Name, sigma, nodeInfo.Strike);
                        //m_context.Log(msg, MessageType.Warning, true);
                        continue;
                    }

                    //bool isCall = (futPx <= pair.Strike);
                    bool isCall;
                    if (m_optionType == StrikeType.Call)
                    {
                        isCall = true;
                    }
                    else if (m_optionType == StrikeType.Put)
                    {
                        isCall = false;
                    }
                    else
                    {
                        isCall = (futPx <= pair.Strike);
                    }

                    StrikeType optionType = isCall ? StrikeType.Call : StrikeType.Put;
                    Contract.Assert(pair.Tick < 1, $"#1 На тестовом контуре Дерибит присылает неправильный шаг цены! Tick:{pair.Tick}; Decimals:{pair.Put.Security.Decimals}");
                    double theorOptPxDollars = FinMath.GetOptionPrice(futPx, pair.Strike, dT, sigma, oldInfo.RiskFreeRate, isCall);
                    // Сразу(!!!) переводим котировку из баксов в битки
                    double theorOptPxBitcoins = theorOptPxDollars / scaleMult;

                    // Сдвигаем цену в долларах (с учетом ш.ц. в баксах)
                    theorOptPxDollars += m_shiftPriceStep * pair.Tick * scaleMult;
                    theorOptPxDollars  = Math.Round(theorOptPxDollars / (pair.Tick * scaleMult)) * (pair.Tick * scaleMult);

                    // Сдвигаем цену в биткойнах (с учетом ш.ц. в битках)
                    theorOptPxBitcoins += m_shiftPriceStep * pair.Tick;
                    theorOptPxBitcoins  = Math.Round(theorOptPxBitcoins / pair.Tick) * pair.Tick;
                    if ((!DoubleUtil.IsPositive(theorOptPxBitcoins)) || (!DoubleUtil.IsPositive(theorOptPxDollars)))
                    {
                        //string msg = String.Format("[DEBUG:{0}] Invalid theorOptPx:{1} for strike:{2}", GetType().Name, theorOptPx, nodeInfo.Strike);
                        //m_context.Log(msg, MessageType.Warning, true);
                        continue;
                    }

                    // Пересчитываем сигму обратно, ЕСЛИ мы применили сдвиг цены в абсолютном выражении
                    if (m_shiftPriceStep != 0)
                    {
                        // Обратный пересчет в волатильность
                        sigma = FinMath.GetOptionSigma(futPx, pair.Strike, dT, theorOptPxDollars, oldInfo.RiskFreeRate, isCall);
                        if (!DoubleUtil.IsPositive(sigma))
                        {
                            //string msg = String.Format("[DEBUG:{0}] Invalid sigma:{1} for strike:{2}", GetType().Name, sigma, nodeInfo.Strike);
                            //m_context.Log(msg, MessageType.Warning, true);
                            continue;
                        }
                    }

                    // ReSharper disable once UseObjectOrCollectionInitializer
                    SmileNodeInfo nodeInfo = new SmileNodeInfo();
                    var           secDesc  = isCall ? pair.CallFinInfo.Security : pair.PutFinInfo.Security;
                    nodeInfo.F            = oldInfo.F;
                    nodeInfo.dT           = oldInfo.dT;
                    nodeInfo.RiskFreeRate = oldInfo.RiskFreeRate;
                    nodeInfo.Strike       = pair.Strike;
                    nodeInfo.Sigma        = sigma;
                    nodeInfo.OptPx        = theorOptPxBitcoins;
                    nodeInfo.OptionType   = isCall ? StrikeType.Call : StrikeType.Put;
                    nodeInfo.Pair         = pair;

                    nodeInfo.Symbol   = secDesc.Name;
                    nodeInfo.DSName   = secDesc.DSName;
                    nodeInfo.Expired  = secDesc.Expired;
                    nodeInfo.FullName = secDesc.FullName;

                    // ReSharper disable once UseObjectOrCollectionInitializer
                    InteractivePointActive tmp = new InteractivePointActive();

                    tmp.IsActive     = true;
                    tmp.ValueX       = pair.Strike;
                    tmp.ValueY       = sigma;
                    tmp.DragableMode = DragableMode.Yonly;
                    tmp.Tooltip      = String.Format(CultureInfo.InvariantCulture,
                                                     " F: {0}\r\n K: {1}; IV: {2:P2}\r\n {3} px {4}",
                                                     futPx, pair.Strike, sigma, optionType, theorOptPxBitcoins);

                    tmp.Tag = nodeInfo;

                    //tmp.Color = Colors.White;
                    if (m_qty > 0)
                    {
                        tmp.Geometry = Geometries.Triangle;
                    }
                    else if (m_qty < 0)
                    {
                        tmp.Geometry = Geometries.TriangleDown;
                    }
                    else
                    {
                        tmp.Geometry = Geometries.None;
                    }

                    InteractiveObject obj = new InteractiveObject();
                    obj.Anchor = tmp;

                    controlPoints.Add(obj);
                }

                // ReSharper disable once UseObjectOrCollectionInitializer
                res = new InteractiveSeries(); // Здесь так надо -- мы делаем новую улыбку
                res.ControlPoints = new ReadOnlyCollection <InteractiveObject>(controlPoints);

                // ReSharper disable once UseObjectOrCollectionInitializer
                SmileInfo sInfo = new SmileInfo();
                sInfo.F            = futPx;
                sInfo.dT           = dT;
                sInfo.Expiry       = oldInfo.Expiry;
                sInfo.ScriptTime   = oldInfo.ScriptTime;
                sInfo.RiskFreeRate = oldInfo.RiskFreeRate;
                sInfo.BaseTicker   = oldInfo.BaseTicker;

                res.Tag = sInfo;

                if (controlPoints.Count > 0)
                {
                    res.ClickEvent -= InteractiveSplineOnQuoteIvEvent;
                    res.ClickEvent += InteractiveSplineOnQuoteIvEvent;

                    m_clickableSeries = res;
                }
            }
            #endregion 2. Формируем улыбку просто для отображения текущего положения потенциальной котировки

            PositionsManager posMan = PositionsManager.GetManager(m_context);
            if (m_cancelAllLong)
            {
                posMan.DropAllLongIvTargets(m_context);
            }
            if (m_cancelAllShort)
            {
                posMan.DropAllShortIvTargets(m_context);
            }

            #region 4. Котирование
            {
                var longTargets  = posMan.GetIvTargets(true);
                var shortTargets = posMan.GetIvTargets(false);
                var ivTargets    = longTargets.Union(shortTargets).ToList();
                for (int j = 0; j < ivTargets.Count; j++)
                {
                    var ivTarget = ivTargets[j];

                    // PROD-6102 - Требуется точное совпадение опционной серии
                    if (optSer.ExpirationDate.Date != ivTarget.SecInfo.Expiry.Date)
                    {
                        // Вывести предупреждение???
                        continue;
                    }

                    IOptionStrikePair pair;
                    double            k = ivTarget.SecInfo.Strike;
                    if (!optSer.TryGetStrikePair(k, out pair))
                    {
                        // Вывести предупреждение???
                        continue;
                    }

                    double      sigma;
                    QuoteIvMode quoteMode = ivTarget.QuoteMode;
                    if (quoteMode == QuoteIvMode.Absolute)
                    {
                        sigma = ivTarget.EntryIv;
                    }
                    else
                    {
                        sigma = oldInfo.ContinuousFunction.Value(k) + ivTarget.EntryIv;
                        if (!DoubleUtil.IsPositive(sigma))
                        {
                            //string msg = String.Format("[DEBUG:{0}] Invalid sigma:{1} for strike:{2}", GetType().Name, sigma, nodeInfo.Strike);
                            //m_context.Log(msg, MessageType.Warning, true);
                            continue;
                        }
                    }

                    //bool isCall = (futPx <= pair.Strike);
                    // Определяю тип опциона на основании информации в Задаче
                    StrikeType taskOptionType = StrikeType.Any;
                    if (ivTarget.SecInfo.StrikeType.HasValue)
                    {
                        taskOptionType = ivTarget.SecInfo.StrikeType.Value;
                    }

                    bool isCall;
                    if (taskOptionType == StrikeType.Call)
                    {
                        isCall = true;
                    }
                    else if (taskOptionType == StrikeType.Put)
                    {
                        isCall = false;
                    }
                    else
                    {
                        isCall = (futPx <= pair.Strike); // Это аварийная ситуация?
                    }
                    StrikeType optionType = isCall ? StrikeType.Call : StrikeType.Put;
                    Contract.Assert(pair.Tick < 1, $"#3 На тестовом контуре Дерибит присылает неправильный шаг цены! Tick:{pair.Tick}; Decimals:{pair.Put.Security.Decimals}");
                    double theorOptPxDollars = FinMath.GetOptionPrice(futPx, pair.Strike, dT, sigma, oldInfo.RiskFreeRate, isCall);
                    // Сразу(!!!) переводим котировку из баксов в битки
                    double theorOptPxBitcoins = theorOptPxDollars / scaleMult;

                    // Сдвигаем цену в долларах (с учетом ш.ц. в баксах)
                    theorOptPxDollars += ivTarget.EntryShiftPrice * pair.Tick * scaleMult;
                    theorOptPxDollars  = Math.Round(theorOptPxDollars / (pair.Tick * scaleMult)) * (pair.Tick * scaleMult);

                    // Сдвигаем цену в биткойнах (с учетом ш.ц. в битках)
                    theorOptPxBitcoins += ivTarget.EntryShiftPrice * pair.Tick;
                    theorOptPxBitcoins  = Math.Round(theorOptPxBitcoins / pair.Tick) * pair.Tick;
                    if ((!DoubleUtil.IsPositive(theorOptPxBitcoins)) || (!DoubleUtil.IsPositive(theorOptPxDollars)))
                    {
                        //string msg = String.Format("[DEBUG:{0}] Invalid theorOptPx:{1} for strike:{2}", GetType().Name, theorOptPx, nodeInfo.Strike);
                        //m_context.Log(msg, MessageType.Warning, true);
                        continue;
                    }

                    IOptionStrike optStrike = isCall ? pair.Call : pair.Put;
                    ISecurity     sec       = optStrike.Security;
                    double        totalQty  = posMan.GetTotalQty(sec, m_context.BarsCount, TotalProfitAlgo.AllPositions, ivTarget.IsLong);
                    // Поскольку котирование страйка по волатильности -- это вопрос набора нужного количества СТРЕДДЛОВ,
                    // то учитывать надо суммарный объём опционов как в колах, так и в путах.
                    // НО ЗАДАЧУ-ТО Я СТАВЛЮ ДЛЯ КОНКРЕТНОГО ИНСТРУМЕНТА!
                    // Как быть?
                    //double totalQty = posMan.GetTotalQty(pair.Put.Security, m_context.BarsCount, TotalProfitAlgo.AllPositions, ivTarget.IsLong);
                    //totalQty += posMan.GetTotalQty(pair.Call.Security, m_context.BarsCount, TotalProfitAlgo.AllPositions, ivTarget.IsLong);
                    double targetQty = Math.Abs(ivTarget.TargetShares) - totalQty;
                    // Если имеется дробный LotTick (как в Дерибит к примеру), то надо предварительно округлить
                    targetQty = sec.RoundShares(targetQty);
                    if (targetQty > 0)
                    {
                        string note = String.Format(CultureInfo.InvariantCulture,
                                                    "{0}; ActQty:{1}; Px:{2}; IV:{3:P2}",
                                                    ivTarget.EntryNotes, targetQty, theorOptPxBitcoins, sigma);
                        if (ivTarget.IsLong)
                        {
                            posMan.BuyAtPrice(m_context, sec, targetQty, theorOptPxBitcoins, ivTarget.EntrySignalName, note);
                        }
                        else
                        {
                            posMan.SellAtPrice(m_context, sec, targetQty, theorOptPxBitcoins, ivTarget.EntrySignalName, note);
                        }
                    }
                    else
                    {
                        string msg = String.Format(CultureInfo.InvariantCulture,
                                                   "IvTarget cancelled. SignalName:{0}; Notes:{1}", ivTarget.EntrySignalName, ivTarget.EntryNotes);
                        posMan.CancelVolatility(m_context, ivTarget, msg);

                        // TODO: потом убрать из ГЛ
                        m_context.Log(msg, MessageType.Info, true, new Dictionary <string, object> {
                            { "VOLATILITY_ORDER_CANCELLED", msg }
                        });
                    }
                }
            }
            #endregion 4. Котирование

            #region 5. Торговля
            if (m_executeCommand && (!DoubleUtil.IsZero(m_qty)))
            {
                double k;
                if ((!Double.TryParse(m_strike, out k)) &&
                    (!Double.TryParse(m_strike, NumberStyles.Any, CultureInfo.InvariantCulture, out k)))
                {
                    return(res);
                }

                var pair = (from p in pairs where DoubleUtil.AreClose(k, p.Strike) select p).SingleOrDefault();
                if (pair == null)
                {
                    return(res);
                }

                InteractiveObject obj = (from o in controlPoints where DoubleUtil.AreClose(k, o.Anchor.ValueX) select o).SingleOrDefault();
                if (obj == null)
                {
                    return(res);
                }

                // TODO: для режима котирования в абсолютных числах сделать отдельную ветку
                //double iv = obj.Anchor.ValueY;
                const QuoteIvMode QuoteMode = QuoteIvMode.Relative;
                if (posMan.BlockTrading)
                {
                    string msg = String.Format(RM.GetString("OptHandlerMsg.PositionsManager.TradingBlocked"),
                                               m_context.Runtime.TradeName + ":QuoteIv");
                    m_context.Log(msg, MessageType.Warning, true);
                    return(res);
                }

                // Выбираю тип инструмента пут или колл?
                bool isCall;
                if (m_optionType == StrikeType.Call)
                {
                    isCall = true;
                }
                else if (m_optionType == StrikeType.Put)
                {
                    isCall = false;
                }
                else
                {
                    isCall = (futPx <= k);
                }

                double iv     = m_shiftIv;
                int    shift  = m_shiftPriceStep;
                var    option = isCall ? pair.Call : pair.Put;
                if (m_qty > 0)
                {
                    // Пересчитываю целочисленный параметр Qty в фактические лоты конкретного инструмента
                    double actQty  = m_qty * option.LotTick;
                    string sigName = String.Format(CultureInfo.InvariantCulture,
                                                   "Qty:{0}; IV:{1:P2}+{2}; dT:{3}; Mode:{4}", actQty, iv, shift, dT, QuoteMode);
                    posMan.BuyVolatility(m_context, option, Math.Abs(actQty), QuoteMode, iv, shift, "BuyVola", sigName);

                    m_context.Log(sigName, MessageType.Info, false);
                }
                else if (m_qty < 0)
                {
                    // Пересчитываю целочисленный параметр Qty в фактические лоты конкретного инструмента
                    double actQty  = m_qty * option.LotTick;
                    string sigName = String.Format(CultureInfo.InvariantCulture,
                                                   "Qty:{0}; IV:{1:P2}+{2}; dT:{3}; Mode:{4}", actQty, iv, shift, dT, QuoteMode);
                    posMan.SellVolatility(m_context, option, Math.Abs(actQty), QuoteMode, iv, shift, "SellVola", sigName);

                    m_context.Log(sigName, MessageType.Info, false);
                }
            }
            #endregion 5. Торговля

            return(res);
        }
예제 #30
0
        private void InteractiveSplineOnClickEvent(object sender, InteractiveActionEventArgs eventArgs)
        {
            // [2016-03-01] PROD-2452: Запрещаю торговлю по узлу, если нет "подсветки"
            {
                InteractiveObject obj = eventArgs.InteractiveObject;
                if ((obj == null) || (obj.Anchor == null) || (obj.ControlPoint1 == null) ||
                    (!(obj.Anchor is InteractivePointActive)) || (!(obj.ControlPoint1 is InteractivePointActive)))
                {
                    string msg = String.Format("[{0}.ClickEvent] Denied #1", GetType().Name);
                    m_context.Log(msg, MessageType.Warning, false);
                    return;
                }

                var cp1 = (InteractivePointActive)obj.ControlPoint1;
                // PROD-4967 - Необязательно проверять активность якоря.
                // Потому что эта настройка делается на более позднем этапе в момент создания графического объекта
                // методом smilePanePane.AddList("SmilePane_pane_TradeAsks_chart", <...>)
                //var anchor = (InteractivePointActive)obj.Anchor;
                //if ((anchor.IsActive == null) || (!anchor.IsActive.Value) ||
                if ((cp1.IsActive == null) || (!cp1.IsActive.Value))
                {
                    string msg = String.Format("[{0}.ClickEvent] Denied #3 (ControlPoint1 is not active)", GetType().Name);
                    m_context.Log(msg, MessageType.Warning, false);
                    return;
                }
            }

            PositionsManager posMan = PositionsManager.GetManager(m_context);

            if (posMan.BlockTrading)
            {
                //string msg = String.Format("[{0}] Trading is blocked. Please, change 'Block Trading' parameter.", m_optionPxMode);
                string msg = String.Format(RM.GetString("OptHandlerMsg.PositionsManager.TradingBlocked"), m_optionPxMode);
                m_context.Log(msg, MessageType.Info, true);
                return;
            }

            // Здесь нет проверки знака m_qty, потому что в данном кубике мы действительно можем и продавать и покупать

            SmileNodeInfo nodeInfo = eventArgs.Point.Tag as SmileNodeInfo;

            if (nodeInfo == null)
            {
                //string msg = String.Format("[{0}] There is no nodeInfo. Quote type: {1}; Strike: {2}",
                string msg = RM.GetStringFormat(CultureInfo.InvariantCulture, "OptHandlerMsg.ThereIsNoNodeInfo",
                                                m_context.Runtime.TradeName, m_optionPxMode, eventArgs.Point.ValueX);
                m_context.Log(msg, MessageType.Error, true);
                return;
            }

            {
                string msg = String.Format(CultureInfo.InvariantCulture, "[{0}.ClickEvent] Strike: {1}; Security: {2}",
                                           GetType().Name, eventArgs.Point.ValueX, nodeInfo.FullName);
                m_context.Log(msg, MessageType.Info, false);
            }

            nodeInfo.ClickTime = DateTime.Now;

            // [2015-10-02] Подписка на данный инструмент, чтобы он появился в коллекции Context.Runtime.Securities
            ISecurity testSec = (from s in Context.Runtime.Securities
                                 let secDesc = s.SecurityDescription
                                               where secDesc.FullName.Equals(nodeInfo.FullName, StringComparison.InvariantCultureIgnoreCase) &&
                                               secDesc.DSName.Equals(nodeInfo.DSName, StringComparison.InvariantCultureIgnoreCase) &&
                                               secDesc.Name.Equals(nodeInfo.Symbol, StringComparison.InvariantCultureIgnoreCase)
                                               select s).SingleOrDefault();

            if (testSec == null)
            {
                ISecurity sec = nodeInfo.Security;
                int       bc  = sec.Bars.Count;
                string    msg = String.Format("[{0}] There is security DsName: {1}; Symbol: {2}; Security: {3} with {4} bars available.",
                                              m_optionPxMode, nodeInfo.DSName, nodeInfo.Symbol, nodeInfo.FullName, bc);
                Context.Log(msg, MessageType.Info, false);

                // Пересчитываю целочисленный параметр Qty в фактические лоты конкретного инструмента
                double actQty = m_qty * sec.LotTick; // Здесь нет модуля, потому что направление сделки несет в себе знак Qty
                nodeInfo.Qty = actQty;
            }
            else if ((nodeInfo.Pair != null) && (nodeInfo.Pair.Put != null))
            {
                // Аварийная ветка
                // Пересчитываю целочисленный параметр Qty в фактические лоты конкретного инструмента
                double actQty = m_qty * nodeInfo.Pair.Put.LotTick; // Здесь нет модуля, потому что направление сделки несет в себе знак Qty
                nodeInfo.Qty = actQty;
            }
            else
            {
                // Аварийная ветка
                // Не могу пересчитать целочисленный параметр Qty в фактические лоты конкретного инструмента!
                //double actQty = Math.Abs(m_qty * nodeInfo.Pair.Put.LotTick);
                nodeInfo.Qty = m_qty; // Здесь нет модуля, потому что направление сделки несет в себе знак Qty

                string msg = String.Format(CultureInfo.InvariantCulture, "[{0}.ClickEvent] LotTick is set to 1.", GetType().Name);
                m_context.Log(msg, MessageType.Warning, false);
            }

            // Передаю событие в PositionsManager дополнив его инфой о количестве лотов
            posMan.InteractiveSplineOnClickEvent(m_context, sender, eventArgs);
        }