public EditSecurityCommand(Security security)
		{
			if (security == null)
				throw new ArgumentNullException("security");

			Security = security;
		}
Example #2
0
		/// <summary>
		/// To get historical ticks.
		/// </summary>
		/// <param name="security">The instrument for which you need to get all trades.</param>
		/// <param name="count">Maximum ticks count.</param>
		/// <param name="isSuccess">Whether all data were obtained successfully or the download process has been interrupted.</param>
		/// <returns>Historical ticks.</returns>
		public IEnumerable<ExecutionMessage> GetHistoricalTicks(Security security, long count, out bool isSuccess)
		{
			if (security == null)
				throw new ArgumentNullException(nameof(security));

			this.AddInfoLog(LocalizedStrings.Str2144Params, security, count);

			var transactionId = TransactionIdGenerator.GetNextId();

			var info = RefTuple.Create(new List<ExecutionMessage>(), new SyncObject(), false, security, false);
			_ticksInfo.Add(transactionId, info);

			SendInMessage(new MarketDataMessage
			{
				SecurityId = security.ToSecurityId(),
				DataType = MarketDataTypes.Trades,
				Count = count,
				IsSubscribe = true,
				TransactionId = transactionId,
			});

			lock (info.Second)
			{
				if (!info.Third)
					info.Second.Wait();
			}

			isSuccess = info.Fifth;

			return info.First;
		}
 public bool OnDataReceivedTest(string providerid, string symbol, string name, double value)
 {
     var tick = new SecurityTicks(symbol);
     var sec = new Security(providerid, name, value);
     tick.OnDataReceived(sec);
     return tick.SymbolTicks.ToList().Contains(sec);
 }
Example #4
0
 public override void CreateGroup(EngineRequest request, Security.Group group)
 {
     CheckInitialization();
     Logger.Storage.Debug("Creating group: " + group.GroupName + "...");
     EngineMethods.CreateGroup act = new EngineMethods.CreateGroup(request, group);
     act.Execute();
 }
		public OpenMarketDepthCommand(Security security)
		{
			if (security == null)
				throw new ArgumentNullException(nameof(security));

			Security = security;
		}
		private void CreateContinuousSecurity_OnClick(object sender, RoutedEventArgs e)
		{
			_continuousSecurityWindow = new ContinuousSecurityWindow
			{
				SecurityProvider = _entityRegistry.Securities,
				ContinuousSecurity = new ContinuousSecurity { Board = ExchangeBoard.Associated }
			};

			if (!_continuousSecurityWindow.ShowModal(this))
				return;

			_continuousSecurity = _continuousSecurityWindow.ContinuousSecurity;
			ContinuousSecurity.Content = _continuousSecurity.Id;

			var first = _continuousSecurity.InnerSecurities.First();

			var gluingSecurity = new Security
			{
				Id = _continuousSecurity.Id,
				Code = _continuousSecurity.Code,
				Board = ExchangeBoard.Associated,
				Type = _continuousSecurity.Type,
				VolumeStep = first.VolumeStep,
				PriceStep = first.PriceStep,
				ExtensionInfo = new Dictionary<object, object> { { "GluingSecurity", true } }
			};

			if (_entityRegistry.Securities.ReadById(gluingSecurity.Id) == null)
			{
				_entityRegistry.Securities.Save(gluingSecurity);
			}
		}
 public DownloadGroup(IDatabase db, Security.Group group,
     int sendTimeout, int receiveTimeout, int sendBufferSize, int receiveBufferSize)
     : base(sendTimeout, receiveTimeout, sendBufferSize, receiveBufferSize)
 {
     _db = db;
     _group = group;
 }
        /********************************************************
        * CLASS PROPERTIES
        *********************************************************/
        /********************************************************
        * CLASS METHODS
        *********************************************************/
        /// <summary>
        /// Process a order fill with the supplied security and order.
        /// </summary>
        /// <param name="vehicle">Asset we're working with</param>
        /// <param name="order">Order class to check if filled.</param>
        /// <returns>OrderEvent packet with the full or partial fill information</returns>
        public virtual OrderEvent Fill(Security vehicle, Order order)
        {
            var fill = new OrderEvent(order);

            try
            {
                //Based on the order type, select the fill model method.
                switch (order.Type)
                {
                    case OrderType.Limit:
                        fill = LimitFill(vehicle, order);
                        break;
                    case OrderType.StopMarket:
                        fill = StopFill(vehicle, order);
                        break;
                    case OrderType.Market:
                        fill = MarketFill(vehicle, order);
                        break;
                }
            }
            catch (Exception err)
            {
                Log.Error("Equity.EquityTransactionModel.Fill(): " + err.Message);
            }
            return fill;
        }
Example #9
0
        protected override void TestSecure(Security config)
        {
            base.TestSecure(config);

            var full = new[] { Operation.Read, Operation.Write, Operation.Execute };
            config.GrantAdministrator(this.ObjectType, full);
        }
