System.Convert.ToDouble(System.DateTime)

Here are the examples of the csharp api System.Convert.ToDouble(System.DateTime) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1083 Examples 7

19 View Source File : KrakenApi.cs
License : Apache License 2.0
Project Creator : AlexWan

private static void Client_BookSnapshotReceived(object sender, Events.KrakenDataEventArgs<BookSnapshotMessage> e)
        {
            string pair = e.Pair.ToString();

            Sec security = Securities.Find(sec => sec.NameInSocket == pair);

            MarketDepth depth = _marketDepths.Find(d => d.SecurityNameCode == security.NameInRest);

            if (depth == null)
            {
                depth = new MarketDepth();
                depth.SecurityNameCode = security.NameInRest;
                _marketDepths.Add(depth);
            }

            for (int i = 0; e.DataMessage.Asks != null && i < e.DataMessage.Asks.Length; i++)
            {
                OsEngine.Enreplacedy.MarketDepthLevel ask = new OsEngine.Enreplacedy.MarketDepthLevel();
                ask.Price = e.DataMessage.Asks[i].Price;
                ask.Ask = e.DataMessage.Asks[i].Volume;

                for (int i2 = 0; i2 < depth.Asks.Count; i2++)
                {
                    if (depth.Asks[i2].Price == ask.Price)
                    {
                        depth.Asks.RemoveAt(i2);
                        break;
                    }
                }

                if (ask.Ask != 0)
                {
                    depth.Asks.Add(ask);
                }

                depth.Time = new DateTime(1970, 1, 1).AddSeconds(Convert.ToDouble(e.DataMessage.Asks[i].Timestamp));
            }

            for (int i = 0; e.DataMessage.Bids != null && i < e.DataMessage.Bids.Length; i++)
            {
                OsEngine.Enreplacedy.MarketDepthLevel bid = new OsEngine.Enreplacedy.MarketDepthLevel();
                bid.Price = e.DataMessage.Bids[i].Price;
                bid.Bid = e.DataMessage.Bids[i].Volume;

                for (int i2 = 0; i2 < depth.Bids.Count; i2++)
                {
                    if (depth.Bids[i2].Price == bid.Price)
                    {
                        depth.Bids.RemoveAt(i2);
                        break;
                    }
                }

                if (bid.Bid != 0)
                {
                    depth.Bids.Add(bid);
                }

                depth.Time = new DateTime(1970, 1, 1).AddSeconds(Convert.ToDouble(e.DataMessage.Bids[i].Timestamp));
            }

            // 1 Теперь сортируем биды и аски

            for (int i = 0; i < depth.Asks.Count; i++)
            {
                for (int i2 = 0; i2 < depth.Asks.Count - 1; i2++)
                {
                    if (depth.Asks[i2].Price > depth.Asks[i2 + 1].Price)
                    {
                        MarketDepthLevel level = depth.Asks[i2];
                        depth.Asks[i2] = depth.Asks[i2 + 1];
                        depth.Asks[i2 + 1] = level;
                    }
                }
            }


            for (int i = 0; i < depth.Bids.Count; i++)
            {
                for (int i2 = 0; i2 < depth.Bids.Count - 1; i2++)
                {
                    if (depth.Bids[i2].Price < depth.Bids[i2 + 1].Price)
                    {
                        MarketDepthLevel level = depth.Bids[i2];
                        depth.Bids[i2] = depth.Bids[i2 + 1];
                        depth.Bids[i2 + 1] = level;
                    }
                }
            }

            // 2 Теперь удаляем перехлёсты


            while (depth.Bids.Count > 0 &&
                depth.Asks.Count > 0 &&
                depth.Bids[0].Price > depth.Asks[0].Price)
            {
                depth.Asks.RemoveAt(0);
            }

            // !!!!!!!!!!!!!!!!!!!!!!


            // высылаем копию

            if (MarketDepthUpdateEvent != null)
            {
                MarketDepthUpdateEvent(depth.GetCopy());
            }
        }

19 View Source File : Cable.cs
License : Apache License 2.0
Project Creator : Algoryx

private void OnPropertyValueUpdate( CableProperties.Direction dir )
    {
      if ( Native != null ) {
        Native.getCableProperties().setYoungsModulus( Convert.ToDouble( Properties[ dir ].YoungsModulus ), CableProperties.ToNative( dir ) );
        Native.getCableProperties().setDamping( Convert.ToDouble( Properties[ dir ].Damping ), CableProperties.ToNative( dir ) );
        Native.getCableProperties().setPoissonsRatio( Convert.ToDouble( Properties[ dir ].PoissonsRatio ), CableProperties.ToNative( dir ) );

        var plasticityComponent = Native.getCablePlasticity();
        if ( plasticityComponent != null )
          plasticityComponent.setYieldPoint( Convert.ToDouble( Properties[ dir ].YieldPoint ), CableProperties.ToNative( dir ) );
      }
    }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj

private void mnuCheckForUpdates_Click(object sender, EventArgs e)
        {
            System.Threading.Tasks.Task<IReadOnlyList<Octokit.Release>> releases;
            Octokit.Release latest = null;

            ProgressDialog progressDownload = new ProgressDialog();

            Thread thread = new Thread(() =>
            {
                Octokit.GitHubClient client = new Octokit.GitHubClient(new Octokit.ProductHeaderValue("alexgracianoarj"));
                releases = client.Repository.Release.GetAll("alexgracianoarj", "nclreplaced");
                latest = releases.Result[0];

                if (progressDownload.InvokeRequired)
                    progressDownload.BeginInvoke(new Action(() => progressDownload.Close()));
            });

            thread.Start();

            progressDownload.Text = "Update";
            progressDownload.lblPleaseWait.Text = "Checking...";
            progressDownload.SetIndeterminate(true);

            progressDownload.ShowDialog();

            double latestVersion = Convert.ToDouble(latest.TagName.Replace("v", ""), System.Globalization.CultureInfo.InvariantCulture);
            double programVersion = Convert.ToDouble(Program.CurrentVersion.ToString(2), System.Globalization.CultureInfo.InvariantCulture);

            if (latestVersion > programVersion)
            {
                if (MessageBox.Show("There is a new version of NClreplaced.\n\nDo you want download the new version and install it now?", "NClreplaced", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
                {
                    thread = new Thread(() =>
                    {
                        WebClient wc = new WebClient();

                        wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sen, env) =>
                        {
                            double bytesIn = double.Parse(env.BytesReceived.ToString());
                            double totalBytes = double.Parse(env.TotalBytesToReceive.ToString());
                            double percentage = bytesIn / totalBytes * 100;

                            if (progressDownload.InvokeRequired)
                                progressDownload.BeginInvoke(new Action(() => progressDownload.SetIndeterminate(false)));

                            if (progressDownload.InvokeRequired)
                                progressDownload.BeginInvoke(new Action(() => progressDownload.lblPleaseWait.Text = "Downloaded " + Convert.ToInt32(percentage) + "% - " + (env.BytesReceived / 1024) + " KB of " + (env.TotalBytesToReceive / 1024) + " KB"));

                            if (progressDownload.InvokeRequired)
                                progressDownload.BeginInvoke(new Action(() => progressDownload.progressBar1.Value = Convert.ToInt32(percentage)));

                        });

                        wc.DownloadFileCompleted += new AsyncCompletedEventHandler((sen, env) =>
                        {
                            // Close the dialog if it hasn't been already
                            if (progressDownload.InvokeRequired)
                                progressDownload.BeginInvoke(new Action(() => progressDownload.Close()));

                            System.Diagnostics.Process.Start(Path.GetTempPath() + "NClreplaced_Update.exe");

                            Application.Exit();
                        });

                        wc.DownloadFileAsync(new Uri(latest.replacedets[0].BrowserDownloadUrl), Path.GetTempPath() + "NClreplaced_Update.exe");
                    });

                    thread.Start();

                    progressDownload.lblPleaseWait.Text = "Downloading...";

                    progressDownload.ShowDialog();
                }
            }
            else
            {
                MessageBox.Show("NClreplaced is already updated.", "NClreplaced", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

19 View Source File : BitfinexClient.cs
License : Apache License 2.0
Project Creator : AlexWan

public void ExecuteOrder(Order order, bool isMarginTrading)
        {
            lock (_lockOrder)
            {
                try
                {
                    if (IsConnected == false)
                    {
                        return;
                    }

                    NewOrderPayload newOrder = new NewOrderPayload();

                    if (isMarginTrading == false && order.SecurityNameCode.Contains(":") == false)
                    {
                        newOrder.type = "exchange limit";
                    }
                    else// if (isMarginTrading)
                    {
                        newOrder.type = "limit";
                    }
                    
                    newOrder.exchange = "bitfinex";
                    newOrder.request = "/v1/order/new";
                    newOrder.side = order.Side == Side.Buy ? "buy" : "sell";
                    newOrder.price = order.Price.ToString(CultureInfo.InvariantCulture);
                    newOrder.amount = order.Volume.ToString(CultureInfo.InvariantCulture);
                    newOrder.symbol = order.SecurityNameCode;
                    newOrder.nonce = GetNonce();

                    var jsonPayload = JsonConvert.SerializeObject(newOrder);

                    var res = CreateAuthQuery(_baseUrlV1, "/order/new", jsonPayload);

                    BitfinexResponseOrder newCreatedOrder;

                    if (res != null)
                    {
                        newCreatedOrder = JsonConvert.DeserializeObject<BitfinexResponseOrder>(res);

                        _osOrders.Add(newCreatedOrder.id.ToString(), order.NumberUser);

                        var newOsOrder = new Order();
                        newOsOrder.SecurityNameCode = newCreatedOrder.symbol;
                        newOsOrder.PortfolioNumber = newCreatedOrder.symbol.Substring(3);
                        newOsOrder.Side = newCreatedOrder.side == "buy" ? Side.Buy : Side.Sell;
                        newOsOrder.NumberMarket = newCreatedOrder.order_id.ToString();
                        newOsOrder.NumberUser = order.NumberUser;
                        newOsOrder.ServerType = ServerType.Bitfinex;
                        newOsOrder.Price = newCreatedOrder.price.ToDecimal();
                        newOsOrder.Volume = newCreatedOrder.original_amount.ToDecimal();
                        newOsOrder.VolumeExecute = newCreatedOrder.executed_amount.ToDecimal();

                        newOsOrder.TimeCallBack = new DateTime(1970, 1, 1) + TimeSpan.FromSeconds(Math.Round(Convert.ToDouble(newCreatedOrder.timestamp.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture)));

                        newOsOrder.State = OrderStateType.Activ;

                        if (MyOrderEvent != null)
                        {
                            MyOrderEvent(newOsOrder);
                        }
                    }
                    else
                    {
                         order.State = OrderStateType.Fail;
                         if (MyOrderEvent != null)
                         {
                             MyOrderEvent(order);
                         }
                    }
                }
                catch (Exception ex)
                {
                    SendLogMessage(ex.ToString(), LogMessageType.Error);
                }
            }
        }

19 View Source File : ScatterSeries.cs
License : MIT License
Project Creator : AlexGyver

protected internal override void UpdateData()
        {
            if (this.ItemsSource == null)
            {
                return;
            }

            var points = this.Points;
            points.Clear();

            // Use the mapping to generate the points
            if (this.Mapping != null)
            {
                foreach (var item in this.ItemsSource)
                {
                    points.Add(this.Mapping(item));
                }

                return;
            }

            // Get DataPoints from the items in ItemsSource
            // if they implement IScatterPointProvider
            // If DataFields are set, this is not used
            /*if (DataFieldX == null || DataFieldY == null)
            {
                foreach (var item in ItemsSource)
                {
                    var idpp = item as IScatterPointProvider;
                    if (idpp == null)
                    {
                        continue;
                    }

                    points.Add(idpp.GetScatterPoint());
                }

                return;
            }*/

            var dest = new List<IDataPoint>();

            // Using reflection to add points
            var filler = new ListFiller<ScatterPoint>();
            filler.Add(this.DataFieldX, (item, value) => item.X = Convert.ToDouble(value));
            filler.Add(this.DataFieldY, (item, value) => item.Y = Convert.ToDouble(value));
            filler.Add(this.DataFieldSize, (item, value) => item.Size = Convert.ToDouble(value));
            filler.Add(this.DataFieldValue, (item, value) => item.Value = Convert.ToDouble(value));
            filler.Add(this.DataFieldTag, (item, value) => item.Tag = value);
            filler.Fill(dest, this.ItemsSource);

            this.Points = dest;
        }

19 View Source File : XmlNodeConverter.cs
License : MIT License
Project Creator : akaskela

private string ConvertTokenToXmlValue(JsonReader reader)
        {
            if (reader.TokenType == JsonToken.String)
            {
                return (reader.Value != null) ? reader.Value.ToString() : null;
            }
            else if (reader.TokenType == JsonToken.Integer)
            {
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
                if (reader.Value is BigInteger)
                {
                    return ((BigInteger)reader.Value).ToString(CultureInfo.InvariantCulture);
                }
#endif

                return XmlConvert.ToString(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture));
            }
            else if (reader.TokenType == JsonToken.Float)
            {
                if (reader.Value is decimal)
                {
                    return XmlConvert.ToString((decimal)reader.Value);
                }
                if (reader.Value is float)
                {
                    return XmlConvert.ToString((float)reader.Value);
                }

                return XmlConvert.ToString(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture));
            }
            else if (reader.TokenType == JsonToken.Boolean)
            {
                return XmlConvert.ToString(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture));
            }
            else if (reader.TokenType == JsonToken.Date)
            {
#if !NET20
                if (reader.Value is DateTimeOffset)
                {
                    return XmlConvert.ToString((DateTimeOffset)reader.Value);
                }
#endif

                DateTime d = Convert.ToDateTime(reader.Value, CultureInfo.InvariantCulture);
#if !PORTABLE
                return XmlConvert.ToString(d, DateTimeUtils.ToSerializationMode(d.Kind));
#else
                return XmlConvert.ToString(d);
#endif
            }
            else if (reader.TokenType == JsonToken.Null)
            {
                return null;
            }
            else
            {
                throw JsonSerializationException.Create(reader, "Cannot get an XML string value from token type '{0}'.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
            }
        }

19 View Source File : LivecoinServer.cs
License : Apache License 2.0
Project Creator : AlexWan

private void Client_NewTradesEvent(TradeNotification newTrade)
        {
            foreach (var t in newTrade.Datas)
            {
                OsEngine.Enreplacedy.Trade trade = new OsEngine.Enreplacedy.Trade();
                trade.SecurityNameCode = newTrade.CurrencyPair;

                trade.Id = t.Id.ToString();
                trade.Price =
                   Convert.ToDecimal(
                       t.Price.Replace(".", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator),
                       CultureInfo.InvariantCulture);
                trade.Time = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(t.Timestamp));
                trade.Volume =
                    Convert.ToDecimal(
                        t.Quanreplacedy.Replace(".", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator),
                        CultureInfo.InvariantCulture);
                trade.Side = t.trade_type == TradeEvent.TradeType.Sell ? Side.Sell : Side.Buy;

                if (NewTradesEvent != null)
                {
                    NewTradesEvent(trade);
                }
            }

        }

