async Task <ulong> PostOrder(CurrencyPair currencyPair, OrderType orderType, decimal rate, decimal amount) { var postData = new Dictionary <string, string> { { "currencyPair", currencyPair.ToString() }, { "rate", rate.ToString() }, { "amount", amount.ToString() } }; string command; if (orderType == OrderType.Buy) { command = "buy"; } else if (orderType == OrderType.Sell) { command = "sell"; } else { throw new Exception("Unrecognized Ordertype in PostOrder"); } var response = await ApiHttpClient.PostData <JObject>(command, ApiUrlHttpsRelativeTrading, postData); return(response.Value <ulong>("orderNumber")); }
private async void MyOpenOrder(string curencyP) { if (curencyP != "") { CurrencyPair c = CurrencyPair.Parse(curencyP); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); var trades = await PC.Trading.GetOpenOrdersAsync(c); if (trades.Count > 0) { foreach (var tr in trades) { InfoView.Rows.Add(c.ToString(), tr.IdOrder, (decimal)tr.AmountBase, (decimal)tr.AmountQuote, (decimal)tr.PricePerCoin, tr.Type); } } sw.Stop(); TimeControls.Text = "Time: " + sw.ElapsedMilliseconds / 100.0; } else { var trades = await PC.Trading.GetOpenOrdersAllAsync(); //if (trades.Count > 0) //foreach (var tr in trades) //{ // InfoView.Rows.Add( tr.IdOrder, (decimal)tr.AmountBase, (decimal)tr.AmountQuote, (decimal)tr.PricePerCoin, tr.Type); //} } }
public void PrintStatistics(CurrencyPair pair) { IBitcoinPrice allHistoryMax = this._repositoryService.Max(pair); IBitcoinPrice allHistoryMin = this._repositoryService.Min(pair); Console.WriteLine(pair.ToString()); Console.WriteLine("-------"); decimal price = this._repositoryService.GetLastValue(pair, out TrendType trend); Console.ForegroundColor = trend == TrendType.Up ? ConsoleColor.Green : ConsoleColor.Red; Console.WriteLine("LAST: {0:N2}", price); Console.ResetColor(); Console.WriteLine(); Console.WriteLine("AVERAGE: {0:N2}", this._repositoryService.GetAggregatedValue(RepositoryService.AggregateType.Average, pair)); Console.WriteLine("MAX: {0:N2} at {1} (UTC)", allHistoryMax.Value, allHistoryMax.Timestamp.DateTimeFromUnixTimestampSeconds()); Console.WriteLine("MIX: {0:N2} at {1} (UTC)", allHistoryMin.Value, allHistoryMin.Timestamp.DateTimeFromUnixTimestampSeconds()); Console.WriteLine(); Console.WriteLine("Last {0} prices", this._printoutServiceOptions.LastPrices); Console.WriteLine("-------------"); Console.WriteLine("AVERAGE: {0:N2}", this._repositoryService.GetAggregatedValue(RepositoryService.AggregateType.Average, pair, this._printoutServiceOptions.LastPrices)); Console.WriteLine("MAX: {0:N2}", this._repositoryService.GetAggregatedValue(RepositoryService.AggregateType.Max, pair, this._printoutServiceOptions.LastPrices)); Console.WriteLine("MIX: {0:N2}", this._repositoryService.GetAggregatedValue(RepositoryService.AggregateType.Min, pair, this._printoutServiceOptions.LastPrices)); Console.WriteLine(); Console.WriteLine("Last {0} minutes", this._printoutServiceOptions.LastMinutes); Console.WriteLine("--------------"); Console.WriteLine("AVERAGE: {0:N2}", this._repositoryService.GetAggregatedValue(RepositoryService.AggregateType.Average, pair, x => x.Timestamp.BelongsToLastMinutes(this._printoutServiceOptions.LastMinutes))); Console.WriteLine("MAX: {0:N2}", this._repositoryService.GetAggregatedValue(RepositoryService.AggregateType.Max, pair, x => x.Timestamp.BelongsToLastMinutes(this._printoutServiceOptions.LastMinutes))); Console.WriteLine("MIX: {0:N2}", this._repositoryService.GetAggregatedValue(RepositoryService.AggregateType.Min, pair, x => x.Timestamp.BelongsToLastMinutes(this._printoutServiceOptions.LastMinutes))); }
private void button5_Click_1(object sender, EventArgs e) { double testProfit = 1, profit2 = 1, profitper = 2; bool fl = true, fl2 = true; infoPeriod(); int mPer = GraphsPer(graphsper2.SelectedIndex); int d = int.Parse(perdayrs.Text); int inrv = int.Parse(intervRSI.Text); double diff, diffOld; CurrencyPair cp = new CurrencyPair(BaseCur.Text, QuoteCur.Text); IList <IMarketChartData> er; er = PC.Markets.GetChartDataAsync(cp, (MarketPeriod)mPer, DateTime.Now.AddDays(-d), DateTime.Now).Result; var r = RSI(er, inrv); for (int i = 0; i < r.Count; i++) { InfoView.Rows.Add(i, cp.ToString(), (decimal)r[i].High, (decimal)r[i].Low, r[i].Time, (decimal)r[i].VolumeBase, (decimal)r[i].VolumeQuote, (decimal)r[i].WeightedAverage, (decimal)r[i].Open, (decimal)r[i].Close, (decimal)r[i].Ema); } for (int j = 2; j <= 25; j++) { Loger.SetLog("----------- " + j + " ---------------- "); var l = RSI(er, j); for (int i = 0; i < l.Count; i++) { Loger.SetLog(l[i].Time + " " + string.Format("{0:0.000}", ((decimal)l[i].Close)) + " " + l[i].Ema); } Loger.SetLog("--------------------------- \r\n"); } }
public async Task <OhlcSeries> ReadOhlcSeries(CurrencyPair currencyPair, DateTime startTime, DateTime endTime, int ohlcTimeSpanSeconds) { // Request chart data const string command = "returnChartData"; var parameters = new Dictionary <string, string> { // TODO: Map global currency pair to poloniex currency pair instead of expecting these to be equal { "currencyPair", currencyPair.ToString() }, { "start", DateTimeHelper.ToUnixTime(startTime).ToString() }, { "end", DateTimeHelper.ToUnixTime(endTime).ToString() }, { "period", ohlcTimeSpanSeconds.ToString() } }; var chartData = await _dataRetriever.PerformRequest <IList <MarketChartData> >(ServerUrl, command, parameters); // Convert chart data to OhlcSeries var ohlcItems = ImmutableList.CreateBuilder <OhlcItem>(); foreach (var chartItem in chartData.Reverse()) { var startOhlc = DateTimeHelper.ToUnixTime(chartItem.Time); var ohlcItem = new OhlcItem(startOhlc, startOhlc, chartItem.High, chartItem.Low, chartItem.Open, chartItem.Close); ohlcItems.Add(ohlcItem); } return(new OhlcSeries(ohlcTimeSpanSeconds, ohlcItems.ToImmutable())); }
public void Update(CurrencyAssetStaticsDataBase CcyDB) { Rows.Clear(); ColumnCount = 5; Columns[0].HeaderText = "Name"; Columns[1].HeaderText = "Symbol"; Columns[2].HeaderText = "Decimal Number"; Columns[3].HeaderText = "Thousand Marker"; Columns[4].HeaderText = "Pricing CcyPair"; for (int i = 0; i < ColumnCount; i++) { Columns[i].Width = i == 0 ? 50 : 75; Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable; } AllowUserToAddRows = false; foreach (var item in CcyDB.DataBase) { CurrencyPair cp = item.PricingCcyPair; string cpStr = cp == null ? "Ref. Ccy" : cp.ToString(); object[] values = { item.Name, item.Symbol, item.DecimalNumber, item.ThousandMark, cpStr }; Rows.Add(values); } _Memo = CcyDB; Rows[0].DefaultCellStyle.BackColor = Color.FromArgb(200, 200, 200); ClearSelection(); }
/// <summary> /// Request the OHLC data from Kraken (looping requests if needed) /// </summary> /// <param name="curPair"></param> /// <param name="freq"></param> /// <param name="count"></param> /// <returns></returns> private GetOHLCResult GetKrakenOHLC(CurrencyPair curPair, Frequency freq = Frequency.Hour4, int count = 10) { this.PublishInfo($"Kraken API Request : OHLC {curPair.ToString()} - {freq.ToString()}"); try { return(KrakenApi.GetOHLC(curPair.GetRequestID(), freq.GetFrequency())); } catch (System.Net.WebException wex) { this.PublishError(wex.Message); // No Internet => wex.Message = "The remote name could not be resolved: 'api.kraken.com'" count--; if (count < 1) { throw new Exception($"Unable to Download Krarken OHLC for: {curPair.ToString()}"); } else { System.Threading.Thread.Sleep(5000); } return(GetKrakenOHLC(curPair, freq, count)); } }
private static RestRequest BuildProductRequest(string ressource, Method method, CurrencyPair currencyPair) { var request = new RestRequest($"/products/{{productId}}/{ressource}", Method.GET); var productId = currencyPair.ToString().ToUpper().Insert(3, "-"); request.AddUrlSegment("productId", productId); return(request); }
/* private IList<IOrder> GetOpenOrders(CurrencyPair currencyPair) * { * var postData = new Dictionary<string, string> { * { "currencyPair", currencyPair.ToString() } * }; * * var data = PostData<IList<Order>>("returnOpenOrders", postData); * return (IList<IOrder>)data; * }*/ /*public Task<IEnumerable<Trade>> GetTradesAsync(CurrencyPair currencyPair) * { * return GetTrades(currencyPair, Helper.DateTimeUnixEpochStart, DateTime.MaxValue); * }*/ public Task <IEnumerable <Trade> > GetTrades(CurrencyPair currencyPair, DateTime startTime, DateTime endTime) { var postData = new Dictionary <string, string> { { "currencyPair", currencyPair.ToString() }, { "start", NonceCalculator.DateTimeToUnixTimeStamp(startTime).ToString() }, { "end", NonceCalculator.DateTimeToUnixTimeStamp(endTime).ToString() } }; return(ApiHttpClient.PostData <IEnumerable <Trade> >("returnTradeHistory", ApiUrlHttpsRelativeTrading, postData)); }
private IList <IOrder> GetOpenOrders(CurrencyPair currencyPair) { var postData = new Dictionary <string, string> { { "currencyPair", currencyPair.ToString() } }; var data = PostData <IList <Order> >("returnOpenOrders", postData); return((IList <IOrder>)data); }
private async Task <bool> DeleteOrder(CurrencyPair currencyPair, ulong orderId) { var postData = new Dictionary <string, string> { { "currencyPair", currencyPair.ToString() }, { "orderNumber", orderId.ToString() } }; var data = await PostData <JObject>("cancelOrder", postData); return(data.Value <byte>("success") == 1); }
public async Task <bool> CancelOrder(CurrencyPair currencyPair, ulong orderNumber) { var postData = new Dictionary <string, string> { { "currencyPair", currencyPair.ToString() }, { "orderNumber", orderNumber.ToString() } }; var data = await ApiHttpClient.PostData <JObject>("cancelOrder", ApiUrlHttpsRelativeTrading, postData); return(data.Value <byte>("success") == 1); }
public Trade(string[] jsonTrds, string last, CurrencyPair pair) { UnixTime = Convert.ToDecimal(jsonTrds[2]); Time = GetTime(Convert.ToDouble(jsonTrds[2])); Pair = pair.ToString(); Price = Convert.ToDecimal(jsonTrds[0]); Volume = Convert.ToDecimal(jsonTrds[1]); Direction = jsonTrds[3]; Type = jsonTrds[4]; Miscellaneous = jsonTrds[5]; LastTradeId = Convert.ToInt64(last); }
private async Task <ulong> PostOrder(CurrencyPair currencyPair, OrderType type, double pricePerCoin, double amountQuote) { var postData = new Dictionary <string, string> { { "currencyPair", currencyPair.ToString() }, { "rate", pricePerCoin.ToStringNormalized() }, { "amount", amountQuote.ToStringNormalized() } }; var data = await PostData <JObject>(type.ToStringNormalized(), postData); return(data.Value <ulong>("orderNumber")); }
private async Task <IEnumerable <Trade> > GetTrades(CurrencyPair currencyPair, DateTime startTime, DateTime endTime) { var postData = new Dictionary <string, string> { { "currencyPair", currencyPair.ToString() }, { "start", Helper.DateTimeToUnixTimeStamp(startTime).ToString() }, { "end", Helper.DateTimeToUnixTimeStamp(endTime).ToString() } }; var data = await PostData <IEnumerable <Trade> >("returnTradeHistory", postData); return(data); }
private Security GetSecurityFromCurrencyPair(CurrencyPair pair) { return(new Security { AssetClass = "CURRENCY", BaseCurrency = pair.BaseCurrency, ContractSize = 1, //! unknown DataFeed = Name, Digit = 8, MarginRate = 1, //! unknown MarketOpen = TimeSpan.Zero, //! unknown MarketClose = TimeSpan.Zero, //! unknown MaxPosition = 100000, //! unknown Name = pair.ToString(), PriceIncrement = 0.00000001M, //! unknown QtyIncrement = 0.0001M, //! unknown SecurityId = pair.Id, Symbol = pair.ToString(), UnitOfMeasure = pair.QuoteCurrency, UnitPrice = 1 //! unknown }); }
public TradeHistory(CurrencyPair currencyPair, int _selectedIndex = 0) { InitializeComponent(); // Set icon from the assembly this.Icon = System.Drawing.Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location).ToImageSource(); PoloniexClient = PoloniexClient.Instance(ApiKeys.PublicKey, ApiKeys.PrivateKey); CurrencyPair = currencyPair; Title = string.Concat("Trade History", "(", CurrencyPair.ToString(), ")"); tabControl.SelectedIndex = _selectedIndex; }
private TickersByExchange GetTickersByExchange(CurrencyPair pair) { TickersByExchange tickers = new TickersByExchange(); foreach (ExchangeApi tradeApi in apiManager.AllExchangeApi) { if (tradeApi.SelectedPairs.Contains(pair)) { var ticker = tradeApi.SelectedTickers[pair.ToString()]; tickers.Add(ticker); } } return(tickers); }
public string[] Serialize() { string[] data = { pair.ToString(), buyTimestamp.ToString(), buyAmountQuote.ToString("F8"), buyPrice.ToString("F8"), sellTimestamp.ToString(), sellAmountQuote.ToString("F8"), sellPrice.ToString("F8") }; return(data); }
public ChartWindow(CurrencyPair currencyPair) { InitializeComponent(); // Set icon from the assembly Icon = System.Drawing.Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location).ToImageSource(); PoloniexClient = PoloniexClient.Instance(ApiKeys.PublicKey, ApiKeys.PrivateKey); CurrencyPair = currencyPair; Title = string.Concat("History ", "(", CurrencyPair.ToString(), ")"); LoadChart(); }
static BlackFxOptionInterpolatedNodalSurfaceVolatilitiesSpecificationTest() { ImmutableList.Builder <FxOptionVolatilitiesNode> nodeBuilder = ImmutableList.builder(); ImmutableList.Builder <QuoteId> quoteIdBuilder = ImmutableList.builder(); for (int i = 0; i < TENORS.Count; ++i) { for (int j = 0; j < STRIKES.Count; ++j) { QuoteId quoteId = QuoteId.of(StandardId.of("OG", GBP_USD.ToString() + "_" + TENORS[i].ToString() + "_" + STRIKES[j])); nodeBuilder.add(FxOptionVolatilitiesNode.of(GBP_USD, SPOT_OFFSET, BDA, ValueType.BLACK_VOLATILITY, quoteId, TENORS[i], SimpleStrike.of(STRIKES[j]))); quoteIdBuilder.add(quoteId); } } NODES = nodeBuilder.build(); QUOTE_IDS = quoteIdBuilder.build(); }
public void LoadGraph(CurrencyPair currencyPair, IList <IMarketChartData> chartData) { GraphPane myPane = zgc1.GraphPane; myPane.Title.Text = "Candlestick Chart " + currencyPair.ToString(); myPane.XAxis.Title.Text = "Date"; myPane.YAxis.Title.Text = "Price " + currencyPair.BaseCurrency; StockPointList spl = new StockPointList(); Random rand = new Random(); foreach (var data in chartData) { var xDate = new XDate(data.Time.Year, data.Time.Month, data.Time.Day, data.Time.Hour, data.Time.Minute, data.Time.Second); double x = xDate; double close = data.Close; double hi = data.High; double low = data.Low; double open = data.Open; StockPt pt = new StockPt(x, hi, low, open, close, data.VolumeBase); spl.Add(pt); } JapaneseCandleStickItem myCurve = myPane.AddJapaneseCandleStick("Price", spl); myCurve.Stick.IsAutoSize = true; myCurve.Stick.Color = System.Drawing.Color.Red; // Use DateAsOrdinal to skip weekend gaps myPane.XAxis.Type = AxisType.Date; // pretty it up a little myPane.Chart.Fill = new Fill(System.Drawing.Color.WhiteSmoke, System.Drawing.Color.Gray, 45.0f); myPane.Fill = new Fill(System.Drawing.Color.WhiteSmoke, System.Drawing.Color.DarkOrange); zgc1.AxisChange(); zgc1.Refresh(); zgc1.Update(); zgc1.IsShowCursorValues = true; this.UpdateLayout(); IsGraphLoaded = true; }
private void SmaAlgo_Click(object sender, EventArgs e) { infoPeriod(); int d = int.Parse(numDay.Text); int mPer = GraphsPer(MPeriod.SelectedIndex); CurrencyPair cp = new CurrencyPair("USDT", "BTC"); var er = PC.Markets.GetChartDataAsync(cp, (MarketPeriod)mPer, DateTime.Now.AddDays(-d), DateTime.Now); int i = 0; foreach (var ter in SmaAl.SMA(er.Result)) { i++; InfoView.Rows.Add(i, cp.ToString(), (decimal)ter.Open, (decimal)ter.Close, (decimal)ter.High, (decimal)ter.Low, ter.Time, (decimal)ter.VolumeBase, (decimal)ter.VolumeQuote, (decimal)ter.WeightedAverage); } InfoView.Rows[InfoView.RowCount - 2].DefaultCellStyle.BackColor = Color.AliceBlue; }
public Tick GetCurrentPrice(CurrencyPair currencyPair) { if (status == BootupStatus.Initialized) { if (map.TryGetValue(currencyPair, out var tick)) { return(tick); } else { throw new KeyNotFoundException($"Could not find {currencyPair.ToString()} in the Ticker"); } } else { throw new UnauthorizedAccessException("Must call and await \"Markets.Initialize() before accessing CurrencyPairs"); } }
public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node) { if ( (!IsInvocation || IsArgumentList) && CurrencyPair.TryParse(node.Identifier.ValueText, out var currentPair)) { var replacedPair = new CurrencyPair(left: currentPair.Left == "X" ? pair.Left : currentPair.Left, right: currentPair.Right == "X" ? pair.Right : currentPair.Right); if (IsInvocation) // eg. replace bittrex(BTC_X) to bittrex(BTC_USD) { ExchangeRates.Add(new ExchangeRate() { CurrencyPair = replacedPair, Exchange = _ExchangeName }); return(SyntaxFactory.IdentifierName(replacedPair.ToString())); } else // eg. replace BTC_X to BTC_USD, then replace by the expression for BTC_USD { var bestCandidate = parent.FindBestCandidate(replacedPair); if (nested > MaxNestedCount) { Errors.Add(RateRulesErrors.TooMuchNestedCalls); return(RateRules.CreateExpression($"ERR_TOO_MUCH_NESTED_CALLS({replacedPair})")); } var innerFlatten = CreateNewContext(replacedPair); var replaced = innerFlatten.Visit(bestCandidate); if (replaced is ExpressionSyntax expression) { var hasBinaryOps = new HasBinaryOperations(); hasBinaryOps.Visit(expression); if (hasBinaryOps.Result) { replaced = SyntaxFactory.ParenthesizedExpression(expression); } } if (Errors.Contains(RateRulesErrors.TooMuchNestedCalls)) { return(RateRules.CreateExpression($"ERR_TOO_MUCH_NESTED_CALLS({replacedPair})")); } return(replaced); } } return(base.VisitIdentifierName(node)); }
//------------------------------------------------------------------------- public virtual void coverage() { BlackFxOptionInterpolatedNodalSurfaceVolatilitiesSpecification test1 = BlackFxOptionInterpolatedNodalSurfaceVolatilitiesSpecification.builder().name(VOL_NAME).currencyPair(GBP_USD).dayCount(ACT_365F).nodes(NODES).timeInterpolator(PCHIP).timeExtrapolatorLeft(LINEAR).timeExtrapolatorRight(LINEAR).strikeInterpolator(PCHIP).strikeExtrapolatorLeft(LINEAR).strikeExtrapolatorRight(LINEAR).build(); coverImmutableBean(test1); CurrencyPair eurUsd = CurrencyPair.of(EUR, USD); ImmutableList.Builder <FxOptionVolatilitiesNode> nodeBuilder = ImmutableList.builder(); for (int i = 0; i < TENORS.Count; ++i) { for (int j = 0; j < STRIKES.Count; ++j) { QuoteId quoteId = QuoteId.of(StandardId.of("OG", eurUsd.ToString() + "_" + TENORS[i].ToString() + "_" + STRIKES[j])); nodeBuilder.add(FxOptionVolatilitiesNode.of(eurUsd, SPOT_OFFSET, BDA, ValueType.BLACK_VOLATILITY, quoteId, TENORS[i], SimpleStrike.of(STRIKES[j]))); } } BlackFxOptionInterpolatedNodalSurfaceVolatilitiesSpecification test2 = BlackFxOptionInterpolatedNodalSurfaceVolatilitiesSpecification.builder().name(FxOptionVolatilitiesName.of("other")).currencyPair(eurUsd).dayCount(ACT_360).nodes(nodeBuilder.build()).timeInterpolator(DOUBLE_QUADRATIC).strikeInterpolator(DOUBLE_QUADRATIC).build(); coverBeanEquals(test1, test2); }
public async Task <IList <Trade> > ReadHistoricTrades(CurrencyPair currencyPair, DateTime startTime, DateTime endTime) { // Load response const string command = "returnTradeHistory"; var parameters = new Dictionary <string, string> { // TODO: Map global currency pair to poloniex currency pair instead of expecting these to be equal { "currencyPair", currencyPair.ToString() }, { "start", DateTimeHelper.ToUnixTime(startTime).ToString() }, { "end", DateTimeHelper.ToUnixTime(endTime).ToString() } }; var historicTradesData = await _dataRetriever.PerformRequest <IList <MarketTrade> >(ServerUrl, command, parameters); var historicTrades = new List <Trade>(); foreach (var historicTrade in historicTradesData.Reverse()) { var trade = new Trade(historicTrade.Date, historicTrade.Type, historicTrade.Rate, historicTrade.Amount, historicTrade.Total); historicTrades.Add(trade); } return(historicTrades); }
public double GetFXDataFromApi(CurrencyPair cp, DateTime date) { this.PublishInfo($"FX API Request : {cp.ToString()} - {date.ToString()}"); string key1 = cp.Ccy1.ToString(); string key2 = cp.Ccy2.ToString(); string url = (string)RootAPIRequest.Clone(); url = url.Replace("{Date}", GetDateTimeString(date)); url = url.Replace("{APIKey}", APIKey); string url1 = (string)url.Clone(); url1 = url1.Replace("{Base}", key2); url1 = url1.Replace("{FX}", key1); string keyToUse = key1; string responseResult; try { var responseJson = Client.GetStringAsync(url1); responseResult = responseJson.Result; } catch { keyToUse = key2; url = url.Replace("{Base}", key1); url = url.Replace("{FX}", key2); var responseJson = Client.GetStringAsync(url); responseResult = responseJson.Result; } responseResult = responseResult.Replace("base", "Base"); FXData results = JsonConvert.DeserializeObject <FXData>(responseResult); double price = results.rates[keyToUse]; return(Math.Round(keyToUse == key1?1 / price:price, 4)); }
/// <summary> /// btcusd,btceur,ltceur /// </summary> /// <param name="pair"></param> /// <returns></returns> public string GetPairName(CurrencyPair pair) { return(pair.ToString().ToLower()); }
private void EmaAlgo_Click(object sender, EventArgs e) { double testProfit = 1, profit2 = 1, profitper = 2; bool fl = true, fl2 = true; infoPeriod(); int mPer = GraphsPer(MPeriod.SelectedIndex); int d = int.Parse(numDay.Text); int per1 = int.Parse(Periods.Text); int per2 = int.Parse(Periods2.Text); double diff, diffOld; CurrencyPair cp = new CurrencyPair(BaseCur.Text, QuoteCur.Text); Task <IList <IMarketChartData> > er; if (DayPeriodCheck.Checked) { er = PC.Markets.GetChartDataAsync(cp, (MarketPeriod)mPer, DateTime.Now.AddDays(-d), DateTime.Now); } else { er = PC.Markets.GetChartDataAsync(cp, (MarketPeriod)mPer, dateTimePicker1.Value, dateTimePicker2.Value); } var emas1 = EmaAl.ExMA(er.Result, per1); var emas2 = EmaAl.ExMA(er.Result, per2); for (int i = 0; i < er.Result.Count; i++) { InfoView.Rows.Add(i, cp.ToString(), (decimal)emas1[i].High, (decimal)emas1[i].Low, emas1[i].Time, (decimal)emas1[i].VolumeBase, (decimal)emas1[i].VolumeQuote, (decimal)emas1[i].WeightedAverage, (decimal)emas1[i].Open, (decimal)emas1[i].Close, (decimal)emas1[i].Ema, (decimal)emas2[i].Ema); if (emas1[i].Ema > emas2[i].Ema) { InfoView.Rows[i].DefaultCellStyle.BackColor = Color.Teal; if (fl && i > 0 ? emas1[i - 1].Ema <= emas2[i - 1].Ema : false) { testProfit = SolveExchange(OrderType.Sell, testProfit, emas1[i].Open, 0.025); fl = !fl; } } else { InfoView.Rows[i].DefaultCellStyle.BackColor = Color.Silver; if (fl != true && i > 0 ? emas1[i - 1].Ema > emas2[i - 1].Ema : false) { testProfit = SolveExchange(OrderType.Buy, testProfit, emas1[i].Open, 0.025); fl = !fl; } } diff = StratEma1021(emas1[i].Ema, emas2[i].Ema); diffOld = i > 0? StratEma1021(emas1[i - 1].Ema, emas2[i - 1].Ema):0; InfoView.Rows[i].Cells[12].Value = testProfit; InfoView.Rows[i].Cells[13].Value = diff; if (diff > 0.25 && diffOld < 0 && fl2 && i > Math.Max(per1, per2)) { profit2 = SolveExchange(OrderType.Sell, profit2, emas1[i].Close, 0.025); fl2 = !fl2; } if ((diff < 0 || (profit2 / 100) * profitper < emas1[i].Close) && diffOld > 0 && fl2 == false && i > Math.Max(per1, per2)) { profit2 = SolveExchange(OrderType.Buy, profit2, emas1[i].Close, 0.025); fl2 = !fl2; } InfoView.Rows[i].Cells[14].Value = profit2; InfoView.Rows[i].Cells[15].Value = (profit2 / 100) * profitper; } }