Example #10
0
	protected void Page_Load(object sender, EventArgs e)
	{
		if (Request.QueryString["p"] != null)
		{
			Security sec = new Security();
			sec = GetPagePermit(Request.QueryString["p"].Trim());
			if (sec != null)
			{
				authString = "var pagePermit = { " +
							" enableBrowser : " + sec.EnableBrowser.ToString().ToLower() + ", " +
							" enableQuery : " + sec.EnableQuery.ToString().ToLower() + ", " +
							" enableAdd : " + sec.EnableAdd.ToString().ToLower() + ", " +
							" enableEdit : " + sec.EnableEdit.ToString().ToLower() + ", " +
							" enableDelete : " + sec.EnableDelete.ToString().ToLower() + ", " +
							" enablePrint : " + sec.EnablePrint.ToString().ToLower() + ", " +
							" enableEditSave : " + sec.EnableEditSave.ToString().ToLower() + ", " +
							" enableNewSave : " + sec.EnableNewSave.ToString().ToLower() + " };";
			}
			else
			{
				//資料庫不存在權限設定,頁面不限定權限
				authString = "var pagePermit = { " +
							" enableBrowser : true, " +
							" enableQuery : true, " +
							" enableAdd : true, " +
							" enableEdit : true, " +
							" enableDelete : true, " +
							" enablePrint : true, " +
							" enableEditSave : true, " +
							" enableNewSave : true };";
			}
		}

		Response.Write(authString);
	}
Example #11
0
		/// <summary>
		/// To create from <see cref="Decimal"/> the pips values.
		/// </summary>
		/// <param name="value"><see cref="Decimal"/> value.</param>
		/// <param name="security">The instrument from which information about the price increment is taken .</param>
		/// <returns>Pips.</returns>
		public static Unit Pips(this decimal value, Security security)
		{
			if (security == null)
				throw new ArgumentNullException(nameof(security));

			return new Unit(value, UnitTypes.Step, type => GetTypeValue(security, type));
		}
        private void TryAddToCache(Security security)
        {
            if (security == null)
                throw new ArgumentNullException("security");

            _cacheById.SafeAdd(security.Id, key => security);
        }
Example #13
0
        /// <summary>
        /// Generates a new order for the specified security taking into account the total margin
        /// used by the account. Returns null when no margin call is to be issued.
        /// </summary>
        /// <param name="security">The security to generate a margin call order for</param>
        /// <param name="netLiquidationValue">The net liquidation value for the entire account</param>
        /// <param name="totalMargin">The totl margin used by the account in units of base currency</param>
        /// <returns>An order object representing a liquidation order to be executed to bring the account within margin requirements</returns>
        public override SubmitOrderRequest GenerateMarginCallOrder(Security security, decimal netLiquidationValue, decimal totalMargin)
        {
            if (totalMargin <= netLiquidationValue)
            {
                return null;
            }
            var forex = (Forex)security;

            // we haven't begun receiving data for this yet
            if (forex.Price == 0m || forex.QuoteCurrency.ConversionRate == 0m)
            {
                return null;
            }

            // compute the amount of quote currency we need to liquidate in order to get within margin requirements
            decimal delta = (totalMargin - netLiquidationValue)/forex.QuoteCurrency.ConversionRate;

            // compute the number of shares required for the order, rounding up
            int quantity = (int) Math.Round(delta/security.Price, MidpointRounding.AwayFromZero);

            // don't try and liquidate more share than we currently hold
            quantity = Math.Min((int)security.Holdings.AbsoluteQuantity, quantity);
            if (security.Holdings.IsLong)
            {
                // adjust to a sell for long positions
                quantity *= -1;
            }

            return new SubmitOrderRequest(OrderType.Market, security.Type, security.Symbol, quantity, 0, 0, security.LocalTime.ConvertToUtc(security.Exchange.TimeZone), "Margin Call");
        }
 public void OnMarketDataClosedEventUnknownProviderEOFTest()
 {
     var data = new Security("Mazaya", Miscellaneous.END_OF_FEED, 0D);
     base._onNewSecurityTicksEvent = DataProcessingHandler;
     OnMarketClosedEvent(data);
     Assert.Pass("These test method provide code coverage for the unit being tested.");
 }
 public bool PublishMarketDataNullSecurityTest(Security data)
 {
     DataReceived = null;
     base._onNewSecurityTicksEvent = DataProcessingHandler;
     PublishMarketData(data);
     return (null == DataReceived);
 }
Example #16
0
		private void PopulateFraudData(Security.FraudCheckData d, OrderTaskContext context)
		{            
			if (context.MTApp.CurrentRequestContext.RoutingContext.HttpContext != null) {
				if (context.MTApp.CurrentRequestContext.RoutingContext.HttpContext.Request.UserHostAddress != null) {
					d.IpAddress = context.MTApp.CurrentRequestContext.RoutingContext.HttpContext.Request.UserHostAddress;
				}
			}
			
            if (context.Order.UserEmail != string.Empty) {
				d.EmailAddress = context.Order.UserEmail;
				string[] parts = d.EmailAddress.Split('@');
				if (parts.Length > 1) {
					d.DomainName = parts[1];
				}
			}
			
            d.PhoneNumber = context.Order.BillingAddress.Phone;

            foreach (Orders.OrderTransaction p in context.MTApp.OrderServices.Transactions.FindForOrder(context.Order.bvin))
            {
                if (p.Action == MerchantTribe.Payment.ActionType.CreditCardInfo)
                {
					d.CreditCard = p.CreditCard.CardNumber;
                    break; 
				}				
			}
		}
		public LookupSecuritiesCommand(Security criteria)
		{
			if (criteria == null)
				throw new ArgumentNullException(nameof(criteria));

			Criteria = criteria;
		}
        public bool AverageProcessorProcessSecurityNullDataTest(Security data)
        {
            ISecurityProcessor processor = new AverageProcessor("AAA");
            processor.ProcessSecurity(data);

            return (null == data);
        }
 /// <summary>
 /// Execute each of the internally held initializers in sequence
 /// </summary>
 /// <param name="security">The security to be initialized</param>
 public void Initialize(Security security)
 {
     foreach (var initializer in _initializers)
     {
         initializer.Initialize(security);
     }
 }