19 View Source File : CharacterCounter.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

public void Evaluate()
        {
            counterField.SetOutput(Convert.ToDouble(counterField.GetInput<string>().Length));
        }

19 View Source File : ModData.cs
License : MIT License
Project Creator : amazingalek

private bool TryUpdate(string key, object userSetting, object modSetting)
		{
			var userValue = Config.GetSettingsValue<object>(key);
			if (userValue is JValue userJValue)
			{
				userValue = userJValue.Value;
			}
			Config.Settings[key] = modSetting;

			if (IsNumber(userSetting) && IsNumber(modSetting))
			{
				Config.SetSettingsValue(key, Convert.ToDouble(userValue));
				return true;
			}

			if (IsBoolean(userSetting) && IsBoolean(modSetting))
			{
				Config.SetSettingsValue(key, Convert.ToBoolean(userValue));
				return true;
			}
			return false;
		}

19 View Source File : ReflectionEntityAttributeUpdate.cs
License : MIT License
Project Creator : Adoxio

protected object GetValue(JToken token, Type propertyType)
		{
			var value = token.ToObject<object>();

			if (value == null)
			{
				return null;
			}

			if (propertyType == typeof(bool?))
			{
				return Convert.ToBoolean(value);
			}

			if (propertyType == typeof(CrmEnreplacedyReference))
			{
				EnreplacedyReference enreplacedyReference;

				if (TryGetEnreplacedyReference(value, out enreplacedyReference))
				{
					return new CrmEnreplacedyReference(enreplacedyReference.LogicalName, enreplacedyReference.Id);
				}

				throw new FormatException("Unable to convert value {0} for attribute {1} to {2}.".FormatWith(value, Attribute.CrmPropertyAttribute.LogicalName, typeof(EnreplacedyReference)));
			}

			if (propertyType == typeof(DateTime?))
			{
				var dateTimeValue = value is DateTime ? (DateTime)value : Convert.ToDateTime(value);

				return dateTimeValue.Kind == DateTimeKind.Utc ? dateTimeValue : dateTimeValue.ToUniversalTime();
			}

			if (propertyType == typeof(double?))
			{
				return Convert.ToDouble(value);
			}

			if (propertyType == typeof(decimal))
			{
				return Convert.ToDecimal(value);
			}

			if (propertyType == typeof(EnreplacedyReference))
			{
				EnreplacedyReference enreplacedyReference;

				if (TryGetEnreplacedyReference(value, out enreplacedyReference))
				{
					return enreplacedyReference;
				}

				throw new FormatException("Unable to convert value {0} for attribute {1} to {2}.".FormatWith(value, Attribute.CrmPropertyAttribute.LogicalName, typeof(EnreplacedyReference)));
			}

			if (propertyType == typeof(Guid?))
			{
				return value is Guid ? value : new Guid(value.ToString());
			}

			if (propertyType == typeof(int?))
			{
				return Convert.ToInt32(value);
			}

			if (propertyType == typeof(long?))
			{
				return Convert.ToInt64(value);
			}

			if (propertyType == typeof(string))
			{
				return value is string ? value : value.ToString();
			}

			if (propertyType.IsreplacedignableFrom(value.GetType()))
			{
				return value;
			}

			throw new InvalidOperationException("Unable to convert value of type".FormatWith(value.GetType(), propertyType, Attribute.CrmPropertyAttribute.LogicalName));
		}

19 View Source File : BinanceServerSpot.cs
License : Apache License 2.0
Project Creator : AlexWan

void _client_NewTradesEvent(TradeResponse trades)
        {
            lock (_newTradesLoker)
            {
                if (trades.data == null)
                {
                    return;
                }
                Trade trade = new Trade();
                trade.SecurityNameCode = trades.data.s;
                trade.Price =
                        trades.data.p.ToDecimal();
                trade.Id = trades.data.t.ToString();
                trade.Time = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(trades.data.T));
                trade.Volume =
                        trades.data.q.ToDecimal();
                trade.Side = trades.data.m == true ? Side.Sell : Side.Buy;

                NewTradesEvent?.Invoke(trade);
            }
        }

19 View Source File : TornadoBarSeries.cs
License : MIT License
Project Creator : AlexGyver

protected internal override void UpdateData()
        {
            if (this.ItemsSource != null)
            {
                this.Items.Clear();

                var filler = new ListFiller<TornadoBarItem>();
                filler.Add(this.MinimumField, (item, value) => item.Minimum = Convert.ToDouble(value));
                filler.Add(this.MaximumField, (item, value) => item.Maximum = Convert.ToDouble(value));
                filler.FillT(this.Items, this.ItemsSource);
            }
        }

19 View Source File : BsonBinaryWriter.cs
License : MIT License
Project Creator : akaskela

private void WriteTokenInternal(BsonToken t)
        {
            switch (t.Type)
            {
                case BsonType.Object:
                {
                    BsonObject value = (BsonObject)t;
                    _writer.Write(value.CalculatedSize);
                    foreach (BsonProperty property in value)
                    {
                        _writer.Write((sbyte)property.Value.Type);
                        WriteString((string)property.Name.Value, property.Name.ByteCount, null);
                        WriteTokenInternal(property.Value);
                    }
                    _writer.Write((byte)0);
                }
                    break;
                case BsonType.Array:
                {
                    BsonArray value = (BsonArray)t;
                    _writer.Write(value.CalculatedSize);
                    ulong index = 0;
                    foreach (BsonToken c in value)
                    {
                        _writer.Write((sbyte)c.Type);
                        WriteString(index.ToString(CultureInfo.InvariantCulture), MathUtils.IntLength(index), null);
                        WriteTokenInternal(c);
                        index++;
                    }
                    _writer.Write((byte)0);
                }
                    break;
                case BsonType.Integer:
                {
                    BsonValue value = (BsonValue)t;
                    _writer.Write(Convert.ToInt32(value.Value, CultureInfo.InvariantCulture));
                }
                    break;
                case BsonType.Long:
                {
                    BsonValue value = (BsonValue)t;
                    _writer.Write(Convert.ToInt64(value.Value, CultureInfo.InvariantCulture));
                }
                    break;
                case BsonType.Number:
                {
                    BsonValue value = (BsonValue)t;
                    _writer.Write(Convert.ToDouble(value.Value, CultureInfo.InvariantCulture));
                }
                    break;
                case BsonType.String:
                {
                    BsonString value = (BsonString)t;
                    WriteString((string)value.Value, value.ByteCount, value.CalculatedSize - 4);
                }
                    break;
                case BsonType.Boolean:
                {
                    BsonValue value = (BsonValue)t;
                    _writer.Write((bool)value.Value);
                }
                    break;
                case BsonType.Null:
                case BsonType.Undefined:
                    break;
                case BsonType.Date:
                {
                    BsonValue value = (BsonValue)t;

                    long ticks = 0;

                    if (value.Value is DateTime)
                    {
                        DateTime dateTime = (DateTime)value.Value;
                        if (DateTimeKindHandling == DateTimeKind.Utc)
                        {
                            dateTime = dateTime.ToUniversalTime();
                        }
                        else if (DateTimeKindHandling == DateTimeKind.Local)
                        {
                            dateTime = dateTime.ToLocalTime();
                        }

                        ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(dateTime, false);
                    }
#if !NET20
                    else
                    {
                        DateTimeOffset dateTimeOffset = (DateTimeOffset)value.Value;
                        ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(dateTimeOffset.UtcDateTime, dateTimeOffset.Offset);
                    }
#endif

                    _writer.Write(ticks);
                }
                    break;
                case BsonType.Binary:
                {
                    BsonBinary value = (BsonBinary)t;

                    byte[] data = (byte[])value.Value;
                    _writer.Write(data.Length);
                    _writer.Write((byte)value.BinaryType);
                    _writer.Write(data);
                }
                    break;
                case BsonType.Oid:
                {
                    BsonValue value = (BsonValue)t;

                    byte[] data = (byte[])value.Value;
                    _writer.Write(data);
                }
                    break;
                case BsonType.Regex:
                {
                    BsonRegex value = (BsonRegex)t;

                    WriteString((string)value.Pattern.Value, value.Pattern.ByteCount, null);
                    WriteString((string)value.Options.Value, value.Options.ByteCount, null);
                }
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(t), "Unexpected token when writing BSON: {0}".FormatWith(CultureInfo.InvariantCulture, t.Type));
            }
        }

