protected override async Task <ExchangeCloseMarginPositionResult> OnCloseMarginPositionAsync(string marketSymbol) { List <object> orderParams = new List <object> { "currencyPair", marketSymbol }; JToken result = await MakePrivateAPIRequestAsync("closeMarginPosition", orderParams); ExchangeCloseMarginPositionResult closePositionResult = new ExchangeCloseMarginPositionResult() { Success = result["success"].ConvertInvariant <bool>(), Message = result["message"].ToStringInvariant(), MarketSymbol = marketSymbol }; JToken symbolTrades = result["resultingTrades"]; if (symbolTrades == null || !symbolTrades.Any()) { return(closePositionResult); } JToken trades = symbolTrades[marketSymbol]; if (trades != null && trades.Children().Count() != 0) { ParseClosePositionTrades(trades, closePositionResult); } return(closePositionResult); }
public void ParseClosePositionTrades(IEnumerable <JToken> trades, ExchangeCloseMarginPositionResult closePosition) { bool closePositionMetadataSet = false; var tradeIds = new List <string>(); foreach (JToken trade in trades) { if (!closePositionMetadataSet) { closePosition.IsBuy = trade["type"].ToStringLowerInvariant() != "sell"; if (!string.IsNullOrWhiteSpace(closePosition.MarketSymbol)) { closePosition.FeesCurrency = ParseFeesCurrency(closePosition.IsBuy, closePosition.MarketSymbol); } closePositionMetadataSet = true; } decimal tradeAmt = trade["amount"].ConvertInvariant <decimal>(); decimal tradeRate = trade["rate"].ConvertInvariant <decimal>(); closePosition.AveragePrice = (closePosition.AveragePrice * closePosition.AmountFilled + tradeAmt * tradeRate) / (closePosition.AmountFilled + tradeAmt); closePosition.AmountFilled += tradeAmt; tradeIds.Add(trade["tradeID"].ToStringInvariant()); if (closePosition.CloseDate == DateTime.MinValue) { closePosition.CloseDate = trade["date"].ToDateTimeInvariant(); } // fee is a percentage taken from the traded amount rounded to 8 decimals closePosition.Fees += CalculateFees(tradeAmt, tradeRate, closePosition.IsBuy, trade["fee"].ConvertInvariant <decimal>()); } closePosition.TradeIds = tradeIds.ToArray(); }