Example #20
0
        public Model.Document Transition(Security.User user)
        {
            Model.Document doc = new Model.Document();
            JArray jarray = null;

            try
            {
                doc.Id = user.Id;
                if (user.Rev != null)
                    doc.Rev = user.Rev;
                doc["Type"] = "user";
                doc["Password"] = user.Password;
                doc["FirstName"] = user.FirstName;
                doc["MiddleName"] = user.MiddleName;
                doc["LastName"] = user.LastName;
                doc["Superuser"] = user.IsSuperuser;

                if (user.Groups != null)
                {
                    jarray = new JArray();
                    for (int i = 0; i < user.Groups.Count; i++)
                        jarray.Add(user.Groups[i]);
                }

                doc["Groups"] = jarray;
            }
            catch (Exception e)
            {
                Logger.Storage.Error("An exception occurred while attempting to parse the user.", e);
                throw;
            }

            return doc;
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     Security sec = new Security();
     //string usercode = sec.getUserCode();
        // string usercode = "chinallk1";
     //Session["usercode"] = usercode;
 }
Example #22
0
 /// <summary>
 /// 更新登入者密碼
 /// </summary>
 /// <returns>bool</returns>
 private bool Updateuerpwd(string pwd)
 {
     bool success = false;
     Security sec = new Security();
     success = sec.Updateuserpwd(Session["UserID"].ToString(), pwd);
     return success;
 }
Example #23
0
    protected void acceptButton_Click(object sender, EventArgs e)
    {
        try
        {
            if (this.IsValid)
            {
                List<string> persAdded = new List<string>();

                foreach (ListItem it in permisos_CBList.Items)
                {
                    if (it.Selected == true)
                    {
                        persAdded.Add(it.Text);
                        it.Selected = false;
                    }
                }

                AdministradordeSistema admin = new AdministradordeSistema();//tmp-> deberia ser quien este logeado!
                Security sec = new Security();
                long centro = sec.getCentroId(centros.Text);
                admin.crearRol(descripcion_TB.Text, persAdded, centro);

                Page.ClientScript.RegisterStartupScript(Page.GetType(), "alert", "alert('Rol Guardado')", true);
                LimpiarPage();
            }
        }
        catch (Exception err)
        {
            Session["Error_Msg"] = err.Message;
            Response.Redirect("~/Error.aspx", true);
        }
    }
Example #24
0
		/// <summary>
		/// To create from <see cref="Decimal"/> the points values.
		/// </summary>
		/// <param name="value"><see cref="Decimal"/> value.</param>
		/// <param name="security">The instrument from which information about the price increment cost is taken .</param>
		/// <returns>Points.</returns>
		public static Unit Points(this decimal value, Security security)
		{
			if (security == null)
				throw new ArgumentNullException("security");

			return new Unit(value, UnitTypes.Point, type => GetTypeValue(security, type));
		}
        /********************************************************
        * CLASS PROPERTIES
        *********************************************************/
        /********************************************************
        * CLASS METHODS
        *********************************************************/
        /// <summary>
        /// Perform neccessary check to see if the model has been filled, appoximate the best we can.
        /// </summary>
        /// <param name="vehicle">Asset we're working with</param>
        /// <param name="order">Order class to check if filled.</param>
        /// <returns>OrderEvent packet with the full or partial fill information</returns>
        /// <seealso cref="OrderEvent"/>
        /// <seealso cref="Order"/>
        public virtual OrderEvent Fill(Security vehicle, Order order)
        {
            var fill = new OrderEvent(order);

            try
            {
                switch (order.Type)
                {
                    case OrderType.Limit:
                        fill = LimitFill(vehicle, order);
                        break;
                    case OrderType.StopMarket:
                        fill = StopFill(vehicle, order);
                        break;
                    case OrderType.Market:
                        fill = MarketFill(vehicle, order);
                        break;
                }
            }
            catch (Exception err)
            {
                Log.Error("Forex.ForexTransactionModel.Fill(): " + err.Message);
            }
            return fill;
        }
 public bool ProcessSecurity(Security data)
 {
     // See FR5 for more info
     if (EnableThirdPartyDelay)
         Thread.Sleep(ProcessDelayInMilliseconds);
     return true;
 }