19 View Source File : BinanceServerFutures.cs
License : Apache License 2.0
Project Creator : AlexWan

void _client_NewTradesEvent(TradeResponse trades)
        {
            lock (_newTradesLoker)
            {
                if (trades.data == null)
                {
                    return;
                }
                Trade trade = new Trade();
                trade.SecurityNameCode = trades.stream.ToString().ToUpper().Split('@')[0];

                if (trade.SecurityNameCode != trades.data.s)
                {
                    return;
                }

                trade.Price =
                        trades.data.p.ToDecimal();
                trade.Id = trades.data.t.ToString();
                trade.Time = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(trades.data.T));
                trade.Volume =
                        trades.data.q.ToDecimal();
                trade.Side = trades.data.m == true ? Side.Sell : Side.Buy;

                NewTradesEvent?.Invoke(trade);            
            }
        }

public double GetField(int row, int column)
        {
            return Convert.ToDouble(Qparser.GetQField(column, row));
        }

19 View Source File : KrakenApi.cs
License : Apache License 2.0
Project Creator : AlexWan

private static void Client_TradeReceived(object sender, Events.KrakenDataEventArgs<TradeMessage> e)
        {
            string pair = e.Pair.ToString();

            Sec security = Securities.Find(sec => sec.NameInSocket == pair);

            for(int i = 0;i < e.DataMessage.Trades.Length;i++)
            {
                OsEngine.Enreplacedy.Trade trade = new OsEngine.Enreplacedy.Trade();
                trade.SecurityNameCode = security.NameInRest;
                trade.Price = e.DataMessage.Trades[i].Price;
                trade.Volume = e.DataMessage.Trades[i].Volume;
                trade.Time = new DateTime(1970, 1, 1).AddSeconds(Convert.ToDouble(e.DataMessage.Trades[i].Time));

                if (e.DataMessage.Trades[i].Side.ToLower() == "s")
                {
                    trade.Side = OsEngine.Enreplacedy.Side.Sell;
                }

                if(TradeUpdateEvent != null)
                {
                    TradeUpdateEvent(trade);
                }

            }
            //= (sender, e) => Console.WriteLine($"Trade received");
        }

19 View Source File : CheckDisplayPrices.cs
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick

private void checkDisplayPrice_run(float fMythicFactor, float fPackUncommon, float fPackRareMythic, float fRareCardsNotinPacks,
        float fMythicCardsNotinPacks, float fUncommonCardsNotinPacks, float fBoxContent, string editionID)
    {
      try
      {
        //used to determine index of best start edition
        //MessageBox.Show((editionBox.SelectedIndex.ToString()));

        var doc = MKMInteract.RequestHelper.GetExpansionsSingles(editionID);
        //would be easier if MKM would deliver detailed info with this call but ...

        MainView.Instance.LogMainWindow("====== Expansion Stats ======");

        //Multiplier 
        float fCardsInSet = doc.SelectNodes("response/single").Count;
        MainView.Instance.LogMainWindow("Cards in set: " + fCardsInSet);


        var xRares = doc.SelectNodes("response/single/rarity[. = \"Rare\"]");
        var xMythic = doc.SelectNodes("response/single/rarity[. = \"Mythic\"]");
        var xUncommon = doc.SelectNodes("response/single/rarity[. = \"Uncommon\"]");

        var iCountRares = xRares.Count - fRareCardsNotinPacks; //53F;
        var iCountMythics = xMythic.Count - fMythicCardsNotinPacks; //15F;
        var iCountUncommons = xUncommon.Count - fUncommonCardsNotinPacks; //80F;

        MainView.Instance.LogMainWindow("Rares in set: " + iCountRares);
        MainView.Instance.LogMainWindow("Mythic in set: " + iCountMythics);
        MainView.Instance.LogMainWindow("Uncommon in set: " + iCountUncommons);

        //factors per booster
        var fFactorUncommon = fPackUncommon / iCountUncommons; //0,0375
        var fFactorMythicRareCombined = fPackRareMythic / (iCountRares + iCountMythics); // 0,014
        var fFactorMythic = fFactorMythicRareCombined / fMythicFactor; //chance is 1:8 for Mythic
        var fFactorRare = fFactorMythicRareCombined / fMythicFactor * (fMythicFactor - 1);

        MainView.Instance.LogMainWindow("====== Calculated Booster Factors ======");
        MainView.Instance.LogMainWindow("Uncommon: " + fFactorUncommon);
        MainView.Instance.LogMainWindow("MR Combo: " + fFactorMythicRareCombined);
        MainView.Instance.LogMainWindow("Rare:" + fFactorRare);
        MainView.Instance.LogMainWindow("Mythic:" + fFactorMythic);

        var fFactorUncommonBox = fFactorUncommon * fBoxContent;
        var fFactorMythicRareCombinedBox = fFactorMythicRareCombined * fBoxContent;
        var fFactorMythicBox = fFactorMythic * fBoxContent;
        var fFactorRareBox = fFactorRare * fBoxContent;

        MainView.Instance.LogMainWindow("====== Calculated Box Factors ======");
        MainView.Instance.LogMainWindow("Uncommon: " + fFactorUncommonBox);
        MainView.Instance.LogMainWindow("MR Combo: " + fFactorMythicRareCombinedBox);
        MainView.Instance.LogMainWindow("Rare:" + fFactorRareBox);
        MainView.Instance.LogMainWindow("Mythic:" + fFactorMythicBox);

        xRares = doc.SelectNodes("response/single");

        float fBoxValue = 0;

        foreach (XmlNode xn in xRares)
        {
          if (xn["rarity"].InnerText == "Rare")
          {
            MainView.Instance.LogMainWindow("Checking (R): " + xn["enName"].InnerText);

            var doc2 =
                MKMInteract.RequestHelper.MakeRequest(
                    "https://api.cardmarket.com/ws/v2.0/products/" + xn["idProduct"].InnerText, "GET");

            if (doc2.HasChildNodes)
            {
              var fCardPrice =
                  (float)Convert.ToDouble(
                          doc2.SelectSingleNode("response/product/priceGuide/SELL").InnerText, CultureInfo.InvariantCulture);

              MainView.Instance.LogMainWindow("Current SELL Price: " + fCardPrice);

              fBoxValue += fCardPrice * fFactorMythicRareCombinedBox;
              //changed cause it's actually a rare + Mythic not rare or mythic I think?  was fFactorRareBox;
            }
          }

          if (xn["rarity"].InnerText == "Mythic")
          {
            MainView.Instance.LogMainWindow("Checking (M): " + xn["enName"].InnerText);

            var doc2 =
                MKMInteract.RequestHelper.MakeRequest(
                    "https://api.cardmarket.com/ws/v2.0/products/" + xn["idProduct"].InnerText, "GET");

            if (doc2.HasChildNodes)
            {
              var fCardPrice = Convert.ToSingle(
                doc2.SelectSingleNode("response/product/priceGuide/SELL").InnerText, CultureInfo.InvariantCulture);
              MainView.Instance.LogMainWindow("Current SELL Price: " + fCardPrice);

              fBoxValue += fCardPrice * fFactorMythicBox;
            }
          }

          if (xn["rarity"].InnerText == "Uncommon")
          {
            MainView.Instance.LogMainWindow("Checking (U): " + xn["enName"].InnerText);

            var doc2 =
                MKMInteract.RequestHelper.MakeRequest(
                    "https://api.cardmarket.com/ws/v2.0/products/" + xn["idProduct"].InnerText, "GET");

            if (doc2.HasChildNodes)
            {
              var fCardPrice =
                  (float)Convert.ToDouble(
                          doc2.SelectSingleNode("response/product/priceGuide/SELL").InnerText, CultureInfo.InvariantCulture);

              MainView.Instance.LogMainWindow("Current SELL Price: " + fCardPrice);

              fBoxValue += fCardPrice * fFactorUncommonBox;
            }
          }
        }
        MainView.Instance.LogMainWindow("Calculated Result *: " + fBoxValue);

        MainView.Instance.LogMainWindow(
            "* Estimated average booster box singles value at MKM SELL Pricing (EUR)\n");
      }
      catch (Exception eError)
      {
        MKMHelpers.LogError("checking display prices", eError.Message, true);
      }
    }

19 View Source File : LivecoinServer.cs
License : Apache License 2.0
Project Creator : AlexWan

private void Client_MyTradeEvent(string orderNumberParent, PrivateTradeEvent tradeInfo)
        {
            MyTrade myTrade = new MyTrade();
            myTrade.NumberTrade = tradeInfo.Id.ToString();
            myTrade.Price = ParseDecimal(tradeInfo.Price);
            myTrade.SecurityNameCode = tradeInfo.CurrencyPair;
            myTrade.Time = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(tradeInfo.Timestamp));
            myTrade.Side = tradeInfo.trade_type == PrivateTradeEvent.TradeType.Buy ? Side.Buy : Side.Sell;
            myTrade.NumberOrderParent = orderNumberParent;
            myTrade.Volume = ParseDecimal(tradeInfo.Quanreplacedy);

            MyTradeEvent?.Invoke(myTrade);
        }

19 View Source File : BaiduMap_main.cs
License : MIT License
Project Creator : 734843327

public void readJSON_Geocoding(WWW www)
    {
        placeInfo = new List<PlaceInfo>();
        string _name;
        string address;
        string addressInfo;
        string my_Json = www.text;
        Vector2d coordinate;
        JSONNode jsonData = JSON.Parse(my_Json);
        int num = jsonData["results"].Count;
        if (num > 5) { num = 5; }//最多只显示5个结果
        for (int i = 0; i < num;i++){
            _name = jsonData["results"][i]["name"];
            address=jsonData["results"][i]["address"];
            addressInfo = _name + "," + address;
            coordinate = new Vector2d(Convert.ToDouble(jsonData["results"][i]["location"]["lat"]), Convert.ToDouble(jsonData["results"][i]["location"]["lng"]));
            placeInfo.Add(new PlaceInfo(coordinate,addressInfo,i));
        }
        GameObject.Find("UserInput").SendMessage("GeocoderResponse",placeInfo);
        status = jsonData["status"];
    }

