private void BuildExchangeRateEntity(IExchangeRate exchRate) { exchRate.ExchangeRateID = _exchRateId; exchRate.ExchangeDate = Convert.ToDateTime(txtDate.Text, _culture); exchRate.USDExchangeRate = Convert.ToDecimal(txtRate.Text); //exchRate.FreeDays = Convert.ToInt32(txtFreeDays.Text); }
/// <summary> /// Updates controls which are set to use multi currency. /// </summary> /// <param name="opportunity">The opportunity.</param> /// <param name="exchangeRate">The exchange rate.</param> private void UpdateMultiCurrencyExchangeRate(IOpportunity opportunity, Double exchangeRate) { string myCurrencyCode = BusinessRuleHelper.GetMyCurrencyCode(); IExchangeRate myExchangeRate = EntityFactory.GetById <IExchangeRate>(String.IsNullOrEmpty(myCurrencyCode) ? "USD" : myCurrencyCode); double myRate = 0; if (myExchangeRate != null) { myRate = myExchangeRate.Rate.GetValueOrDefault(1); } string currentCode = opportunity.ExchangeRateCode; curOpenSalesPotential.CurrentCode = currentCode; curOpenSalesPotential.ExchangeRate = exchangeRate; curMyCurSalesPotential.CurrentCode = myCurrencyCode; curMyCurSalesPotential.ExchangeRate = myRate; curActualWon.CurrentCode = currentCode; curActualWon.ExchangeRate = exchangeRate; curMyCurActualWon.CurrentCode = myCurrencyCode; curMyCurActualWon.ExchangeRate = myRate; curPotentialLost.CurrentCode = currentCode; curPotentialLost.ExchangeRate = exchangeRate; curMyCurPotentialLost.CurrentCode = myCurrencyCode; curMyCurPotentialLost.ExchangeRate = myRate; curWeighted.CurrentCode = currentCode; curWeighted.ExchangeRate = exchangeRate; curMyCurWeighted.CurrentCode = myCurrencyCode; curMyCurWeighted.ExchangeRate = myRate; }
public static Money ToEur(decimal amount, DateTime actionDate, IExchangeRate exchangeRate) { var targetCurrency = exchangeRate.FindExchangeRate(CurrencyType.Eur, actionDate); var newAmount = amount / targetCurrency.Value; return(new Money(decimal.Round(newAmount, Currency.Eur.DecimalPlaces), Currency.Eur)); }
protected override void InitializeObject(IGenericEntity ent) { if (ent is IExchangeRate) { IExchangeRate ExchangeRate = (IExchangeRate)ent; DBStoredProcedure spInsert = new DBStoredProcedure(); spInsert.ProcedureName = "catInsertExchangeRate"; spInsert.AddParameter(new DBParameter("Year", DbType.Int32, ParameterDirection.Input, ExchangeRate.Year)); spInsert.AddParameter(new DBParameter("Month", DbType.Int32, ParameterDirection.Input, ExchangeRate.Month)); spInsert.AddParameter(new DBParameter("IdCurrencyTo", DbType.Int32, ParameterDirection.Input, ExchangeRate.IdCurrencyTo)); spInsert.AddParameter(new DBParameter("ConversionRate", DbType.Decimal, ParameterDirection.Input, ExchangeRate.ConversionRate)); DBStoredProcedure spUpdate = new DBStoredProcedure(); spUpdate.ProcedureName = "catUpdateExchangeRate"; spUpdate.AddParameter(new DBParameter("Id", DbType.Int32, ParameterDirection.Input, ExchangeRate.Id)); spUpdate.AddParameter(new DBParameter("Year", DbType.Int32, ParameterDirection.Input, ExchangeRate.Year)); spUpdate.AddParameter(new DBParameter("Month", DbType.Int32, ParameterDirection.Input, ExchangeRate.Month)); spUpdate.AddParameter(new DBParameter("IdCurrencyTo", DbType.Int32, ParameterDirection.Input, ExchangeRate.IdCurrencyTo)); spUpdate.AddParameter(new DBParameter("ConversionRate", DbType.Decimal, ParameterDirection.Input, ExchangeRate.ConversionRate)); DBStoredProcedure spDelete = new DBStoredProcedure(); spDelete.ProcedureName = "catDeleteExchangeRate"; spDelete.AddParameter(new DBParameter("Id", DbType.Int32, ParameterDirection.Input, ExchangeRate.Id)); this.AddStoredProcedure("InsertObject", spInsert); this.AddStoredProcedure("UpdateObject", spUpdate); this.AddStoredProcedure("DeleteObject", spDelete); DBStoredProcedure spSelect = new DBStoredProcedure(); spSelect.ProcedureName = "catSelectExchangeRate"; spSelect.AddParameter(new DBParameter("Id", DbType.Int32, ParameterDirection.Input, ExchangeRate.Id)); this.AddStoredProcedure("SelectObject", spSelect); } }
public void Setup() { _config = program.InitConfiguration(); //Account to create _account = new Account() { AccountNo = "AC345", CustomerName = "Smith1 Barens1", LocalCurrencyCode = "GBP" }; //Db Set up var connection = _config["ConnectionString:BankDb"]; var builder = new DbContextOptionsBuilder <BankDBContext>() .UseSqlServer(connection); _bankDBContext = new BankDBContext(builder.Options); //Delete If exists ClearDbData(); //Set up DB InitDBContext(); _exchangeRate = new ExchangeRate(_config); //_bankDBContext.Accounts }
private void GetExchageRateData(Sage.Platform.Controls.ExchangeRateTypeEnum exchangeRateType, out string exchangeRateCode, out double exchangeRate) { string _exchangeRateCode = string.Empty; double?_exchangeRate = 0.0; if (exchangeRateType == Sage.Platform.Controls.ExchangeRateTypeEnum.EntityRate) { IOpportunity opp = BindingSource.Current as IOpportunity; _exchangeRateCode = opp.ExchangeRateCode; _exchangeRate = opp.ExchangeRate; } if (exchangeRateType == Sage.Platform.Controls.ExchangeRateTypeEnum.MyRate) { _exchangeRateCode = BusinessRuleHelper.GetMyCurrencyCode(); IExchangeRate myExchangeRate = EntityFactory.GetById <IExchangeRate>(String.IsNullOrEmpty(_exchangeRateCode) ? "USD" : _exchangeRateCode); if (myExchangeRate != null) { _exchangeRate = myExchangeRate.Rate.GetValueOrDefault(1); } } if (exchangeRateType == Sage.Platform.Controls.ExchangeRateTypeEnum.BaseRate) { var optionSvc = ApplicationContext.Current.Services.Get <ISystemOptionsService>(true); _exchangeRateCode = optionSvc.BaseCurrency; IExchangeRate er = EntityFactory.GetById <IExchangeRate>(String.IsNullOrEmpty(_exchangeRateCode) ? "USD" : _exchangeRateCode); _exchangeRate = er.Rate.GetValueOrDefault(1); if (_exchangeRate.Equals(0)) { _exchangeRate = 1; } } exchangeRateCode = _exchangeRateCode; exchangeRate = Convert.ToDouble(_exchangeRate); }
/// <summary> /// Updates controls which are set to use multi currency. /// </summary> /// <param name="salesOrder">The sales order.</param> /// <param name="exchangeRate">The exchange rate.</param> private void UpdateMultiCurrencyExchangeRate(ISalesOrder salesOrder, Double exchangeRate) { string myCurrencyCode = BusinessRuleHelper.GetMyCurrencyCode(); IExchangeRate myExchangeRate = EntityFactory.GetById <IExchangeRate>(String.IsNullOrEmpty(myCurrencyCode) ? "USD" : myCurrencyCode); double myRate = 0; if (myExchangeRate != null) { myRate = myExchangeRate.Rate.GetValueOrDefault(1); } curDiscount.CurrentCode = salesOrder.CurrencyCode; curDiscount.ExchangeRate = exchangeRate; curMyDiscount.CurrentCode = myCurrencyCode; curMyDiscount.ExchangeRate = myRate; curSubTotal.CurrentCode = String.IsNullOrEmpty(lueCurrencyCode.LookupResultValue.ToString()) ? salesOrder.CurrencyCode : lueCurrencyCode.LookupResultValue.ToString(); curTotal.CurrentCode = curSubTotal.CurrentCode; curTotal.ExchangeRate = exchangeRate; curMyTotal.CurrentCode = myCurrencyCode; curMyTotal.ExchangeRate = myRate; curSubTotal.CurrentCode = salesOrder.CurrencyCode; curSubTotal.ExchangeRate = exchangeRate; curMySubTotal.CurrentCode = myCurrencyCode; curMySubTotal.ExchangeRate = myRate; curTax.CurrentCode = salesOrder.CurrencyCode; curTax.ExchangeRate = exchangeRate; curMyTax.CurrentCode = myCurrencyCode; curMyTax.ExchangeRate = myRate; curShipping.CurrentCode = salesOrder.CurrencyCode; curShipping.ExchangeRate = exchangeRate; curMyShipping.CurrentCode = myCurrencyCode; curMyShipping.ExchangeRate = myRate; }
/*double tertySecondsChange = trend.ChangePercentageToLatest(ownedExchangeRate, TimeSpan.FromMinutes(0.5)); * double oneMinuteChange = trend.ChangePercentageToLatest(ownedExchangeRate, TimeSpan.FromMinutes(1)); * double fiveMinuteChange = trend.ChangePercentageToLatest(ownedExchangeRate, TimeSpan.FromMinutes(5)); * double thertyMinuteChange = trend.ChangePercentageToLatest(ownedExchangeRate, TimeSpan.FromMinutes(30)); * double sixtyMinuteChange = trend.ChangePercentageToLatest(ownedExchangeRate, TimeSpan.FromMinutes(60)); * double twientyFourHoursChange = trend.ChangePercentageToLatest(ownedExchangeRate, TimeSpan.FromHours(23)); * double currencyBalance = (account.BalancesInUsd[ownedExchangeRate.MainCurrency] - account.InitialBalancesInUsd[ownedExchangeRate.MainCurrency]); * double percentageGrowth = account.InitialBalancesInUsd[ownedExchangeRate.MainCurrency] != 0.0 && account.BalancesInUsd[ownedExchangeRate.MainCurrency] - account.InitialBalancesInUsd[ownedExchangeRate.MainCurrency] != 0.0 * ? 100.0 * (account.BalancesInUsd[ownedExchangeRate.MainCurrency] - account.InitialBalancesInUsd[ownedExchangeRate.MainCurrency]) / account.InitialBalancesInUsd[ownedExchangeRate.MainCurrency] * : 0.0; * } * * DateTime now = DateTime.Now; * DateTime dateTimeInitial = stockDataPoints.First(k => k.Key > now - timeSpan).Key; * if(stockDataPoints[dateTimeInitial] == stockDataPoints.Last().Value || * stockDataPoints.First().Key > now - timeSpan) * { * return double.NaN; * } * } * } * * public double ChangePercentageToLatest(IExchangeRate exchangeRate, TimeSpan timeSpan) * { * IDictionary<DateTime, double> stockDataPoints = exchangeRate.ExhangeHistory; * * DateTime now = DateTime.Now; * DateTime dateTimeInitial = stockDataPoints.First(k => k.Key > now - timeSpan).Key; * if (stockDataPoints[dateTimeInitial] == stockDataPoints.Last().Value || * stockDataPoints.First().Key > now - timeSpan) * { * return double.NaN; * } * return 100.0 * ((stockDataPoints.Last().Value - stockDataPoints[dateTimeInitial]) / stockDataPoints[dateTimeInitial]); * } * * public double ChangeWeighedPercentageToLatest(IExchangeRate exchangeRate, TimeSpan timeSpan) * { * IDictionary<DateTime, double> stockDataPoints = exchangeRate.ExhangeHistory; * * DateTime now = DateTime.Now; * DateTime dateTimeInitial = stockDataPoints.First(k => k.Key > now - timeSpan).Key; * List<KeyValuePair<DateTime,double>> entries = stockDataPoints.Where(k => k.Key > now - timeSpan).ToList(); * List<double> weigthedChangesPercentage = entries.Average(); * * List <double> weigthedChanges = new List<double>(); * for (int i = 1; i < entries.Count; i++) * { * weigthedChanges.Add(entries[i].Value - entries[i - 1].Value); * } * return weigthedChanges.Average(); * * return 100.0 * ((stockDataPoints.Last().Value - stockDataPoints[dateTimeInitial]) / stockDataPoints[dateTimeInitial]); * } * * * /* public TrendStatus CalculateTrends(IExchangeRate exchangeRate, int divisor = 3) * { * Acceleration acceleration = new Acceleration() * }*/ public TrendStatus CalculateTrend(IExchangeRate exchangeRate, int divisor = 3) { IDictionary <DateTime, double> stockDataPoints = exchangeRate.ExhangeHistory; if (stockDataPoints.Count() < MinimumSize && stockDataPoints.Count() < divisor) { return(TrendStatus.Keep); } IDictionary <DateTime, double> stockDataPointsDivided = exchangeRate.ExhangeHistory; DateTime now = DateTime.Now; IDictionary <double, double> stockDataPercentagePointsSeconds = new Dictionary <double, double>(); int count = 0; double previousValue = double.NaN; foreach (KeyValuePair <DateTime, double> entry in stockDataPoints) { if (double.IsNaN(previousValue)) { previousValue = entry.Value; continue; } if (count % divisor == 0) { stockDataPercentagePointsSeconds.Add((now - entry.Key).TotalSeconds, entry.Value == previousValue ? 0 : ((entry.Value - previousValue) / previousValue) * 100); } previousValue = entry.Value; } if (stockDataPercentagePointsSeconds.Count() < 2) { return(TrendStatus.Keep); } IDictionary <double, double> firstDerivatives; IDictionary <double, double> secondDerivatives; //CalculateDerivatives(stockDataPercentagePointsSeconds, out firstDerivatives, out secondDerivatives); /*String toString = String.Join("----", Enumerable.Range(0, stockDataPercentagePointsSeconds.Count).Select(index => * stockDataPercentagePointsSeconds.Values.ElementAt(index).ToString("N5") + ", " + firstDerivatives.Values.ElementAt(index).ToString("N5") + ", " + * secondDerivatives.Values.ElementAt(index).ToString("N5"))); */ /* * Console.WriteLine("\n"); * Console.WriteLine("," + + "," + + ","); * Console.WriteLine("\n"); * */ return(0); }
/// <summary> /// Set new IExchangeRate to use for next change /// </summary> /// <param name="newRate">NewIExchange to use</param> public void SetNewRate(IExchangeRate newRate) { if (newRate == null) { throw new ArgumentNullException("newRate"); } _rate = newRate; }
public void AddExchangeRate(IExchangeRate newRate) { if (this.exchangeRates.Contains(newRate)) { return; } this.exchangeRates.Add(newRate); }
//With exchange rate public Deposit(Account account, double amount, string currencyCode, string reference, BankDBContext context, IExchangeRate exchangeRate) { _account = account; _amount = amount; _currencyCode = currencyCode; _context = context; _reference = reference; _exchangeRate = exchangeRate; IsCommandCompleted = false; }
public async Task SendExchangeRateMessageAsync(Message message, IExchangeRate exchangeRate, ITelegramBotClient telegramBotClient) { await telegramBotClient.SendTextMessageAsync( chatId : message.Chat, text : $"{ exchangeRate.GetTargetCurrency() } / { exchangeRate.GetHomeCurrency() } : " + $"{ exchangeRate.GetRate() }", parseMode : ParseMode.Markdown, disableNotification : true, replyToMessageId : message.MessageId ); }
protected override void InitializeObject(IGenericEntity ent) { if (ent is IExchangeRate) { IExchangeRate exchangeRate = (IExchangeRate)ent; DBStoredProcedure spUpdate = new DBStoredProcedure(); spUpdate.ProcedureName = "catUpdateBudgetExchangeRate"; spUpdate.AddParameter(new DBParameter("@IdCategory", DbType.Int32, ParameterDirection.Input, exchangeRate.IdCategory)); spUpdate.AddParameter(new DBParameter("@Year", DbType.Int32, ParameterDirection.Input, exchangeRate.Year)); spUpdate.AddParameter(new DBParameter("@Rate", DbType.Decimal, ParameterDirection.Input, exchangeRate.Value)); spUpdate.AddParameter(new DBParameter("@IdCurrency", DbType.Decimal, ParameterDirection.Input, exchangeRate.IdCurrency)); this.AddStoredProcedure("UpdateObject", spUpdate); } }
/// <summary> /// Handles the OnChange event of the CurrencyCode control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void CurrencyCode_OnChange(object sender, EventArgs e) { IOpportunity opportunity = BindingSource.Current as IOpportunity; if (opportunity != null) { IExchangeRate exchangeRate = EntityFactory.GetById <IExchangeRate>(lueCurrencyCode.LookupResultValue); if (exchangeRate != null) { Double rate = exchangeRate.Rate.GetValueOrDefault(1); opportunity.ExchangeRate = rate; opportunity.ExchangeRateDate = DateTime.UtcNow; opportunity.ExchangeRateCode = lueCurrencyCode.LookupResultValue.ToString(); UpdateMultiCurrencyExchangeRate(opportunity, rate); } } }
/// <summary> /// Handles the OnChange event of the CurrencyCode control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void CurrencyCode_OnChange(object sender, EventArgs e) { ISalesOrder salesOrder = BindingSource.Current as ISalesOrder; if (salesOrder != null) { IExchangeRate exchangeRate = EntityFactory.GetById <IExchangeRate>(lueCurrencyCode.LookupResultValue); if (exchangeRate != null) { Double rate = exchangeRate.Rate.GetValueOrDefault(1); salesOrder.ExchangeRate = rate; salesOrder.ExchangeRateDate = DateTime.UtcNow; salesOrder.CurrencyCode = lueCurrencyCode.LookupResultValue.ToString(); UpdateMultiCurrencyExchangeRate(salesOrder, rate); } } }
public double GetChangePercentage(IExchangeRate exchangeRate) { IDictionary <DateTime, double> stockDataPoints = exchangeRate.ExhangeHistory; if (stockDataPoints.Count == 0) { return(double.NaN); } double end = stockDataPoints.First().Value; double start = stockDataPoints.Last().Value; if (start == end) { return(0.0); } return((start - end) / start); }
public static int SaveExchangeRate(IExchangeRate chg, int modifiedBy) { string strExecution = "[chg].[uspSaveExchangeRate]"; int result = 0; using (DbQuery oDq = new DbQuery(strExecution)) { oDq.AddIntegerParam("@ExchangeRateID", chg.ExchangeRateID); oDq.AddIntegerParam("@CompanyID", chg.CompanyID); oDq.AddDateTimeParam("@ExchangeDate", chg.ExchangeDate); oDq.AddDecimalParam("@USDExchangeRate", 10, 2, chg.USDExchangeRate); //oDq.AddIntegerParam("@FreeDays", chg.FreeDays); oDq.AddIntegerParam("@ModifiedBy", modifiedBy); oDq.AddIntegerParam("@Result", result, QueryParameterDirection.Output); oDq.RunActionQuery(); result = Convert.ToInt32(oDq.GetParaValue("@Result")); } return(result); }
public double GetChangePercentage(IExchangeRate exchangeRate, DateTime endDate, TimeSpan timeSpan) { IDictionary <DateTime, double> stockDataPoints = exchangeRate.ExhangeHistory; return(double.NaN); if (stockDataPoints.Count == 0 || endDate - timeSpan <= stockDataPoints.First().Key) { return(double.NaN); } double end = stockDataPoints.First(pair => pair.Key >= endDate - timeSpan).Value; double start = stockDataPoints.First(pair => pair.Key >= endDate).Value; if (start == end) { return(0.0); } return((start - end) / start); }
public string SaveExchangeRate(IExchangeRate exchangeRate, int modifiedBy) { exchangeRate.CompanyID = Constants.DEFAULT_COMPANY_ID; int result = 0; string errMessage = string.Empty; result = ChargeDAL.SaveExchangeRate(exchangeRate, modifiedBy); switch (result) { case 1: errMessage = ResourceManager.GetStringWithoutName("ERR00073"); break; default: break; } return(errMessage); }
public static IExchangeRate GetExchangeRate(int exchangeRateID, SearchCriteria searchCriteria) { string strExecution = "[chg].[uspGetExchangeRate]"; IExchangeRate chg = null; using (DbQuery oDq = new DbQuery(strExecution)) { oDq.AddIntegerParam("@ExchangeRateID", exchangeRateID); oDq.AddVarcharParam("@SortExpression", 50, searchCriteria.SortExpression); oDq.AddVarcharParam("@SortDirection", 4, searchCriteria.SortDirection); DataTableReader reader = oDq.GetTableReader(); while (reader.Read()) { chg = new ExchangeRateEntity(reader); } reader.Close(); } return(chg); }
protected void cmdOK_Click(object sender, EventArgs e) { IOpportunity opportunity = this.BindingSource.Current as IOpportunity; if (opportunity != null) { IExchangeRate exchRate = EntityFactory.GetById <IExchangeRate>(lveChangeRate.Text); try { opportunity.ExchangeRateCode = exchRate.Id.ToString(); opportunity.ExchangeRate = Convert.ToDouble(txtExchangeRate.Text); opportunity.Save(); } catch (Exception) { throw new ApplicationException(GetLocalResourceObject("Error_ChangingExchangeRate").ToString()); } } DialogService.CloseEventHappened(sender, e); Refresh(); }
protected void grdProducts_RowDataBound(object sender, GridViewRowEventArgs e) { string oppCurrencyCode; if (e.Row.RowType == DataControlRowType.DataRow) { // added for automation testing e.Row.Attributes.Add("id", string.Format("node_{0}", ((IProduct)((IOpportunityProduct)e.Row.DataItem).Product).Id)); IUserOptionsService userOption = ApplicationContext.Current.Services.Get <IUserOptionsService>(); if (userOption != null) { oppCurrencyCode = userOption.GetCommonOption("lveCurrency", "OpportunityDefaults"); if (string.IsNullOrEmpty(oppCurrencyCode)) { oppCurrencyCode = "USD"; } IExchangeRate rate = EntityFactory.GetById <IExchangeRate>(oppCurrencyCode); // Calculated Price Sage.SalesLogix.Web.Controls.Currency curr = (Sage.SalesLogix.Web.Controls.Currency)e.Row.FindControl("curCalcPriceMC"); if (curr != null) { curr.ExchangeRate = rate.Rate.GetValueOrDefault(1); curr.CurrentCode = rate.Id.ToString(); } //Extended Price Sage.SalesLogix.Web.Controls.Currency curExtPriceMC = (Sage.SalesLogix.Web.Controls.Currency)e.Row.FindControl("curExtPriceMC"); if (curExtPriceMC != null) { curExtPriceMC.ExchangeRate = rate.Rate.GetValueOrDefault(1); curExtPriceMC.CurrentCode = rate.Id.ToString(); } } } }
protected void GetExchangeRate(object sender, EventArgs e) { Sage.Entity.Interfaces.IOpportunity entity = this.BindingSource.Current as Sage.Entity.Interfaces.IOpportunity; //IExchangeRate exchRate = lveChangeRate.LookupResultValue as IExchangeRate; IExchangeRate exchRate = EntityFactory.GetById <IExchangeRate>(lveChangeRate.LookupResultValue); if (exchRate != null) { txtExchangeRate.Text = exchRate.Rate.ToString(); lblRateCurrent.Text = string.Format(GetLocalResourceObject("ThisRateCurrent_rsc").ToString(), Convert.ToString(exchRate.ModifyDate.Value.ToShortDateString())).ToString(); GetFromValues(); curTo.ExchangeRate = exchRate.Rate.GetValueOrDefault(1); curTo.CurrentCode = exchRate.Id.ToString(); curTo.Text = Convert.ToString(entity.SalesPotential); lveChangeRate.Text = exchRate.Id.ToString(); txtExchangeRate.Text = Convert.ToString(exchRate.Rate.GetValueOrDefault(1)); } blnGetValues = true; }
public ExchangeRateController(IExchangeRate iExchangeRate) { _iExchangeRate = iExchangeRate; }
public void Setup() { _config = program.InitConfiguration(); _exchangeRate = new ExchangeRate(_config); }
static void Main(string[] args) { if (args.Count() != 2) { Console.WriteLine("Error. Usage BinanceExecute.exe [binance key] [binance secret]"); Console.WriteLine("Press enter to exit"); Console.ReadLine(); Environment.Exit(0); } TimeSpan maxTradeData = TimeSpan.FromHours(12); TimeSpan refreshData = TimeSpan.FromSeconds(1); string key = args[0]; string secret = args[1]; var binanceClient = new BinanceClient.BinanceClient(key, secret); var binanceService = new BinanceService(binanceClient); IBinanceDataPool binanceDataPool = new BinanceDataPool(binanceService); binanceDataPool.Start(refreshData); List <ICurrency> allCurrencies = Currency.AllCurrencies.Where(curr => curr != Currency.UsDollar).ToList(); List <IExchangeRate> allExchangeRates = allCurrencies.Select(curr => (IExchangeRate) new ExchangeRate(curr, Currency.UsDollar, binanceDataPool, maxTradeData)).ToList(); IExchangeRate liteCoinExchangeRate = allExchangeRates.FirstOrDefault(exc => exc.ReferenceCurrency == Currency.UsDollar && exc.MainCurrency == Currency.LiteCoin); Account account = new Account(binanceDataPool, allCurrencies, allExchangeRates, maxTradeData); DoWork(account, refreshData, binanceDataPool, false); /* List<ITrade> trades = allCurrencies.Select(currency => allCurrencies. * Select(referenceCurrency => new KeyValuePair<ICurrency, ICurrency>(currency, referenceCurrency)). * Where(keyPairVal => keyPairVal.Key != keyPairVal.Value)). * SelectMany(keyPairVals => keyPairVals).Select(keyPairVal => * new Trade(binanceDataPool, keyPairVal.Key, keyPairVal.Value, allExchangeRates) as ITrade).ToList(); * */ /*IExchangeRate exchangeRate = new ExchangeRate(Currency.Ethereum, Currency.Bitcoin, binanceService, exchangeRatePool, maxTradeData); * Order order = new Order(exchangeRate, 0.0056, binanceService); * order.PlaceBuyOrder(); */ /* * var getAccount = binanceService.GetAccountAsync(); * Task.WaitAll(getAccount); * dynamic account = getAccount.Result; * Console.WriteLine(account);*/ //GET TICKER DEPTH /*var getDepth = binanceService.GetDepthAsync("BTCUSDT"); * Task.WaitAll(getDepth); * dynamic depth = getDepth.Result; * Console.WriteLine(depth);*/ /*IExchangeRatePool exchangeRatePool = new BinanceDataPool(binanceService); * exchangeRatePool.Start(TimeSpan.FromSeconds(0.5)); * * IExchangeRate bitCoinExchangeRate = new ExchangeRate(Currency.Bitcoin, Currency.UsDollar, binanceService, exchangeRatePool, maxTradeData); * IExchangeRate binanceCoinExchangeRate = new ExchangeRate(Currency.BinanceCoin, Currency.UsDollar, binanceService, exchangeRatePool, maxTradeData); * IExchangeRate ethereumExchangeRate = new ExchangeRate(Currency.Ethereum, Currency.UsDollar, binanceService, exchangeRatePool, maxTradeData); * IExchangeRate liteCoinExchangeRate = new ExchangeRate(Currency.LiteCoin, Currency.UsDollar, binanceService, exchangeRatePool, maxTradeData); * * * Thread.Sleep(500000);*/ /* * //GET ACCOUNT INFORMATION * var getAccount = binanceService.GetAccountAsync(); * Task.WaitAll(getAccount); * dynamic account = getAccount.Result; * Console.WriteLine(account); * * //GET ORDERS FOR SYMBOL * var getOrders = binanceService.GetOrdersAsync("BNBBTC", 100); * Task.WaitAll(getOrders); * dynamic orders = getOrders.Result; * Console.WriteLine(orders); * * //GET MY TRADES * var getMyTrades = binanceService.GetTradesAsync("WTCBTC"); * Task.WaitAll(getAccount); * dynamic trades = getMyTrades.Result; * Console.WriteLine(trades); * * //GET ALL PRICES * List<Prices> prices = new List<Prices>(); * prices = binanceService.ListPrices(); * Console.WriteLine(prices);*/ //GET PRICE OF SYMBOL /*double symbol = binanceService.GetPriceOfSymbol("BTCUSDT"); * Console.WriteLine("Price of BNB: " + symbol);*/ /*//PLACE BUY ORDER * var placeBuyOrder = binanceService.PlaceBuyOrderAsync("NEOBTC", 1.00, 00.008851); * Task.WaitAll(placeBuyOrder); * dynamic buyOrderResult = placeBuyOrder.Result; * Console.WriteLine(buyOrderResult); * * //PLACE SELL ORDER * var placeSellOrder = binanceService.PlaceSellOrderAsync("NEOBTC", 1.00, 00.008851); * Task.WaitAll(placeSellOrder); * dynamic sellOrderResult = placeSellOrder.Result; * Console.WriteLine(sellOrderResult); * * //TEST ORDER--------------------------------------------------------------------------- * var placeOrderTest = binanceService.PlaceTestOrderAsync("NEOBTC", "SELL", 1.00, 00.006151); * Task.WaitAll(placeOrderTest); * dynamic testOrderResult = placeOrderTest.Result; * Console.WriteLine(testOrderResult); * //------------------------------------------------------------------------------------- * * //CHECK ORDER STATUS BY ID * var checkOrder = binanceService.CheckOrderStatusAsync("NEOBTC", 5436663); * Task.WaitAll(checkOrder); * dynamic checkOrderResult = checkOrder.Result; * Console.WriteLine(checkOrderResult); * * //DELETE ORDER BY ID * var deleteOrder = binanceService.CancelOrderAsync("NEOBTC", 5436663); * Task.WaitAll(deleteOrder); * dynamic deleteOrderResult = deleteOrder.Result; * Console.WriteLine(deleteOrderResult);*/ Console.ReadLine(); }
/* * public static void WatchHoldings(IAccount account, List<IExchangeRate> allExchangeRates, List<ICurrency> allCurrencies, IBinanceDataPool binanceDataPool) * { * double exchangeCommission = 0.005; * * Object listLocker = new object(); * * List<KeyValuePair<ICurrency, Task>> orderTasks = new List<KeyValuePair<ICurrency, Task>>(); * List<KeyValuePair<ICurrency, CancellationToken>> cancellationTokens = new List<KeyValuePair<ICurrency, CancellationToken>>(); * while (true) * { * account.RefreshHoldings(); * * List<ICurrency> ownedCurrencies = account.Balances.Keys.Except(Currency.CurrenciesToTrade).ToList(); * List<IExchangeRate> ownedExchangeRates = allExchangeRates.Where(exch => * ownedCurrencies.Any(curr => curr == exch.MainCurrency && exch.ReferenceCurrency == Currency.UsDollar)).ToList(); * * IDictionary<IExchangeRate, Trend.TrendStatus> statuses = new Dictionary<IExchangeRate, Trend.TrendStatus>(); * foreach (var ownedExchangeRate in ownedExchangeRates) * { * lock (listLocker) * { * if (orderTasks.Any(orderTask1 => orderTask1.Key == ownedExchangeRate.MainCurrency)) * { * continue; * } * } * * ITrend trend = new Trend(); * Trend.TrendStatus action = trend.GetTrendStatus( * ownedExchangeRate, account.InitialBalancesInUsd[ownedExchangeRate.MainCurrency], account.BalancesInUsd[ownedExchangeRate.MainCurrency], 0.01, 0.1); * statuses.Add(ownedExchangeRate, action); * * * if (action == Trend.TrendStatus.Keep) * { * continue; * } * * Task orderTask = null; * CancellationToken token = new CancellationToken(false); * Order order = new Order(ownedExchangeRate, account.Balances[ownedExchangeRate.MainCurrency] * 0.90, binanceDataPool); * switch (action) * { * case Trend.TrendStatus.Buy: * { * orderTask = new Task(() => * { * order.PlaceBuyOrder(); * }, token); * * } * break; * case Trend.TrendStatus.BuyNow: * { * orderTask = new Task(() => * { * order.PlaceBuyOrder(); * }); * } * break; * case Trend.TrendStatus.SellNow: * { * orderTask = new Task(() => * { * order.PlaceSellOrder(); * }); * } * break; * case Trend.TrendStatus.Sell: * { * orderTask = new Task(() => * { * order.PlaceSellOrder(); * ; * }); * } * break; * } * * if (orderTask == null) * { * continue; * } * * orderTask.ContinueWith((task, state) => * { * lock (listLocker) * { * orderTasks.RemoveAll(orderTask1 => orderTask1.Key == ownedExchangeRate.MainCurrency); * cancellationTokens.RemoveAll(orderTask1 => orderTask1.Key == ownedExchangeRate.MainCurrency); * } * }, null); * * lock (listLocker) * { * orderTasks.Add(new KeyValuePair<ICurrency, Task>(ownedExchangeRate.MainCurrency, orderTask)); * cancellationTokens.Add(new KeyValuePair<ICurrency, CancellationToken>(ownedExchangeRate.MainCurrency, token)); * } * orderTask.Start(); * } * } * } * * */ public static void DoWork(IAccount account, TimeSpan refreshRate, IBinanceDataPool binanceDataPool, bool trade) { Console.WriteLine("Hi, I provide this software \"as is\" free of charge to the crypto community."); Console.WriteLine("However, feel free to send any gratuaty to Ethereum (ETH) 0xcb6803b1afa702c220144cf3828c356e936291f9"); Console.WriteLine(""); int rowsOfInitialText = 3; double exchangeCommission = 0.005; TimeSpan sizeOfTrend = TimeSpan.FromMinutes(1); IDictionary <ICurrency, Trend.TrendStatus> trends = account.SupportedCurrencies.ToDictionary (currency => (ICurrency)currency, currency => Trend.TrendStatus.NotEnoughData); Object listLocker = new object(); List <KeyValuePair <ICurrency, Task> > orderTasks = new List <KeyValuePair <ICurrency, Task> >(); List <KeyValuePair <ICurrency, CancellationToken> > cancellationTokens = new List <KeyValuePair <ICurrency, CancellationToken> >(); while (true) { account.RefreshHoldings(); List <ICurrency> ownedCurrencies = account.Balances.Keys.ToList(); IDictionary <ICurrency, double> balancesUsd = account.BalancesInUsd; foreach (var balance in balancesUsd) { int currencyIndex = balancesUsd.Keys.ToList().IndexOf(balance.Key); IExchangeRate ownedExchangeRate = account.ExchangeRates.First(exch => exch.MainCurrency == balance.Key && exch.ReferenceCurrency == Currency.UsDollar); ITrend trend = new Trend(); DateTime now = DateTime.Now; double dataPointHalfMinute = trend.GetChangePercentage(ownedExchangeRate, TimeSpan.FromSeconds(30)) * 100.0; double dataPoint1Minutes = trend.GetChangePercentage(ownedExchangeRate, TimeSpan.FromMinutes(1)) * 100.0; double dataPoint5Minutes = trend.GetChangePercentage(ownedExchangeRate, TimeSpan.FromMinutes(5)) * 100.0; double dataPoin30Minutes = trend.GetChangePercentage(ownedExchangeRate, TimeSpan.FromMinutes(30)) * 100.0; double dataPoin60Minutes = trend.GetChangePercentage(ownedExchangeRate, TimeSpan.FromMinutes(60)) * 100.0; double dataPoinLifeTime = trend.GetChangePercentage(ownedExchangeRate, TimeSpan.FromHours(24)) * 100.0; double currencyBalance = (account.BalancesInUsd[ownedExchangeRate.MainCurrency] - account.InitialBalancesInUsd[ownedExchangeRate.MainCurrency]); double percentageGrowth = trend.GetChangePercentage(ownedExchangeRate) * 100.0; Trend.TrendStatus action = trends[balance.Key] = trend.GetTrendStatus(ownedExchangeRate, TimeSpan.FromMinutes(1), account.InitialBalancesInUsd[ownedExchangeRate.MainCurrency], account.BalancesInUsd[ownedExchangeRate.MainCurrency], 0.01, 0.3); List <WriteLineStruct> writeLineList = new List <WriteLineStruct>() { new WriteLineStruct() { Text = (ownedExchangeRate.MainCurrency.Symbol + " : ${0:0.00}, "), Value = account.BalancesInUsd[ownedExchangeRate.MainCurrency], Threshold = double.NaN }, new WriteLineStruct() { Text = "Initial Value : $ : ${0:0.00}, ", Value = account.InitialBalancesInUsd[ownedExchangeRate.MainCurrency], Threshold = double.NaN }, new WriteLineStruct() { Text = "Change : ${0:0.00}, ", Value = currencyBalance, Threshold = 1.0 }, new WriteLineStruct() { Text = "Growth : {0:0.00}%, ", Value = percentageGrowth, Threshold = 0.1 }, new WriteLineStruct() { Text = "Unit Price : ${0:0.00}, ", Value = ownedExchangeRate.Price, Threshold = double.NaN }, new WriteLineStruct() { Text = (action + ", ").PadRight(10), Value = (int)action, Threshold = 0.9 }, new WriteLineStruct() { Text = !double.IsNaN(dataPointHalfMinute) ? "----30 Seconds Change : {0:0.00}%, " : "", Value = dataPointHalfMinute, Threshold = 1.0 }, new WriteLineStruct() { Text = !double.IsNaN(dataPoint1Minutes) ?"1 Minute Change : {0:0.00}%, " : "", Value = dataPoint1Minutes, Threshold = 1.0 }, new WriteLineStruct() { Text = !double.IsNaN(dataPoint5Minutes) ?"5 Minute Change : {0:0.00}%, " : "", Value = dataPoint5Minutes, Threshold = 1.0 }, new WriteLineStruct() { Text = !double.IsNaN(dataPoin30Minutes) ?"30 Minute Change : {0:0.00}%, " : "", Value = dataPoin30Minutes, Threshold = 1.0 }, new WriteLineStruct() { Text = !double.IsNaN(dataPoin60Minutes) ?"60 Minute Change : {0:0.00}%, " : "", Value = dataPoin60Minutes, Threshold = 1.0 }, new WriteLineStruct() { Text = !double.IsNaN(dataPoinLifeTime) ?"Ever Change : {0:0.00}%, " : "", Value = dataPoinLifeTime, Threshold = 1.0 }, }; WriteLine(writeLineList, currencyIndex + rowsOfInitialText); if (!trade) { continue; } lock (listLocker) { if (orderTasks.Any(orderTask1 => orderTask1.Key == ownedExchangeRate.MainCurrency)) { continue; } } if (action == Trend.TrendStatus.Keep) { continue; } CancellationToken token = new CancellationToken(false); Order order = new Order(ownedExchangeRate.ExchangeRateSymbol, account.Balances[ownedExchangeRate.MainCurrency], binanceDataPool); Task orderTask = new Task(() => { switch (action) { case Trend.TrendStatus.BuyNow: { order.PlaceBuyOrder(ownedExchangeRate.Price * 1.01); } break; case Trend.TrendStatus.Buy: { order.PlaceBuyOrder(ownedExchangeRate.Price); } break; case Trend.TrendStatus.SellNow: { order.PlaceSellOrder(ownedExchangeRate.Price); } break; case Trend.TrendStatus.Sell: { order.PlaceSellOrder(ownedExchangeRate.Price * 0.99); } break; } }, token); if (orderTask == null) { continue; } orderTask.ContinueWith((task, state) => { lock (listLocker) { orderTasks.RemoveAll(orderTask1 => orderTask1.Key == ownedExchangeRate.MainCurrency); cancellationTokens.RemoveAll(orderTask1 => orderTask1.Key == ownedExchangeRate.MainCurrency); } }, null); lock (listLocker) { orderTasks.Add(new KeyValuePair <ICurrency, Task>(ownedExchangeRate.MainCurrency, orderTask)); cancellationTokens.Add(new KeyValuePair <ICurrency, CancellationToken>(ownedExchangeRate.MainCurrency, token)); } orderTask.Start(); } List <WriteLineStruct> writeLineListEnd = new List <WriteLineStruct>() { new WriteLineStruct() { Text = ("Account Total : ${0:0.00}, "), Value = account.AccountTotalInUsd, Threshold = double.NaN }, new WriteLineStruct() { Text = "Initial Account Total : ${0:0.00}, ", Value = account.InitialAccountTotalInUsd, Threshold = double.NaN }, new WriteLineStruct() { Text = "Change Account Total : ${0:0.00}, ", Value = account.ChangeAccountTotalInUsd, Threshold = 1.0 }, }; WriteLine(writeLineListEnd, ownedCurrencies.Count + rowsOfInitialText); Thread.Sleep(refreshRate); } ; }
/* public void CalculateDerivatives(IDictionary<double, double> inputPoints, out IDictionary<double, double> firstDerivatives, * out IDictionary<double, double> secondDerivatives) * { * * var inputPointsXArray = inputPoints.Keys.ToArray(); * var inputPointsYArray = inputPoints.Values.ToArray(); * * spline1dinterpolant akimaSplineToDifferentiate; * alglib.spline1dbuildakima(inputPointsXArray, inputPointsYArray, out akimaSplineToDifferentiate); * * firstDerivatives = new Dictionary<double, double>(); * secondDerivatives = new Dictionary<double, double>(); * foreach (var pair in inputPoints) * { * var xPoint = pair.Key; * double functionVal, firstDeriv, secondDeriv; * alglib.spline1ddiff(akimaSplineToDifferentiate, xPoint, out functionVal, out firstDeriv, out secondDeriv); * * firstDerivatives.Add(xPoint, firstDeriv); * secondDerivatives.Add(xPoint, secondDeriv); * } * }*/ public TrendStatus GetTrendStatus(IExchangeRate exchangeRate, TimeSpan trendSpan, double initialValue, double currentValue, double limitCommission, double lossTolerance) { const int divider = 3; IDictionary <DateTime, double> stockDataPoints = exchangeRate.ExhangeHistory; DateTime now = DateTime.Now; List <KeyValuePair <DateTime, double> > stockDataPercentagePointsSeconds = new List <KeyValuePair <DateTime, double> >(); List <double> rankings = new List <double>(); for (int sample = 1; sample < 10; sample *= 2) { rankings.Add(GetChangePercentage(exchangeRate, now - (trendSpan *= sample), trendSpan)); } rankings.RemoveAll(ranking => double.IsNaN(ranking)); if (rankings.Count < 1) { return(TrendStatus.NotEnoughData); //Not enough data } double gainLossPercentage = (currentValue - initialValue) / currentValue; double expectedGain = gainLossPercentage - limitCommission; int sets = (int)Math.Floor(rankings.Count / (double)divider); if (Math.Abs(expectedGain) < limitCommission) { return(TrendStatus.Keep); // A stable asset, we should sell if we have better options } else if (expectedGain > limitCommission) { if (rankings.Count < divider) { return(TrendStatus.NotEnoughData); //Not enough data } if (rankings.Count < divider) { return(TrendStatus.NotEnoughData); //Not enough data } if (rankings.All(ranking => ranking > 0)) { return(TrendStatus.Buy); // A asset on the rise, keep it } if (Math.Abs(rankings.Last()) < limitCommission) { return(TrendStatus.Keep); } if (rankings.Last() < -limitCommission) { return(TrendStatus.Sell); } if (rankings.Last() > limitCommission) { return(TrendStatus.Keep); } } else { if (expectedGain < -lossTolerance || rankings.First() < -lossTolerance) { return(TrendStatus.SellNow); } if (rankings.Count < divider) { return(TrendStatus.NotEnoughData); //Not enough data } if (rankings.All(ranking => ranking > 0)) { return(TrendStatus.Buy); // A asset on the rise, keep it } if (Math.Abs(rankings.Last()) < limitCommission) { return(TrendStatus.Buy); } return(TrendStatus.Keep); // We dont sell on a loss } return(TrendStatus.Inconlusive); /* IDictionary<double, double> firstDerivatives; * IDictionary<double, double> secondDerivatives; * * CalculateDerivatives(stockDataPercentagePointsSeconds, out firstDerivatives, out secondDerivatives);*/ }
public double GetChangePercentage(IExchangeRate exchangeRate, TimeSpan span) { return(GetChangePercentage(exchangeRate, DateTime.Now, span)); }
private ExchangeCurrency(string initialCurrency, string targetCurrency, IExchangeRate rate) { _firstCurrency = initialCurrency; _secondCurrency = targetCurrency; _rate = rate; }