Example #27
0
    private System.Collections.IEnumerator doLogin(LoginServerCall lsc)
    {
        Debug.Log("starting login" + calls.Count);
          		string url = serverUrl+"login/"+lsc.getId()+"/" + lsc.getDeviceType()+"/MSW"+"/" +lsc.getVersion();

        Debug.Log(url);
        WWW www = new WWW(url);
          		yield return www;
          		Debug.Log("after yield");
        try {
        if (www.error == null) {
            online = true;
            //no error occured
            Debug.Log (www.text);
            Response response = Response.DeserializeObject(www.text);
            //login.debug();
            security = response.security;
            login = response.login;
            content = response.content;
            lsc.processCallback(response);
        } else {
            Debug.Log("ERROR: " + www.error);
            setOffline();
            calls.Add(lsc);

        }
          		www.Dispose();
          		www = null;
        } catch (Exception e) {
            Debug.Log("got an exception " + e.Message);
        }
        processing = false;
        Debug.Log("ending login"+ calls.Count);
    }
		public HistoryCandlesWindow(Security security)
		{
			if (security == null)
				throw new ArgumentNullException("security");

			_security = security;

			InitializeComponent();
			Title = _security.Code + LocalizedStrings.Str3747;

			TimeFramePicker.ItemsSource = new[]
			{
				TimeSpan.FromMinutes(1),
				TimeSpan.FromMinutes(5),
				TimeSpan.FromMinutes(15),
				TimeSpan.FromMinutes(60),
				TimeSpan.FromDays(1),
				TimeSpan.FromDays(7),
				TimeSpan.FromTicks(TimeHelper.TicksPerMonth)
			};
			TimeFramePicker.SelectedIndex = 1;

			DateFromPicker.Value = DateTime.Today.AddDays(-7);
			DateToPicker.Value = DateTime.Today;

			var area = new ChartArea();
			_candlesElem = new ChartCandleElement();
			area.Elements.Add(_candlesElem);

			Chart.Areas.Add(area);
		}
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="security">Used security level.</param>
 /// <param name="encrypt"></param>
 /// <param name="blockCipherKey"></param>
 /// <param name="aad"></param>
 /// <param name="iv"></param>
 /// <param name="tag"></param>
 public GXDLMSChipperingStream(Security security, bool encrypt, byte[] blockCipherKey, byte[] aad, byte[] iv, byte[] tag)
 {            
     this.Security = security;
     const int TagSize = 0x10;
     this.Tag = tag;
     if (this.Tag == null)//Tag size is 12 bytes.
     {
         this.Tag = new byte[12];
     }
     else if (this.Tag.Length != 12)
     {
         throw new ArgumentOutOfRangeException("Invalid tag.");
     }
     Encrypt = encrypt;
     WorkingKey = GenerateKey(true, blockCipherKey);
     int bufLength = Encrypt ? BlockSize : (BlockSize + TagSize);
     this.bufBlock = new byte[bufLength];
     Aad = aad;
     this.H = new byte[BlockSize];
     ProcessBlock(H, 0, H, 0);
     Init(H);
     this.J0 = new byte[16];
     Array.Copy(iv, 0, J0, 0, iv.Length);
     this.J0[15] = 0x01;
     this.S = GetGHash(Aad);
     this.counter = (byte[]) J0.Clone();
     this.BytesRemaining = 0;
     this.totalLength = 0;
 }
    protected void loginButton_Click( object sender , EventArgs e )
    {
        dbModule dm = new dbModule();
        pbModule pm = new pbModule();
        string uCode = ucodeTextbox.Text.Trim();
        string uPass = upassTextbox.Text.Trim();
        if ( !pm.isValidString( uCode) || !pm.isValidString( uPass ) )
        {
            errors.Text = Resources.Resource.strNotValidString;
            return;
        }
        int result = dm.adminLogin( uCode , uPass );
        switch ( result )
        {
            case -1 :
                errors.Text = Resources.Resource.strWrongPasswordString;
                break;
            case 0:
                errors.Text = Resources.Resource.strWrongUsernameString;
                break;
            case 1:

                Security s = new Security();
                s.setSecurity( priCode.xtgly );
                s.setUserCode(ucodeTextbox.Text.Trim());
                s.setUserName( dm.getUnameByUcode(uCode, priCode.xtgly ) );
                Session["sec"] = s;
                Session["usercode"] = s.getUserCode();
                Response.Redirect( "adminDefault.aspx" );
                break;
            default:
                errors.Text = Resources.Resource.strDuplicateUserNameString;
                break;
        }
    }
Example #31
0
 /// <summary>
 /// Создать <see cref="CandleSeries"/> для свечек <see cref="RenkoCandle"/>.
 /// </summary>
 /// <param name="security">Инструмент.</param>
 /// <param name="arg">Значение <see cref="RenkoCandle.BoxSize"/>.</param>
 /// <returns>Серия свечек.</returns>
 public static CandleSeries Renko(this Security security, Unit arg)
 {
     return(new CandleSeries(typeof(RenkoCandle), security, arg));
 }
Example #32
0
 private void RaiseSecurityChanged(Security security)
 {
     SecurityChanged?.Invoke(security);
     SecuritiesChanged?.Invoke(new[] { security });
 }
Example #33
0
 /// <summary>
 /// Сохранить исполнения в хранилище.
 /// </summary>
 /// <param name="security">Инструмент.</param>
 /// <param name="executions">Исполнения.</param>
 protected void SaveExecutions(Security security, IEnumerable <ExecutionMessage> executions)
 {
     SafeSave(security, typeof(ExecutionMessage), ExecutionTypes.Order, executions, t => t.ServerTime, Enumerable.Empty <Func <ExecutionMessage, string> >());
 }
Example #34
0
 /// <summary>
 /// Сохранить лог заявок по инструменту в хранилище.
 /// </summary>
 /// <param name="security">Инструмент.</param>
 /// <param name="items">Лог заявок.</param>
 protected void SaveOrderLog(Security security, IEnumerable <OrderLogItem> items)
 {
     SafeSave(security, typeof(ExecutionMessage), ExecutionTypes.OrderLog, items,
              i => i.Order.Time, Enumerable.Empty <Func <OrderLogItem, string> >());
 }