19 View Source File : Variable.cs
License : MIT License
Project Creator : AMalininHere

public double AsDouble()
        {
            EnsureIsOfType(VariableType.Double);
            return Convert.ToDouble(Value);
        }

19 View Source File : IntervalBarSeries.cs
License : MIT License
Project Creator : AlexGyver

protected internal override void UpdateData()
        {
            if (this.ItemsSource != null)
            {
                this.Items.Clear();

                var filler = new ListFiller<IntervalBarItem>();
                filler.Add(this.MinimumField, (item, value) => item.Start = Convert.ToDouble(value));
                filler.Add(this.MaximumField, (item, value) => item.End = Convert.ToDouble(value));
                filler.FillT(this.Items, this.ItemsSource);
            }
        }

19 View Source File : PieSeries.cs
License : MIT License
Project Creator : AlexGyver

protected internal override void UpdateData()
        {
            if (this.ItemsSource == null)
            {
                return;
            }

            this.slices.Clear();

            var filler = new ListFiller<PieSlice>();
            filler.Add(this.LabelField, (item, value) => item.Label = Convert.ToString(value));
            filler.Add(this.ValueField, (item, value) => item.Value = Convert.ToDouble(value));
            filler.Add(this.ColorField, (item, value) => item.Fill = (OxyColor)value);
            filler.Add(this.IsExplodedField, (item, value) => item.IsExploded = (bool)value);
            filler.FillT(this.slices, this.ItemsSource);
        }

19 View Source File : BaiduMap_main.cs
License : MIT License
Project Creator : 734843327

public void readJSON_Direction(WWW www)//处理路径规划结果:分解成若干个途经点。
    {
        string my_Json = www.text;
        JSONNode jsonData = JSON.Parse(my_Json);
        //Debug.Log(jsonData["result"]["routes"][0]["steps"].Count);
        //Debug.Log(jsonData["result"]["routes"][0]["steps"][1]["instructions"]);
        //Debug.Log(jsonData["result"]["routes"][0]["steps"][0]["path"]);
        //Debug.Log(jsonData["result"]["routes"][0]["steps"][1]["stepOriginLocation"]["lng"]);
        //results里包括routes和一些没用的东西,routes里包括steps和一些没用的东西
        //routes后面只能接[0],steps表示每个路段(不一定是直线!多为折线),接[i];path表示每个路段折线中的每一个顶点
        //我要的:每个steps的instruction(需翻译成汉字)、path(需分割并翻译成vector2d)、
        //                   stepOriginLocation和stepDestinationLocation(翻译成vector2d)
        routePointInfo = new List<RoutePointInfo>();
        int stepCount=jsonData["result"]["routes"][0]["steps"].Count;
        int pathCount;


        for (int i = 0; i < stepCount; i++)//对于每一个路段:
        {
            //pathCount = jsonData["result"]["routes"][0]["steps"][i]["path"].Count;
            //for (int j = 0; j < pathCount; j++) { }//上句和这句不行,path是一个长的字符串,没做处理
            string _instructionInfo = jsonData["result"]["routes"][0]["steps"][i]["instructions"];
            string pathInfo=jsonData["result"]["routes"][0]["steps"][i]["path"];//拿到path和instruction,准备处理成结构体
            string[] WholeString = pathInfo.Split(';');
            pathCount = WholeString.Length;

            double y_start = Convert.ToDouble(jsonData["result"]["routes"][0]["steps"][i]["stepOriginLocation"]["lng"]);
            double x_start = Convert.ToDouble(jsonData["result"]["routes"][0]["steps"][i]["stepOriginLocation"]["lat"]);
            double y_end = Convert.ToDouble(jsonData["result"]["routes"][0]["steps"][i]["stepDestinationLocation"]["lng"]);
            double x_end = Convert.ToDouble(jsonData["result"]["routes"][0]["steps"][i]["stepDestinationLocation"]["lat"]);
            routePointInfo.Add(new RoutePointInfo(new Vector2d(x_start,y_start), _instructionInfo, "Origin",i,-1));
            for (int j = 0; j < pathCount; j++) {//对于路段中的每一个顶点:
                string[] wholeCoodinate = WholeString[j].Split(',');
                double y = Convert.ToDouble(wholeCoodinate[0]);
                double x = Convert.ToDouble(wholeCoodinate[1]);
                Vector2d _coordinate =new Vector2d (x, y);
                routePointInfo.Add(new RoutePointInfo(_coordinate, _instructionInfo,"path",i,j));
                //Debug.Log(_coordinate.x + "," + _coordinate.y);
            }
            routePointInfo.Add(new RoutePointInfo(new Vector2d(x_end, y_end), _instructionInfo, "Destination",i,-2));
        }
        for(int i = 0; i < routePointInfo.Count; i++)
        {
            Debug.Log(routePointInfo[i].coordinate+"   "+routePointInfo[i].instructionInfo+"   "+routePointInfo[i].typeInfo);
        }
        isMapReady = true;
        GameTest.ith = 0;
    }

19 View Source File : ScatterSeries.cs
License : MIT License
Project Creator : AlexGyver

protected void AddScatterPoints(
            IList<ScatterPoint> dest,
            IEnumerable itemsSource,
            string dataFieldX,
            string dataFieldY,
            string dataFieldSize,
            string dataFieldValue,
            string dataFieldTag)
        {
            var filler = new ListFiller<ScatterPoint>();
            filler.Add(dataFieldX, (item, value) => item.X = Convert.ToDouble(value));
            filler.Add(dataFieldY, (item, value) => item.Y = Convert.ToDouble(value));
            filler.Add(dataFieldSize, (item, value) => item.Size = Convert.ToDouble(value));
            filler.Add(dataFieldValue, (item, value) => item.Value = Convert.ToDouble(value));
            filler.Add(dataFieldTag, (item, value) => item.Tag = value);
            filler.FillT(dest, itemsSource);
        }

19 View Source File : DoubleControlTemplate.cs
License : MIT License
Project Creator : Adoxio

protected override void InstantiateValidatorsIn(Control container)
		{
			var floatValidator = new CustomValidator
			{
				ID = string.Format("FloatValidator{0}", ControlID),
				ControlToValidate = ControlID,
				ValidationGroup = ValidationGroup,
				ErrorMessage = ValidationSummaryMarkup((string.IsNullOrWhiteSpace(Metadata.ValidationErrorMessage) ? (Metadata.Messages == null || !Metadata.Messages.ContainsKey("float")) ? ResourceManager.GetString("Invalid_Floating_Point_Value_Error").FormatWith(Metadata.Label) : Metadata.Messages["float"].FormatWith(Metadata.Label) : Metadata.ValidationErrorMessage)),
				Text = "*",
			};

			floatValidator.ServerValidate += OnDoubleFormatValidate;

			container.Controls.Add(floatValidator);

			var maxValue = Metadata.MaxValue.HasValue ? Convert.ToDouble(Metadata.MaxValue.Value) : double.MaxValue;
			var minValue = Metadata.MinValue.HasValue ? Convert.ToDouble(Metadata.MinValue.Value) : double.MinValue;

			var rangeValidator = new CustomValidator
			{
				ID = string.Format("RangeValidator{0}", ControlID),
				ControlToValidate = ControlID,
				ValidationGroup = ValidationGroup,
				ErrorMessage = ValidationSummaryMarkup((string.IsNullOrWhiteSpace(Metadata.RangeValidationErrorMessage) ? (Metadata.Messages == null || !Metadata.Messages.ContainsKey("range")) ? ResourceManager.GetString("Invalid_Range_Error").FormatWith(Metadata.Label, minValue.ToString("N{0}".FormatWith(Metadata.Precision.GetValueOrDefault(2))), maxValue.ToString("N{0}".FormatWith(Metadata.Precision.GetValueOrDefault(2)))) : Metadata.Messages["range"].FormatWith(Metadata.Label, minValue.ToString("N{0}".FormatWith(Metadata.Precision.GetValueOrDefault(2))), maxValue.ToString("N{0}".FormatWith(Metadata.Precision.GetValueOrDefault(2)))) : Metadata.RangeValidationErrorMessage)),
				Text = "*",
			};

			rangeValidator.ServerValidate += GetRangeValidationHandler(minValue, maxValue);

			container.Controls.Add(rangeValidator);

			if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired)
			{
				container.Controls.Add(new RequiredFieldValidator
				{
					ID = string.Format("RequiredFieldValidator{0}", ControlID),
					ControlToValidate = ControlID,
					ValidationGroup = ValidationGroup,
					Display = ValidatorDisplay,
					ErrorMessage = ValidationSummaryMarkup((string.IsNullOrWhiteSpace(Metadata.RequiredFieldValidationErrorMessage) ? (Metadata.Messages == null || !Metadata.Messages.ContainsKey("required")) ? ResourceManager.GetString("Required_Field_Error").FormatWith(Metadata.Label) : Metadata.Messages["required"].FormatWith(Metadata.Label) : Metadata.RequiredFieldValidationErrorMessage)),
					Text = ValidationText,
				});
			}

			if (!string.IsNullOrWhiteSpace(Metadata.ValidationRegularExpression))
			{
				container.Controls.Add(new RegularExpressionValidator
				{
					ID = string.Format("RegularExpressionValidator{0}", ControlID),
					ControlToValidate = ControlID,
					ValidationGroup = ValidationGroup,
					ErrorMessage = ValidationSummaryMarkup((string.IsNullOrWhiteSpace(Metadata.ValidationRegularExpressionErrorMessage) ? ResourceManager.GetString("Invalid_Error").FormatWith(Metadata.Label) : Metadata.ValidationRegularExpressionErrorMessage)),
					Text = "*",
					ValidationExpression = Metadata.ValidationRegularExpression
				});
			}

			this.InstantiateCustomValidatorsIn(container);
		}

19 View Source File : KalmanFilter.cs
License : Apache License 2.0
Project Creator : AlexWan

private decimal GetValue(List<Candle> candles, int index)
        {
            //Kalman[i]=Error+Velocity[i], where
            //Error=Kalman[i-1]+Distance*ShK,
            //Velocity[i]=Velocity[i-1]+Distance*K/100,
            //Distance=Price[i]-Kalman[i-1],
            //ShK=sqrt(Sharpness*K/100).

            if (index == 0)
            {
                _velocity.Add(0);
                return 0;
            }

            double shk = Math.Sqrt(Convert.ToDouble(Sharpness * K / 100));
            double distans = Convert.ToDouble(candles[index].Close - Values[index - 1]);

            if (index + 1 > _velocity.Count)
            {
                _velocity.Add(0);
            }

            _velocity[index] = _velocity[index - 1] + distans * Convert.ToDouble(K) / 100;

            double error = Convert.ToDouble(Values[index - 1]) + distans * shk;

            return Convert.ToDecimal(error + _velocity[index]);
        }

19 View Source File : KalmanFilter.cs
License : Apache License 2.0
Project Creator : AlexWan