Example #35
0
 private void SafeSave <T>(Security security, Type messageType, object arg, IEnumerable <T> values, Func <T, DateTimeOffset> getTime, IEnumerable <Func <T, string> > getErrors)
 {
     SafeSave(security, messageType, arg, values, getTime, getErrors, (s, d, f) => (IMarketDataStorage <T>)StorageRegistry.GetStorage(s, typeof(T), arg, d, f));
 }
 public MarketDataTradesRequestWrapper(int pMdReqId, Security pSecurity, SubscriptionRequestType pSubscriptionRequestType) : base(pMdReqId, pSecurity, pSubscriptionRequestType)
 {
 }
Example #37
0
 /// <inheritdoc />
 public MarketDepth GetMarketDepth(Security security)
 {
     return(MarketDataProvider.GetMarketDepth(security));
 }
Example #38
0
 /// <summary>
 /// Зарегистрирована ли группировка свечек по определённому признаку.
 /// </summary>
 /// <typeparam name="TCandle">Тип свечек.</typeparam>
 /// <param name="manager">Менеджер свечек.</param>
 /// <param name="security">Инструмент, для которого зарегистрирована группировка.</param>
 /// <param name="arg">Параметр свечи.</param>
 /// <returns><see langword="true"/>, если зарегистрирована. Иначе, <see langword="false"/>.</returns>
 public static bool IsCandlesRegistered <TCandle>(this ICandleManager manager, Security security, object arg)
     where TCandle : Candle
 {
     return(manager.GetSeries <TCandle>(security, arg) != null);
 }
Example #39
0
 /// <summary>
 /// Создать <see cref="CandleSeries"/> для свечек <see cref="VolumeCandle"/>.
 /// </summary>
 /// <param name="security">Инструмент.</param>
 /// <param name="arg">Значение <see cref="VolumeCandle.Volume"/>.</param>
 /// <returns>Серия свечек.</returns>
 public static CandleSeries Volume(this Security security, decimal arg)
 {
     return(new CandleSeries(typeof(VolumeCandle), security, arg));
 }
Example #40
0
 /// <summary>
 /// Создать <see cref="CandleSeries"/> для свечек <see cref="PnFCandle"/>.
 /// </summary>
 /// <param name="security">Инструмент.</param>
 /// <param name="arg">Значение <see cref="PnFCandle.PnFArg"/>.</param>
 /// <returns>Серия свечек.</returns>
 public static CandleSeries PnF(this Security security, PnFArg arg)
 {
     return(new CandleSeries(typeof(PnFCandle), security, arg));
 }
Example #41
0
 /// <summary>
 /// Получить серию свечек по заданным параметрам.
 /// </summary>
 /// <typeparam name="TCandle">Тип свечек.</typeparam>
 /// <param name="manager">Менеджер свечек.</param>
 /// <param name="security">Инструмент, по которому нужно фильтровать сделки для формирования свечек.</param>
 /// <param name="arg">Параметр свечи.</param>
 /// <returns>Серия свечек. Null, если такая серия не зарегистрирована.</returns>
 public static CandleSeries GetSeries <TCandle>(this ICandleManager manager, Security security, object arg)
     where TCandle : Candle
 {
     return(manager.ThrowIfNull().Series.FirstOrDefault(s => s.CandleType == typeof(TCandle) && s.Security == security && s.Arg.Equals(arg)));
 }
Example #42
0
 /// <summary>
 /// Создать <see cref="CandleSeries"/> для свечек <see cref="TickCandle"/>.
 /// </summary>
 /// <param name="security">Инструмент.</param>
 /// <param name="arg">Значение <see cref="TickCandle.MaxTradeCount"/>.</param>
 /// <returns>Серия свечек.</returns>
 public static CandleSeries Tick(this Security security, decimal arg)
 {
     return(new CandleSeries(typeof(TickCandle), security, arg));
 }
Example #43
0
        private static bool HandleOptionData(DateTime algorithmTime, BaseData baseData, OptionChains optionChains, Security security, Lazy <Slice> sliceFuture)
        {
            var symbol = baseData.Symbol;

            OptionChain chain;
            var         canonical = Symbol.CreateOption(symbol.Underlying, symbol.ID.Market, default(OptionStyle), default(OptionRight), 0, SecurityIdentifier.DefaultDate);

            if (!optionChains.TryGetValue(canonical, out chain))
            {
                chain = new OptionChain(canonical, algorithmTime);
                optionChains[canonical] = chain;
            }

            var universeData = baseData as OptionChainUniverseDataCollection;

            if (universeData != null)
            {
                if (universeData.Underlying != null)
                {
                    chain.Underlying = universeData.Underlying;

                    foreach (var addedContract in chain.Contracts)
                    {
                        addedContract.Value.UnderlyingLastPrice = chain.Underlying.Price;
                    }
                }
                foreach (var contractSymbol in universeData.FilteredContracts)
                {
                    chain.FilteredContracts.Add(contractSymbol);
                }
                return(false);
            }

            OptionContract contract;

            if (!chain.Contracts.TryGetValue(baseData.Symbol, out contract))
            {
                var underlyingSymbol = baseData.Symbol.Underlying;
                contract = new OptionContract(baseData.Symbol, underlyingSymbol)
                {
                    Time                = baseData.EndTime,
                    LastPrice           = security.Close,
                    BidPrice            = security.BidPrice,
                    BidSize             = (long)security.BidSize,
                    AskPrice            = security.AskPrice,
                    AskSize             = (long)security.AskSize,
                    OpenInterest        = security.OpenInterest,
                    UnderlyingLastPrice = chain.Underlying.Price
                };

                chain.Contracts[baseData.Symbol] = contract;
                var option = security as Option;
                if (option != null)
                {
                    contract.SetOptionPriceModel(() => option.PriceModel.Evaluate(option, sliceFuture.Value, contract));
                }
            }

            // populate ticks and tradebars dictionaries with no aux data
            switch (baseData.DataType)
            {
            case MarketDataType.Tick:
                var tick = (Tick)baseData;
                chain.Ticks.Add(tick.Symbol, tick);
                UpdateContract(contract, tick);
                break;

            case MarketDataType.TradeBar:
                var tradeBar = (TradeBar)baseData;
                chain.TradeBars[symbol] = tradeBar;
                contract.LastPrice      = tradeBar.Close;
                break;

            case MarketDataType.QuoteBar:
                var quote = (QuoteBar)baseData;
                chain.QuoteBars[symbol] = quote;
                UpdateContract(contract, quote);
                break;

            case MarketDataType.Base:
                chain.AddAuxData(baseData);
                break;
            }
            return(true);
        }
Example #44
0
 /// <summary>
 /// Создать <see cref="CandleSeries"/> для свечек <see cref="TimeFrameCandle"/>.
 /// </summary>
 /// <param name="security">Инструмент.</param>
 /// <param name="arg">Значение <see cref="TimeFrameCandle.TimeFrame"/>.</param>
 /// <returns>Серия свечек.</returns>
 public static CandleSeries TimeFrame(this Security security, TimeSpan arg)
 {
     return(new CandleSeries(typeof(TimeFrameCandle), security, arg));
 }
Example #45
0
        /// <summary>
        /// The create users.
        /// </summary>
        /// <param name="boardID">
        /// The board id.
        /// </param>
        /// <param name="_users_Number">
        /// The _users_ number.
        /// </param>
        /// <param name="_outCounter">
        /// The _out counter.
        /// </param>
        /// <param name="_countLimit">
        /// The _count limit.
        /// </param>
        /// <param name="_excludeCurrentBoard">
        /// The _exclude current board.
        /// </param>
        /// <returns>
        /// The string with number of created users.
        /// </returns>
        private string CreateUsers(
            int boardID, int _users_Number, int _outCounter, int _countLimit, bool _excludeCurrentBoard)
        {
            int iboards;

            // if ( _users_Number > createCommonLimit ) _users_Number = createCommonLimit;
            for (iboards = 0; iboards < _countLimit; iboards++)
            {
                boardID = this.UsersBoardsList.Items[iboards].Value.ToType <int>();
                int i;
                for (i = 0; i < this.UsersNumber.Text.Trim().ToType <int>(); i++)
                {
                    this.randomGuid = Guid.NewGuid().ToString();
                    string newEmail    = this.UserPrefixTB.Text.Trim() + this.randomGuid + "@test.info";
                    string newUsername = this.UserPrefixTB.Text.Trim() + this.randomGuid;

                    if (UserMembershipHelper.UserExists(newUsername, newEmail))
                    {
                        continue;
                    }

                    string hashinput = DateTime.UtcNow + newEmail + Security.CreatePassword(20);
                    string hash      = FormsAuthentication.HashPasswordForStoringInConfigFile(hashinput, "md5");

                    MembershipCreateStatus status;
                    MembershipUser         user = this.Get <MembershipProvider>().CreateUser(
                        newUsername,
                        this.Password.Text.Trim(),
                        newEmail,
                        this.Question.Text.Trim(),
                        this.Answer.Text.Trim(),
                        !this.Get <YafBoardSettings>().EmailVerification,
                        null,
                        out status);

                    if (status != MembershipCreateStatus.Success)
                    {
                        continue;
                    }

                    // setup inital roles (if any) for this user
                    RoleMembershipHelper.SetupUserRoles(boardID, newUsername);

                    // create the user in the YAF DB as well as sync roles...
                    int?userID = RoleMembershipHelper.CreateForumUser(user, boardID);

                    // create profile
                    YafUserProfile userProfile = YafUserProfile.GetProfile(newUsername);

                    // setup their inital profile information
                    userProfile.Location = this.Location.Text.Trim();
                    userProfile.Homepage = this.HomePage.Text.Trim();
                    userProfile.Save();

                    // save the time zone...
                    if (
                        !(this.UsersBoardsList.Items[iboards].Value.ToType <int>() == YafContext.Current.PageBoardID &&
                          _excludeCurrentBoard))
                    {
                        LegacyDb.user_save(
                            LegacyDb.user_get(boardID, user.ProviderUserKey),
                            boardID,
                            null,
                            null,
                            null,
                            this.TimeZones.SelectedValue.ToType <int>(),
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null);
                        _outCounter++;
                    }
                }
            }

            return(_outCounter + " Users in " + iboards + " Board(s); ");
        }