private decimal GetValue(List<Candle> candles, int index)
        {
            //Kalman[i]=Error+Velocity[i], where
            //Error=Kalman[i-1]+Distance*ShK,
            //Velocity[i]=Velocity[i-1]+Distance*K/100,
            //Distance=Price[i]-Kalman[i-1],
            //ShK=sqrt(Sharpness*K/100).

            if (index == 0)
            {
                _velocity.Add(0);
                return 0;
            }

            double shk = Math.Sqrt(Convert.ToDouble(_sharpness.ValueDecimal * K.ValueDecimal / 100));
            double distans = Convert.ToDouble(candles[index].Close - _series.Values[index - 1]);

            if (index + 1 > _velocity.Count)
            {
                _velocity.Add(0);
            }

            _velocity[index] = _velocity[index - 1] + distans * Convert.ToDouble(K.ValueDecimal) / 100;

            double error = Convert.ToDouble(_series.Values[index - 1]) + distans * shk;

            return Convert.ToDecimal(error + _velocity[index]);
        }

19 View Source File : RatingBar.cs
License : GNU General Public License v3.0
Project Creator : aduskin

private void ValueChangedHanlder(object sender, ExecutedRoutedEventArgs e)
      {
         if (!this.IsReadOnly && e.Parameter is int)
         {
            this.Value = Convert.ToDouble(e.Parameter);
            this.mIsConfirm = true;
         }
      }

19 View Source File : BinanceServerFutures.cs
License : Apache License 2.0
Project Creator : AlexWan

void _client_UpdateMarketDepth(DepthResponseFutures myDepth)
        {
            try
            {
                lock (_depthLocker)
                {
                    if (_depths == null)
                    {
                        _depths = new List<MarketDepth>();
                    }

                    if (myDepth.data.a == null || myDepth.data.a.Count == 0 ||
                        myDepth.data.b == null || myDepth.data.b.Count == 0)
                    {
                        return;
                    }

                    var needDepth = _depths.Find(depth =>
                        depth.SecurityNameCode == myDepth.stream.Split('@')[0].ToUpper());

                    if (needDepth == null)
                    {
                        needDepth = new MarketDepth();
                        needDepth.SecurityNameCode = myDepth.stream.Split('@')[0].ToUpper();
                        _depths.Add(needDepth);
                    }

                    List<MarketDepthLevel> ascs = new List<MarketDepthLevel>();
                    List<MarketDepthLevel> bids = new List<MarketDepthLevel>();

                    for (int i = 0; i < myDepth.data.a.Count; i++)
                    {
                        ascs.Add(new MarketDepthLevel()
                        {
                            Ask =
                                myDepth.data.a[i][1].ToString().ToDecimal()
                            ,
                            Price =
                                myDepth.data.a[i][0].ToString().ToDecimal()

                        });
                    }

                    for (int i = 0; i < myDepth.data.b.Count; i++)
                    {
                        bids.Add(new MarketDepthLevel()
                        {
                            Bid =
                                myDepth.data.b[i][1].ToString().ToDecimal()
                            ,
                            Price =
                                myDepth.data.b[i][0].ToString().ToDecimal()
                        });
                    }

                    needDepth.Asks = ascs;
                    needDepth.Bids = bids;

                    needDepth.Time = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(myDepth.data.T));

                    if (needDepth.Time == DateTime.MinValue)
                    {
                        return;
                    }

                    if (MarketDepthEvent != null)
                    {
                        MarketDepthEvent(needDepth.GetCopy());
                    }
                }
            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
            }
        }

19 View Source File : SeriesAnimationCustomModifier.cs
License : MIT License
Project Creator : ABTSoftware

private void ScaleAnimation()
        {
            foreach (var s in ParentSurface.RenderableSeries)
            {
                if (s is BaseRenderableSeries series)
                {
                    var trans = new ScaleAnimation();
                    trans.Duration = TimeSpan.FromSeconds(5);
                    trans.AnimationDelay = TimeSpan.FromSeconds(1);
                    trans.EasingFunction = new BounceEase { Bounces = 2, EasingMode = EasingMode.EaseInOut, Bounciness = 3 };
                    if (s.DataSeries != null)
                    {
                        trans.ZeroLine = (Convert.ToDouble(series.DataSeries.YMax) +
                                          Convert.ToDouble(series.DataSeries.YMin)) / 2.0;
                    }

                    series.SeriesAnimation = trans;
                }
            }
        }

19 View Source File : KrakenApi.cs
License : Apache License 2.0
Project Creator : AlexWan

private static void Client_OwnTradesReceived(object sender, Events.KrakenPrivateEventArgs<OwnTradesMessage> e)
        {

            List<TradeObject> trades = e.PrivateMessage.Trades;

            for (int i = 0; i < trades.Count; i++)
            {
                TradeObject t = trades[i];

                OsEngine.Enreplacedy.MyTrade trade = new OsEngine.Enreplacedy.MyTrade();
                trade.NumberOrderParent = t.OrderTxId;
                trade.Price = t.Price;
                trade.NumberTrade = t.TradeId;
                string pair = t.Pair.ToString();

                Sec security = Securities.Find(sec => sec.NameInSocket == pair);

                if (security == null)
                {
                    return;
                }

                trade.SecurityNameCode = security.NameInRest;
                trade.Volume = t.Volume;
                DateTime time = new DateTime(1970, 1, 1).AddSeconds(Convert.ToDouble(t.Time));
                trade.Time = time;

                if (t.Type == "sell")
                {
                    trade.Side = OsEngine.Enreplacedy.Side.Sell;
                }
                else
                {
                    trade.Side = OsEngine.Enreplacedy.Side.Sell;
                }

                if (MyTradeUpdateEvent != null)
                {
                    MyTradeUpdateEvent(trade);
                }
            }


            //
            // = (sender, e) => Console.WriteLine($"OwnTrades received");
        }

19 View Source File : JsonValidatingReader.cs
License : MIT License
Project Creator : akaskela