Example #46
0
        private static bool HandleFuturesData(DateTime algorithmTime, BaseData baseData, FuturesChains futuresChains, Security security)
        {
            var symbol = baseData.Symbol;

            FuturesChain chain;
            var          canonical = Symbol.Create(symbol.ID.Symbol, SecurityType.Future, symbol.ID.Market);

            if (!futuresChains.TryGetValue(canonical, out chain))
            {
                chain = new FuturesChain(canonical, algorithmTime);
                futuresChains[canonical] = chain;
            }

            var universeData = baseData as FuturesChainUniverseDataCollection;

            if (universeData != null)
            {
                foreach (var contractSymbol in universeData.FilteredContracts)
                {
                    chain.FilteredContracts.Add(contractSymbol);
                }
                return(false);
            }

            FuturesContract contract;

            if (!chain.Contracts.TryGetValue(baseData.Symbol, out contract))
            {
                var underlyingSymbol = baseData.Symbol.Underlying;
                contract = new FuturesContract(baseData.Symbol, underlyingSymbol)
                {
                    Time         = baseData.EndTime,
                    LastPrice    = security.Close,
                    BidPrice     = security.BidPrice,
                    BidSize      = (long)security.BidSize,
                    AskPrice     = security.AskPrice,
                    AskSize      = (long)security.AskSize,
                    OpenInterest = security.OpenInterest
                };
                chain.Contracts[baseData.Symbol] = contract;
            }

            // populate ticks and tradebars dictionaries with no aux data
            switch (baseData.DataType)
            {
            case MarketDataType.Tick:
                var tick = (Tick)baseData;
                chain.Ticks.Add(tick.Symbol, tick);
                UpdateContract(contract, tick);
                break;

            case MarketDataType.TradeBar:
                var tradeBar = (TradeBar)baseData;
                chain.TradeBars[symbol] = tradeBar;
                contract.LastPrice      = tradeBar.Close;
                break;

            case MarketDataType.QuoteBar:
                var quote = (QuoteBar)baseData;
                chain.QuoteBars[symbol] = quote;
                UpdateContract(contract, quote);
                break;

            case MarketDataType.Base:
                chain.AddAuxData(baseData);
                break;
            }
            return(true);
        }
Example #47
0
        /// <summary>
        /// Creates a subscription to process the request
        /// </summary>
        private Subscription CreateSubscription(HistoryRequest request, DateTime start, DateTime end)
        {
            // data reader expects these values in local times
            start = start.ConvertFromUtc(request.ExchangeHours.TimeZone);
            end   = end.ConvertFromUtc(request.ExchangeHours.TimeZone);

            var config = new SubscriptionDataConfig(request.DataType,
                                                    request.Symbol,
                                                    request.Resolution,
                                                    request.TimeZone,
                                                    request.ExchangeHours.TimeZone,
                                                    request.FillForwardResolution.HasValue,
                                                    request.IncludeExtendedMarketHours,
                                                    false,
                                                    request.IsCustomData
                                                    );

            var security = new Security(request.ExchangeHours, config, 1.0m);

            IEnumerator <BaseData> reader = new SubscriptionDataReader(config,
                                                                       start,
                                                                       end,
                                                                       ResultHandlerStub.Instance,
                                                                       config.SecurityType == SecurityType.Equity ? _mapFileProvider.Get(config.Market) : MapFileResolver.Empty,
                                                                       _factorFileProvider,
                                                                       Time.EachTradeableDay(request.ExchangeHours, start, end),
                                                                       false,
                                                                       includeAuxilliaryData: false
                                                                       );

            // optionally apply fill forward behavior
            if (request.FillForwardResolution.HasValue)
            {
                var readOnlyRef = Ref.CreateReadOnly(() => request.FillForwardResolution.Value.ToTimeSpan());
                reader = new FillForwardEnumerator(reader, security.Exchange, readOnlyRef, security.IsExtendedMarketHours, end, config.Increment);
            }

            // since the SubscriptionDataReader performs an any overlap condition on the trade bar's entire
            // range (time->end time) we can end up passing the incorrect data (too far past, possibly future),
            // so to combat this we deliberately filter the results from the data reader to fix these cases
            // which only apply to non-tick data

            reader = new SubscriptionFilterEnumerator(reader, security, end);
            reader = new FilterEnumerator <BaseData>(reader, data =>
            {
                // allow all ticks
                if (config.Resolution == Resolution.Tick)
                {
                    return(true);
                }
                // filter out future data
                if (data.EndTime > end)
                {
                    return(false);
                }
                // filter out data before the start
                return(data.EndTime > start);
            });

            var timeZoneOffsetProvider = new TimeZoneOffsetProvider(security.Exchange.TimeZone, start, end);

            return(new Subscription(null, security, reader, timeZoneOffsetProvider, start, end, false));
        }
 /// <summary>
 /// subscribe
 /// подписаться
 /// </summary>
 public void Subscrible(Security security)
 {
     _client.SubscribleTradesAndDepths(security);
 }
 void ISecurityStorage.Save(Security security)
 {
     _entityRegistry.Securities.Save(security);
     TryAddToCache(security);
 }
        ///// <summary>
        ///// 更新用户
        ///// </summary>
        ///// <param name="model"></param>
        ///// <returns></returns>
        internal bool Update(OMS_SysUserInfo model)
        {
            SqlParameter[] parms =
            {
                new SqlParameter("@Id",         model.Id),
                new SqlParameter("@FullName",   model.FullName),
                new SqlParameter("@Sex",        model.Sex),
                new SqlParameter("@LoginName",  model.LoginName),
                new SqlParameter("@LoginPwd",   string.IsNullOrEmpty(model.LoginPwd)?model.LoginPwd:Security.MD5_Encrypt(model.LoginPwd)),
                new SqlParameter("@BranchId",   model.BranchId),
                new SqlParameter("@BumenId",    model.BumenId),
                new SqlParameter("@PositionId", model.PositionId),
                new SqlParameter("@Status",     model.Status),
                new SqlParameter("@RoleIds",    model.RoleIds)
            };

            StringBuilder sql = new StringBuilder();

            sql.AppendFormat("update {0} set ", TableName);
            sql.Append("FullName=@FullName,");
            sql.Append("Sex=@Sex,");
            sql.Append("LoginName=@LoginName,");
            if (model.LoginPwd != null)
            {
                sql.Append("LoginPwd=@LoginPwd,");
            }
            sql.Append("BranchId=@BranchId,");
            sql.Append("BumenId=@BumenId,");
            sql.Append("PositionId=@PositionId,");
            sql.Append("Status=@Status,");
            sql.Append("RoleIds=@RoleIds");

            sql.Append(" where Id=@Id");

            int rows = DbHelper.ExecuteNonQueryText(sql.ToString(), parms);

            return(rows > 0 ? true : false);
        }
Example #51
0
 public async Task ChangePassword(string id, string newPassword)
 {
     (var hash, var salt) = Security.CreatePasswordHash(newPassword);
     await userRepository.UpdatePassword(id, hash, salt);
 }
Example #52
0
        private void InvStoreDataGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (StoreDG.Columns[e.ColumnIndex].Name == "EditEnd")
            {
                return;
            }

            string InvNotes = string.Empty;
            int    StoreID  = 0;

            if (StoreDG.SelectedRows.Count != 0 && StoreDG.SelectedRows[0].Cells["InvNotes"].Value != DBNull.Value)
            {
                InvNotes = StoreDG.SelectedRows[0].Cells["InvNotes"].Value.ToString();
            }
            if (StoreDG.SelectedRows.Count != 0 && StoreDG.SelectedRows[0].Cells["PersonalStoreID"].Value != DBNull.Value)
            {
                StoreID = Convert.ToInt32(StoreDG.SelectedRows[0].Cells["PersonalStoreID"].Value);
            }

            decimal CurrentCount = InventoryManager.PlaningEndCount(StoreID);

            //if (CurrentCount < 1)
            //    return;

            PhantomForm PhantomForm = new Infinium.PhantomForm();

            PhantomForm.Show();

            AddInventoryRestForm = new AddInventoryRestForm(CurrentCount, InvNotes);

            TopForm = AddInventoryRestForm;
            AddInventoryRestForm.ShowDialog();
            TopForm = null;

            PhantomForm.Close();

            PhantomForm.Dispose();

            if (AddInventoryRestForm.IsOKPress)
            {
                int     InventoryID = InventoryManager.CurrentInventoryID;
                int     UserID      = Security.CurrentUserID;
                decimal FactCount   = AddInventoryRestForm.FactCount;
                string  Notes       = AddInventoryRestForm.Notes;

                AddInventoryRestForm.Dispose();
                AddInventoryRestForm = null;
                GC.Collect();

                InventoryManager.AddInventoryDetail(Security.GetCurrentDate(), InventoryID, StoreID, CurrentCount, FactCount, UserID, Notes);
                InventoryManager.ChangeCurrentFields(FactCount, Notes);
                InventoryManager.InventaryEndEdit(true);
                CheckStoreColumns(ref StoreDG);
            }
            else
            {
                AddInventoryRestForm.Dispose();
                AddInventoryRestForm = null;
                GC.Collect();
            }
        }
Example #53
0
 /// <inheritdoc />
 public void RegisterOrderLog(Security security, DateTimeOffset?from = null, DateTimeOffset?to = null, long?count = null)
 {
     SubscribeMarketData(security, MarketDataTypes.OrderLog, from, to, count);
 }
 object ISecurityProvider.GetNativeId(Security security)
 {
     return(_cacheByMfdId.SyncGet(d => d.FirstOrDefault(p => p.Value == security).Key));
 }
Example #55
0
 /// <inheritdoc />
 public void RegisterTrades(Security security, DateTimeOffset?from = null, DateTimeOffset?to = null, long?count = null, MarketDataBuildModes buildMode = MarketDataBuildModes.LoadAndBuild, MarketDataTypes?buildFrom = null)
 {
     SubscribeMarketData(security, MarketDataTypes.Trades, from, to, count, buildMode, buildFrom);
 }
Example #56
0
 /// <inheritdoc />
 public void UnRegisterOrderLog(Security security)
 {
     UnSubscribeMarketData(security, MarketDataTypes.OrderLog);
 }
Example #57
0
 /// <inheritdoc />
 public void UnRegisterMarketDepth(Security security)
 {
     UnSubscribeMarketData(security, MarketDataTypes.MarketDepth);
 }
Example #58
0
 /// <inheritdoc />
 public void UnRegisterTrades(Security security)
 {
     UnSubscribeMarketData(security, MarketDataTypes.Trades);
 }
Example #59
0
 /// <inheritdoc />
 public void RegisterMarketDepth(Security security, DateTimeOffset?from = null, DateTimeOffset?to = null, long?count = null, MarketDataBuildModes buildMode = MarketDataBuildModes.LoadAndBuild, MarketDataTypes?buildFrom = null, int?maxDepth = null)
 {
     SubscribeMarketData(security, MarketDataTypes.MarketDepth, from, to, count, buildMode, buildFrom, null, maxDepth);
 }
Example #60
0
 /// <inheritdoc />
 public void UnRegisterFilteredMarketDepth(Security security)
 {
     UnSubscribeMarketData(security, FilteredMarketDepthAdapter.FilteredMarketDepth);
 }