private void ValidateFloat(JsonSchemaModel schema)
        {
            if (schema == null)
            {
                return;
            }

            if (!TestType(schema, JsonSchemaType.Float))
            {
                return;
            }

            ValidateNotDisallowed(schema);

            double value = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture);

            if (schema.Maximum != null)
            {
                if (value > schema.Maximum)
                {
                    RaiseError("Float {0} exceeds maximum value of {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Maximum), schema);
                }
                if (schema.ExclusiveMaximum && value == schema.Maximum)
                {
                    RaiseError("Float {0} equals maximum value of {1} and exclusive maximum is true.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Maximum), schema);
                }
            }

            if (schema.Minimum != null)
            {
                if (value < schema.Minimum)
                {
                    RaiseError("Float {0} is less than minimum value of {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Minimum), schema);
                }
                if (schema.ExclusiveMinimum && value == schema.Minimum)
                {
                    RaiseError("Float {0} equals minimum value of {1} and exclusive minimum is true.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Minimum), schema);
                }
            }

            if (schema.DivisibleBy != null)
            {
                double remainder = FloatingPointRemainder(value, schema.DivisibleBy.GetValueOrDefault());

                if (!IsZero(remainder))
                {
                    RaiseError("Float {0} is not evenly divisible by {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.DivisibleBy), schema);
                }
            }
        }

19 View Source File : KrakenApi.cs
License : Apache License 2.0
Project Creator : AlexWan

private static void Client_BookUpdateReceived(object sender, Events.KrakenDataEventArgs<BookUpdateMessage> e)
        {
            string pair = e.Pair.ToString();

            Sec security = Securities.Find(sec => sec.NameInSocket == pair);

            MarketDepth depth = _marketDepths.Find(d => d.SecurityNameCode == security.NameInRest);

            if (depth == null)
            {
                depth = new MarketDepth();
                depth.SecurityNameCode = security.NameInRest;
                _marketDepths.Add(depth);
            }

            for (int i = 0; e.DataMessage.Asks != null && i < e.DataMessage.Asks.Length;i++)
            {
                OsEngine.Enreplacedy.MarketDepthLevel ask = new OsEngine.Enreplacedy.MarketDepthLevel();
                ask.Price = e.DataMessage.Asks[i].Price;
                ask.Ask = e.DataMessage.Asks[i].Volume;

                for(int i2 = 0;i2 < depth.Asks.Count;i2++)
                {
                    if(depth.Asks[i2].Price == ask.Price)
                    {
                        depth.Asks.RemoveAt(i2);
                        break;
                    }
                }

                if(ask.Ask != 0)
                {
                    depth.Asks.Add(ask);
                }
                
                depth.Time = new DateTime(1970, 1, 1).AddSeconds(Convert.ToDouble(e.DataMessage.Asks[i].Timestamp));
            }

            for (int i = 0; e.DataMessage.Bids != null && i < e.DataMessage.Bids.Length; i++)
            {
                OsEngine.Enreplacedy.MarketDepthLevel bid = new OsEngine.Enreplacedy.MarketDepthLevel();
                bid.Price = e.DataMessage.Bids[i].Price;
                bid.Bid = e.DataMessage.Bids[i].Volume;

                for (int i2 = 0; i2 < depth.Bids.Count; i2++)
                {
                    if (depth.Bids[i2].Price == bid.Price)
                    {
                        depth.Bids.RemoveAt(i2);
                        break;
                    }
                }

                if (bid.Bid != 0)
                {
                    depth.Bids.Add(bid);
                }

                depth.Time = new DateTime(1970, 1, 1).AddSeconds(Convert.ToDouble(e.DataMessage.Bids[i].Timestamp));
            }

            // 1 Теперь сортируем биды и аски

            for(int i = 0;i < depth.Asks.Count;i++)
            {
                for(int i2 = 0;i2< depth.Asks.Count-1;i2++)
                {
                    if(depth.Asks[i2].Price > depth.Asks[i2+1].Price)
                    {
                        MarketDepthLevel level = depth.Asks[i2];
                        depth.Asks[i2] = depth.Asks[i2+1];
                        depth.Asks[i2 + 1] = level;
                    }
                }
            }


            for (int i = 0; i < depth.Bids.Count; i++)
            {
                for (int i2 = 0; i2 < depth.Bids.Count - 1; i2++)
                {
                    if (depth.Bids[i2].Price < depth.Bids[i2 + 1].Price)
                    {
                        MarketDepthLevel level = depth.Bids[i2];
                        depth.Bids[i2] = depth.Bids[i2 + 1];
                        depth.Bids[i2 + 1] = level;
                    }
                }
            }

            // 2 Теперь удаляем перехлёсты


            while(depth.Bids.Count > 0 &&
                depth.Asks.Count > 0 &&
                depth.Bids[0].Price > depth.Asks[0].Price)
            {
                depth.Asks.RemoveAt(0);
            }

            // !!!!!!!!!!!!!!!!!!!!!!


            // высылаем копию

            if (MarketDepthUpdateEvent != null)
            {
                MarketDepthUpdateEvent(depth.GetCopy());
            }

        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : 3RD-Dimension

private void viewport_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {             
            viewport.CalculateCursorPosition = true;
           if (Keyboard.IsKeyDown(Key.LeftShift))
            {
                if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile)
                {
                    // CurrentPosition Obsolete but works for now
                    string PositionX = GlobalFunctions.DecimalPlaceNoRounding(Convert.ToDouble(viewport.CurrentPosition.X), 3);
                    string PositionY = GlobalFunctions.DecimalPlaceNoRounding(Convert.ToDouble(viewport.CurrentPosition.Y), 3);
                    if (MessageBox.Show("Jog to Position " + "X:" + PositionX + ", Y:" + PositionY + "?", "Go to Position?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        machine.SendLine($"G90 G0 X{PositionX} Y{PositionY}");
                    }
                }
            }          
        }

19 View Source File : KrakenApi.cs
License : Apache License 2.0
Project Creator : AlexWan

private static void Client_SpreadReceived(object sender, Events.KrakenDataEventArgs<SpreadMessage> e)
        {
            // += (sender, e) => Console.WriteLine($"Spread received");
            return;

            string pair = e.Pair.ToString();

            Sec security = Securities.Find(sec => sec.NameInSocket == pair);
            DateTime time = new DateTime(1970, 1, 1).AddSeconds(Convert.ToDouble(e.DataMessage.Time));

            OsEngine.Enreplacedy.MarketDepth depth = new OsEngine.Enreplacedy.MarketDepth();
            depth.Time = time;
            depth.SecurityNameCode = security.NameInRest;

            OsEngine.Enreplacedy.MarketDepthLevel ask = new OsEngine.Enreplacedy.MarketDepthLevel();
            ask.Price = e.DataMessage.Ask;
            ask.Ask = 1;

            OsEngine.Enreplacedy.MarketDepthLevel bid = new OsEngine.Enreplacedy.MarketDepthLevel();
            bid.Price = e.DataMessage.Bid;
            bid.Bid = 1;

            depth.Asks.Add(ask);
            depth.Bids.Add(bid);

            if(MarketDepthUpdateEvent != null)
            {
                MarketDepthUpdateEvent(depth);
            }

        }

19 View Source File : AuthenticationHelper.cs
License : MIT License
Project Creator : AlejandroRuiz

public static string GenerateJwtToken(string email, ApplicationUser user, IConfiguration configuration)
        {
            var claims = new List<Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.NameIdentifier, user.Id)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtKey"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expires = DateTime.Now.AddDays(Convert.ToDouble(configuration["JwtExpireDays"]));

            var token = new JwtSecurityToken(
                configuration["JwtIssuer"],
                configuration["JwtIssuer"],
                claims,
                expires: expires,
                signingCredentials: creds
            );
            return new JwtSecurityTokenHandler().WriteToken(token);
        }

19 View Source File : KrakenApi.cs
License : Apache License 2.0
Project Creator : AlexWan

private static void Client_OpenOrdersReceived(object sender, Events.KrakenPrivateEventArgs<OpenOrdersMessage> e)
        {
            //OrdersUpdateEvent

            List<Order> orders = e.PrivateMessage.Orders.ToList();

            for (int i = 0; i < orders.Count; i++)
            {
                Order o = orders[i];

                int numberUser = 0;

                if (o.UserRef == 0)
                {
                    OrdersRef myRef = _ordersRefs.Find(ord => ord.MarketRef == o.OrderId);
                    if(myRef == null)
                    {
                        continue;
                    }
                    else
                    {
                        numberUser = myRef.UserRef;
                    }
                }
                else if(_ordersRefs.Find(ord => ord.UserRef == o.UserRef) == null)
                {
                    OrdersRef newRef = new OrdersRef();
                    newRef.MarketRef = o.OrderId;
                    newRef.UserRef = Convert.ToInt32(o.UserRef);
                    _ordersRefs.Add(newRef);

                    numberUser = Convert.ToInt32(o.UserRef);
                }

                OsEngine.Enreplacedy.Order orderOsEngine = new OsEngine.Enreplacedy.Order();

                orderOsEngine.NumberMarket = o.OrderId;
                orderOsEngine.NumberUser = numberUser;

                DateTime time = new DateTime(1970, 1, 1).AddSeconds(Convert.ToDouble(o.OpenTimestamp));

                orderOsEngine.TimeCallBack = time;

                if (o.Status == "canceled" ||
                    o.Status == "expired")
                {
                    orderOsEngine.State = OsEngine.Enreplacedy.OrderStateType.Cancel;
                }

                else if (o.Status == "closed" ||
                    o.Status == "canceled" ||
                    o.Status == "expired")
                {
                    orderOsEngine.State = OsEngine.Enreplacedy.OrderStateType.Done;
                }

                else
                {
                    orderOsEngine.State = OsEngine.Enreplacedy.OrderStateType.Activ;
                }

                if (OrdersUpdateEvent != null)
                {
                    OrdersUpdateEvent(orderOsEngine);
                }
            }


            // = (sender, e) => Console.WriteLine($"OpenOrders received");
        }

19 View Source File : CursorPosition.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

public void Evaluate()
        {
            Point currentPos = WindowHooks.CurrentCursorPosition();
            _XField.SetOutput(Convert.ToDouble(currentPos.X));
            _YField.SetOutput(Convert.ToDouble(currentPos.Y));
        }

19 View Source File : LivecoinServer.cs
License : Apache License 2.0
Project Creator : AlexWan

private void Client_MyOrderEvent(int numUser, string portfolio, PrivateOrderRawEvent orderInfo)
        {
            lock (_orderLocker)
            {
                var needOrder = _myOrders.Find(o => o.NumberUser == numUser);

                if (needOrder == null)
                {
                    return;
                }

                var order = new OsEngine.Enreplacedy.Order();
                order.NumberUser = numUser;
                order.PortfolioNumber = portfolio;
                order.SecurityNameCode = needOrder.SecurityNameCode;

                if (orderInfo.Id == -1)
                {
                    order.State = OrderStateType.Fail;
                    order.Price = needOrder.Price;
                    order.Volume = needOrder.Volume;
                    order.Side = needOrder.Side;
                    order.NumberMarket = needOrder.NumberMarket;

                    MyOrderEvent?.Invoke(order);

                    return;
                }

                order.NumberMarket = orderInfo.Id.ToString();
                order.Price = ParseDecimal(orderInfo.Price);
                order.TimeCallBack = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(orderInfo.Timestamp));
                order.Volume = needOrder.Volume;
                order.Side = orderInfo.order_type == PrivateOrderRawEvent.OrderType.Bid ? Side.Buy : Side.Sell;

                decimal quanreplacedy = ParseDecimal(orderInfo.Quanreplacedy);
                decimal cancelVolume = ParseDecimal(orderInfo.QuanreplacedyLeftBeforeCancellation);

                if (quanreplacedy == 0 && cancelVolume == needOrder.Volume)
                {
                    order.State = OrderStateType.Cancel;
                    DelOrder(needOrder);
                }
                else if (quanreplacedy == 0 && cancelVolume == 0)
                {
                    order.State = OrderStateType.Done;
                    DelOrder(needOrder);
                }
                else if (quanreplacedy == order.Volume)
                {
                    order.State = OrderStateType.Activ;
                }
                else if (needOrder.Volume != quanreplacedy && quanreplacedy != 0)
                {
                    order.State = OrderStateType.Patrial;
                }

                MyOrderEvent?.Invoke(order);
            }
        }

19 View Source File : RequestMessage.cs
License : MIT License
Project Creator : alexandredenes

public static RequestMessage Parse(byte[] data)
        {
            RequestMessage retVal = new RequestMessage();

            JObject obj = JObject.Parse(Encoding.Default.GetString(data));

            retVal.Id = (string)obj["id"];
            retVal.Action = (string)obj["action"];
            retVal.Params = (JObject)obj["params"];
            retVal.Timeout = Convert.ToDouble(obj["timeout"]);
            retVal.Level = (int)obj["level"];
            retVal.Metrics = string.IsNullOrEmpty(obj["metrics"].ToString()) ? false : (bool)obj["metrics"];
            retVal.ParentID = (string)obj["parentID"];
            retVal.RequestID = (string)obj["requestID"];
            retVal.Ver = (string)obj["ver"];
            retVal.Sender = (string)obj["sender"];

            return retVal;
        }

19 View Source File : OsMinerServer.cs
License : Apache License 2.0
Project Creator : AlexWan

private void LoadCandleFromFolder(string folderName)
        {

            string[] files = Directory.GetFiles(folderName);

            if (files.Length == 0)
            {
                return;
            }

            List<MinerCandleSeries> security = new List<MinerCandleSeries>();

            for (int i = 0; i < files.Length; i++)
            {
                security.Add(new MinerCandleSeries());
                security[security.Count - 1].FileAdress = files[i];
                security[security.Count - 1].LogMessageEvent += TesterServer_LogMessageEvent;

                string name = files[i].Split('\\')[files[i].Split('\\').Length - 1];

                security[security.Count - 1].Security = new Security();
                security[security.Count - 1].Security.Name = name;
                security[security.Count - 1].Security.Lot = 1;
                security[security.Count - 1].Security.NameClreplaced = "TestClreplaced";
                security[security.Count - 1].Security.Go = 1;
                security[security.Count - 1].Security.PriceStepCost = 1;
                security[security.Count - 1].Security.PriceStep = 1;
                // timeframe / тф
                // step price / шаг цены
                // begin / начало
                // end / конец

                StreamReader reader = new StreamReader(files[i]);

                // candles/свечи: 20110111,100000,19577.00000,19655.00000,19533.00000,19585.00000,2752
                // ticks ver.1/тики 1 вар: 20150401,100000,86160.000000000,2
                // ticks ver.2/тики 2 вар: 20151006,040529,3010,5,Buy/Sell/Unknown

                string str = reader.ReadLine();

                try
                {
                    // check whether candles are in the file / смотрим свечи ли в файле
                    Candle candle = new Candle();
                    candle.SetCandleFromString(str);
                    // candles are in the file. We look at which ones / в файле свечи. Смотрим какие именно

                    security[security.Count - 1].TimeStart = candle.TimeStart;

                    Candle candle2 = new Candle();
                    candle2.SetCandleFromString(reader.ReadLine());

                    security[security.Count - 1].TimeFrameSpan = candle2.TimeStart - candle.TimeStart;
                    security[security.Count - 1].TimeFrame = GetTimeFrame(security[security.Count - 1].TimeFrameSpan);
                    // step price / шаг цены

                    decimal minPriceStep = decimal.MaxValue;
                    int countFive = 0;

                    CultureInfo culture = new CultureInfo("ru-RU");

                    for (int i2 = 0; i2 < 20; i2++)
                    {
                        Candle candleN = new Candle();
                        candleN.SetCandleFromString(reader.ReadLine());

                        decimal open = (decimal) Convert.ToDouble(candleN.Open);
                        decimal high = (decimal) Convert.ToDouble(candleN.High);
                        decimal low = (decimal) Convert.ToDouble(candleN.Low);
                        decimal close = (decimal) Convert.ToDouble(candleN.Close);

                        if (open.ToString(culture).Split(',').Length > 1 ||
                            high.ToString(culture).Split(',').Length > 1 ||
                            low.ToString(culture).Split(',').Length > 1 ||
                            close.ToString(culture).Split(',').Length > 1)
                        {
                            // if the real part takes place / если имеет место вещественная часть
                            int lenght = 1;

                            if (open.ToString(culture).Split(',').Length > 1 &&
                                open.ToString(culture).Split(',')[1].Length > lenght)
                            {
                                lenght = open.ToString(culture).Split(',')[1].Length;
                            }

                            if (high.ToString(culture).Split(',').Length > 1 &&
                                high.ToString(culture).Split(',')[1].Length > lenght)
                            {
                                lenght = high.ToString(culture).Split(',')[1].Length;
                            }

                            if (low.ToString(culture).Split(',').Length > 1 &&
                                low.ToString(culture).Split(',')[1].Length > lenght)
                            {
                                lenght = low.ToString(culture).Split(',')[1].Length;
                            }

                            if (close.ToString(culture).Split(',').Length > 1 &&
                                close.ToString(culture).Split(',')[1].Length > lenght)
                            {
                                lenght = close.ToString(culture).Split(',')[1].Length;
                            }

                            if (lenght == 1 && minPriceStep > 0.1m)
                            {
                                minPriceStep = 0.1m;
                            }
                            if (lenght == 2 && minPriceStep > 0.01m)
                            {
                                minPriceStep = 0.01m;
                            }
                            if (lenght == 3 && minPriceStep > 0.001m)
                            {
                                minPriceStep = 0.001m;
                            }
                            if (lenght == 4 && minPriceStep > 0.0001m)
                            {
                                minPriceStep = 0.0001m;
                            }
                            if (lenght == 5 && minPriceStep > 0.00001m)
                            {
                                minPriceStep = 0.00001m;
                            }
                            if (lenght == 6 && minPriceStep > 0.000001m)
                            {
                                minPriceStep = 0.000001m;
                            }
                            if (lenght == 7 && minPriceStep > 0.0000001m)
                            {
                                minPriceStep = 0.0000001m;
                            }
                        }
                        else
                        {
                            // if the real part doesn't take place / если вещественной части нет
                            int lenght = 1;

                            for (int i3 = open.ToString(culture).Length - 1; open.ToString(culture)[i3] == '0'; i3--)
                            {
                                lenght = lenght*10;
                            }

                            int lengthLow = 1;

                            for (int i3 = low.ToString(culture).Length - 1; low.ToString(culture)[i3] == '0'; i3--)
                            {
                                lengthLow = lengthLow*10;

                                if (lenght > lengthLow)
                                {
                                    lenght = lengthLow;
                                }
                            }

                            int lengthHigh = 1;

                            for (int i3 = high.ToString(culture).Length - 1; high.ToString(culture)[i3] == '0'; i3--)
                            {
                                lengthHigh = lengthHigh*10;

                                if (lenght > lengthHigh)
                                {
                                    lenght = lengthHigh;
                                }
                            }

                            int lengthClose = 1;

                            for (int i3 = close.ToString(culture).Length - 1; close.ToString(culture)[i3] == '0'; i3--)
                            {
                                lengthClose = lengthClose*10;

                                if (lenght > lengthClose)
                                {
                                    lenght = lengthClose;
                                }
                            }
                            if (minPriceStep > lenght)
                            {
                                minPriceStep = lenght;
                            }

                            if (minPriceStep == 1 &&
                                open%5 == 0 && high%5 == 0 &&
                                close%5 == 0 && low%5 == 0)
                            {
                                countFive++;
                            }
                        }
                    }


                    if (minPriceStep == 1 &&
                        countFive == 20)
                    {
                        minPriceStep = 5;
                    }


                    security[security.Count - 1].Security.PriceStep = minPriceStep;
                    security[security.Count - 1].Security.PriceStepCost = minPriceStep;


                    // last date / последняя дата
                    string lastString = null;

                    while (!reader.EndOfStream)
                    {
                        lastString = reader.ReadLine();
                    }


                    Candle candle3 = new Candle();
                    candle3.SetCandleFromString(lastString);
                    security[security.Count - 1].TimeEnd = candle3.TimeStart;

                    reader.Close();

                }
                catch (Exception)
                {
                    security.Remove(security[security.Count - 1]);
                }
                finally
                {
                    reader.Close();
                }
            }

			// save security
            // сохраняем бумаги

            if (security == null ||
                security.Count == 0)
            {
                return;
            }

            if (_securities == null)
            {
                _securities = new List<Security>();
            }

            for (int i = 0; i < security.Count; i++)
            {
                if (_securities.Find(security1 => security1.Name == security[i].Security.Name) == null)
                {
                    _securities.Add(security[i].Security);
                }
            }

// count time
// считаем время
            
            SecuritiesTester.AddRange(security);

            if (SecuritiesTester.Count != 0)
            {
                for (int i = 0; i < SecuritiesTester.Count; i++)
                {
                    if ((TimeMin == DateTime.MinValue && SecuritiesTester[i].TimeStart != DateTime.MinValue) ||
                        (SecuritiesTester[i].TimeStart != DateTime.MinValue && SecuritiesTester[i].TimeStart < TimeMin))
                    {
                        TimeMin = SecuritiesTester[i].TimeStart;
                        TimeStart = SecuritiesTester[i].TimeStart;
                        TimeNow = SecuritiesTester[i].TimeStart;
                    }
                    if (SecuritiesTester[i].TimeEnd != DateTime.MinValue &&
                        SecuritiesTester[i].TimeEnd > TimeMax)
                    {
                        TimeMax = SecuritiesTester[i].TimeEnd;
                        TimeEnd = SecuritiesTester[i].TimeEnd;
                    }
                    SecuritiesTester[i].LoadCandles();
                }
            }
        }

19 View Source File : GRBLStepsCalc.cs
License : MIT License
Project Creator : 3RD-Dimension

private void checkFineTuneInput(object sender, TextChangedEventArgs e)
        {
            if (!string.IsNullOrEmpty(currentSteps.Text) && !string.IsNullOrEmpty(distanceCommanded.Text) && !string.IsNullOrEmpty(distanceTraveled.Text))
            {
                _distanceTraveled = Convert.ToDouble(distanceTraveled.Text);
                _distanceCommanded = Convert.ToDouble(distanceCommanded.Text);
                calcNewSteps();
            }
        }

19 View Source File : TaskInput.cs
License : MIT License
Project Creator : altskop

private void moveMouse(Vector2 destination)
        {
            var x = destination.x * 65535 / Screen.PrimaryScreen.Bounds.Width;
            var y = destination.y * 65535 / Screen.PrimaryScreen.Bounds.Height;
            inputSimulator.Mouse.MoveMouseTo(Convert.ToDouble(x), Convert.ToDouble(y));
        }

19 View Source File : BarSeriesBase{T}.cs
License : MIT License
Project Creator : AlexGyver

protected internal override void UpdateData()
        {
            if (this.ItemsSource == null)
            {
                return;
            }

            var dest = new List<T>();

            // Using reflection to add points
            var filler = new ListFiller<T>();
            filler.Add(this.ValueField, (item, value) => item.Value = Convert.ToDouble(value));
            filler.Add(this.ColorField, (item, value) => item.Color = (OxyColor)value);
            filler.Fill(dest, this.ItemsSource);
            this.Items = dest;
        }

19 View Source File : MetadataEntityAttributeUpdate.cs
License : MIT License
Project Creator : Adoxio

protected object GetValue(JToken token, AttributeTypeCode attributeType)
		{
			var value = token.ToObject<object>();

			if (value == null)
			{
				return null;
			}

			if (attributeType == AttributeTypeCode.Customer || attributeType == AttributeTypeCode.Lookup || attributeType == AttributeTypeCode.Owner)
			{
				EnreplacedyReference enreplacedyReference;

				if (TryGetEnreplacedyReference(value, out enreplacedyReference))
				{
					return enreplacedyReference;
				}

				throw new FormatException("Unable to convert value {0} for attribute {1} to {2}.".FormatWith(value, Attribute.LogicalName, typeof(EnreplacedyReference)));
			}

			// Option set values will be in Int64 form from the JSON deserialization -- convert those to OptionSetValues
			// for option set attributes.
			if (attributeType == AttributeTypeCode.EnreplacedyName || attributeType == AttributeTypeCode.Picklist || attributeType == AttributeTypeCode.State || attributeType == AttributeTypeCode.Status)
			{
				return new OptionSetValue(Convert.ToInt32(value));
			}

			if (attributeType == AttributeTypeCode.Memo || attributeType == AttributeTypeCode.String)
			{
				return value is string ? value : value.ToString();
			}

			if (attributeType == AttributeTypeCode.BigInt)
			{
				return Convert.ToInt64(value);
			}

			if (attributeType == AttributeTypeCode.Boolean)
			{
				return Convert.ToBoolean(value);
			}

			if (attributeType == AttributeTypeCode.DateTime)
			{
				var dateTimeValue = Convert.ToDateTime(value);

				return dateTimeValue.Kind == DateTimeKind.Utc ? dateTimeValue : dateTimeValue.ToUniversalTime();
			}

			if (attributeType == AttributeTypeCode.Decimal)
			{
				return Convert.ToDecimal(value);
			}

			if (attributeType == AttributeTypeCode.Double)
			{
				return Convert.ToDouble(value);
			}

			if (attributeType == AttributeTypeCode.Integer)
			{
				return Convert.ToInt32(value);
			}

			if (attributeType == AttributeTypeCode.Money)
			{
				return new Money(Convert.ToDecimal(value));
			}

			if (attributeType == AttributeTypeCode.Uniqueidentifier)
			{
				return value is Guid ? value : new Guid(value.ToString());
			}

			return value;
		}

19 View Source File : HotKeyControl.cs
License : MIT License
Project Creator : 3RD-Dimension

private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (!machine.Connected)
                return;     

            string currentHotPressed = HotKeys.KeyProcess(sender, e); // Get Keycode
            if (currentHotPressed == null) return; // If currentHotPressed is null, Return (to avoid continuing with  blank)

            if (currentHotPressed == "Left" || currentHotPressed == "Right" || currentHotPressed == "Up" || currentHotPressed == "Down")
            {
                viewport.IsPanEnabled = false;
                viewport.IsRotationEnabled = false;
                viewport.IsMoveEnabled = false;
            }

            if (machine.Mode == Machine.OperatingMode.Manual)
            {
                if (machine.BufferState > 0 || machine.Status != "Idle")
                    return;

                string direction = null;

                if (currentHotPressed == HotKeys.hotkeyCode["JogXPos"])
                    direction = "X";
                else if (currentHotPressed == HotKeys.hotkeyCode["JogXNeg"])
                    direction = "X-";
                else if (currentHotPressed == HotKeys.hotkeyCode["JogYPos"])
                    direction = "Y";
                else if (currentHotPressed == HotKeys.hotkeyCode["JogYNeg"])
                    direction = "Y-";
                else if (currentHotPressed == HotKeys.hotkeyCode["JogZPos"])
                    direction = "Z";
                else if (currentHotPressed == HotKeys.hotkeyCode["JogZNeg"])
                    direction = "Z-";
                else if (currentHotPressed == HotKeys.hotkeyCode["RTOrigin"]) // Return to Origin ie back to all axis Zero position
                    ButtonManualReturnToZero.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                else if (currentHotPressed == HotKeys.hotkeyCode["FSStop"]) // Jog Cancel
                    machine.JogCancel();

                if (direction != null)
                {
                    manualJogSendCommand(direction);
                }
            }

            viewport.IsPanEnabled = true;
            viewport.IsRotationEnabled = true;
            viewport.IsMoveEnabled = true;

            // Emergency Reset
            if (machine.Connected && currentHotPressed == HotKeys.hotkeyCode["EmgStop"])
                machine.SoftReset();
            // Cycle Start - Only allowed if Connected, and not currently sending a file
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["CycleStart"])
                ButtonFileStart.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            // Reload File (Re-Do)
            else if (machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["ReDoReload"]) // Only if not currently sending
                ReloadCurrentFile();
            else if (machine.Mode == Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["FSStop"]) // Put machine on Hold if sending a file
                ButtonFilePause.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            // Spindle and Flood  (firmware takes care if it will enable or disable so just need to know if it is connected to controller to turn on Manually.           
            else if (machine.Connected && currentHotPressed == HotKeys.hotkeyCode["SpindleOnOff"]) // Spindle Toggle
                SpindleControl();
            else if (machine.Connected && currentHotPressed == HotKeys.hotkeyCode["CoolantOnOff"]) // Coolant Toggle
                FloodControl();
            else if (machine.Connected && currentHotPressed == HotKeys.hotkeyCode["MistOnOff"]) // Mist Toggle
                MistControl();

            // Need to save back to Settings otherwise will not register unless it is focused, maybe try Focus() first....
            
            // JOG RATE AXIS X
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JRateIncX"])
            {
                double currentJogRate = Convert.ToDouble(TextBoxJogFeedX.Text);
                double newJogRate = currentJogRate + Properties.Settings.Default.JogFeedXIncDec;
                TextBoxJogFeedX.Text = newJogRate.ToString();
                Properties.Settings.Default.JogFeedX = newJogRate;
            }           
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JRateDecX"])
            {
                double currentJogRate = Convert.ToDouble(TextBoxJogFeedX.Text);
                double newJogRate = currentJogRate - Properties.Settings.Default.JogFeedXIncDec;
                if (newJogRate < Properties.Settings.Default.JogFeedXIncDec)
                    newJogRate = Properties.Settings.Default.JogFeedXIncDec;
                TextBoxJogFeedX.Text = newJogRate.ToString();
                Properties.Settings.Default.JogFeedX = newJogRate;
            }
            // JOG RATE AXIS Y
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JRateIncY"])
            {
                double currentJogRate = Convert.ToDouble(TextBoxJogFeedY.Text);
                double newJogRate = currentJogRate + Properties.Settings.Default.JogFeedYIncDec;
                TextBoxJogFeedY.Text = newJogRate.ToString();
                Properties.Settings.Default.JogFeedY = newJogRate;
            }
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JRateDecY"])
            {
                double currentJogRate = Convert.ToDouble(TextBoxJogFeedY.Text);
                double newJogRate = currentJogRate - Properties.Settings.Default.JogFeedYIncDec;
                if (newJogRate < Properties.Settings.Default.JogFeedYIncDec)
                    newJogRate = Properties.Settings.Default.JogFeedYIncDec;
                TextBoxJogFeedY.Text = newJogRate.ToString();
                Properties.Settings.Default.JogFeedY = newJogRate;
            }
            // JOG RATE AXIS Z
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JRateIncZ"])
            {
                double currentJogRate = Convert.ToDouble(TextBoxJogFeedZ.Text);
                double newJogRate = currentJogRate + Properties.Settings.Default.JogFeedZIncDec;
                TextBoxJogFeedZ.Text = newJogRate.ToString();
                Properties.Settings.Default.JogFeedZ = newJogRate;
            }
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JRateDecZ"])
            {
                double currentJogRate = Convert.ToDouble(TextBoxJogFeedZ.Text);
                double newJogRate = currentJogRate - Properties.Settings.Default.JogFeedZIncDec;
                if (newJogRate < Properties.Settings.Default.JogFeedZIncDec)
                    newJogRate = Properties.Settings.Default.JogFeedZIncDec;
                TextBoxJogFeedZ.Text = newJogRate.ToString();
                Properties.Settings.Default.JogFeedZ = newJogRate;
            }

            // JOG DISTANCE X
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JDistIncX"])
            {
                double currentJogDist = Convert.ToDouble(TextBoxJogDistanceX.Text);
                double newJogDist = currentJogDist + Properties.Settings.Default.JogDistXIncDec;
                TextBoxJogDistanceX.Text = newJogDist.ToString();
                Properties.Settings.Default.JogDistanceX = newJogDist;
            }
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JDistDecX"])
            {
                double currentJogDist = Convert.ToDouble(TextBoxJogDistanceX.Text);
                double newJogDist = currentJogDist - Properties.Settings.Default.JogDistXIncDec;
                if (newJogDist < Properties.Settings.Default.JogDistXIncDec)  
                    newJogDist = Properties.Settings.Default.JogDistXIncDec;
                TextBoxJogDistanceX.Text = newJogDist.ToString();
                Properties.Settings.Default.JogDistanceX = newJogDist;
            }

            // JOG DISTANCE Y
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JDistIncY"])
            {
                double currentJogDist = Convert.ToDouble(TextBoxJogDistanceY.Text);
                double newJogDist = currentJogDist + Properties.Settings.Default.JogDistYIncDec;
                TextBoxJogDistanceY.Text = newJogDist.ToString();
                Properties.Settings.Default.JogDistanceY = newJogDist;
            }
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JDistDecY"])
            {
                double currentJogDist = Convert.ToDouble(TextBoxJogDistanceY.Text);
                double newJogDist = currentJogDist - Properties.Settings.Default.JogDistYIncDec;
                if (newJogDist < Properties.Settings.Default.JogDistYIncDec)
                    newJogDist = Properties.Settings.Default.JogDistYIncDec;
                TextBoxJogDistanceY.Text = newJogDist.ToString();
                Properties.Settings.Default.JogDistanceY = newJogDist;
            }

            // JOG DISTANCE Z
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JDistIncZ"])
            {
                double currentJogDist = Convert.ToDouble(TextBoxJogDistanceZ.Text);
                double newJogDist = currentJogDist + Properties.Settings.Default.JogDistZIncDec;
                TextBoxJogDistanceZ.Text = newJogDist.ToString();
                Properties.Settings.Default.JogDistanceZ = newJogDist;
            }
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JDistDecZ"])
            {
                double currentJogDist = Convert.ToDouble(TextBoxJogDistanceZ.Text);
                double newJogDist = currentJogDist - Properties.Settings.Default.JogDistZIncDec;
                if (newJogDist < Properties.Settings.Default.JogDistZIncDec)
                    newJogDist = Properties.Settings.Default.JogDistZIncDec;
                TextBoxJogDistanceZ.Text = newJogDist.ToString();
                Properties.Settings.Default.JogDistanceZ = newJogDist;
            }
            
            // Feed Rate
            // FeedRateIncrement & SpindleIncrement False = 1% Inc and Dec, True = 10% Inc and Dec
            else if (machine.Mode == Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["FRateInc"]) // Feed Rate Incease
            {
                if (Properties.Settings.Default.FeedRateIncrement == true) // 10% Increase
                {
                    Feed10Inc.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                }
                else if (Properties.Settings.Default.FeedRateIncrement == false) // 1% Increase
                {
                    Feed1Inc.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                }
            }
            else if (machine.Mode == Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["FRateDec"]) // Feed Rate Incease
            {               
                if (Properties.Settings.Default.FeedRateIncrement == true) // 10% Decrease
                {
                    Feed10Dec.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                }
                else if (Properties.Settings.Default.FeedRateIncrement == false) // 1% Decrease
                {
                    Feed1Dec.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                }
            }
            // Spindle Increase and Decrease
            else if (machine.Mode == Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["SpindleInc"]) // Spindle Incease
            {
                if (Properties.Settings.Default.FeedRateIncrement == true) // 10% Increase
                {
                    Spindle10Inc.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                }
                else if (Properties.Settings.Default.FeedRateIncrement == false) // 1% Increase
                {
                    Spindle1Inc.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                }
            }
            else if (machine.Mode == Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["SprindleDec"]) // Spindle Incease
            {
                if (Properties.Settings.Default.FeedRateIncrement == true) // 10% Decrease
                {
                    Spindle10Dec.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                }
                else if (Properties.Settings.Default.FeedRateIncrement == false) // 1% Decrease
                {
                    Spindle1Dec.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                }
            }
        }

19 View Source File : GRBLStepsCalc.cs
License : MIT License
Project Creator : 3RD-Dimension

public void openStepsCalc(object sender, RoutedEventArgs e)
        {
            // Clear Textboxes
            distanceTraveled.Clear();
            distanceCommanded.Clear();
            newStepValue.Clear();

            _settingTextBox = sender as TextBox;
            currentSteps.Text = _settingTextBox.Text;
            _currentSteps = Convert.ToDouble(currentSteps.Text);
            GRBLSettingsScroller.IsEnabled = false;
            StepsCalcPanel.Visibility = Visibility.Visible;
        }

19 View Source File : DynamoDBItem.cs
License : MIT License
Project Creator : abelperezok

public double GetDouble(string key)
        {
            return Convert.ToDouble(_data.GetValueOrDefault(key)?.N);
        }

19 View Source File : RatingBar.cs
License : GNU General Public License v3.0
Project Creator : aduskin

private static void ValueChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
      {
         RatingBar ratingBar = d as RatingBar;
         double newValue = Convert.ToDouble(e.NewValue);
         var buttonList = ((RatingBar)d).RatingButtonsInternal;

         foreach (var ratingBarButton in buttonList)
         {
            ratingBarButton.IsHalf = false;
            ratingBarButton.IsSelected = ratingBarButton.Value <= newValue;
         }

         //for (int i = 0; i < buttonList.Count; i++)
         //{
         //    RatingBarButton ratingBarButton = buttonList[i];
         //    ratingBarButton.IsSelected = i <= Math.Ceiling(newValue);
         //    ratingBarButton.IsHalf = ratingBar.IsInt(newValue) ? false : Math.Ceiling(newValue) == i;
         //}
      }

19 View Source File : ParabolicSARUi.xaml.cs
License : Apache License 2.0
Project Creator : AlexWan

private void ButtonAccept_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (Convert.ToDouble(TextBoxAf.Text) <= 0 || Convert.ToDouble(TextBoxMaxAf.Text) <= 0)
                {
                    throw new Exception("error");
                }
                //Enum.TryParse(ComboBoxMovingType.SelectedItem.ToString(), true, out _mA.TypeCalculationAverage);
            }
            catch (Exception)
            {
                MessageBox.Show("Процесс сохранения прерван. В одном из полей недопустимые значения");
                return;
            }

            _mA.ColorUp = HostColor.Child.BackColor;
            _mA.ColorDown = HostColorDown.Child.BackColor;

            _mA.Af = Convert.ToDouble(TextBoxAf.Text);
            _mA.MaxAf = Convert.ToDouble(TextBoxMaxAf.Text);
            _mA.PaintOn = CheckBoxPaintOnOff.IsChecked.Value;
            //Enum.TryParse(ComboBoxPriceField.SelectedItem.ToString(), true, out _mA.TypePointsToSearch);

            _mA.Save();
            IsChange = true;
            Close();
        }

See More Examples