internal static decimal Calculate(TradePLFormula tradePLFormula, decimal quantity, decimal buyPrice, decimal sellPrice, decimal closePrice) { try { decimal tradePL = 0; switch (tradePLFormula) { case TradePLFormula.S_BxCS: tradePL = quantity * (sellPrice - buyPrice); break; case TradePLFormula.S_BxCSiL: tradePL = quantity * (sellPrice - buyPrice) / closePrice; break; case TradePLFormula.Si1_Bi1xCSiL: tradePL = quantity * (1 / sellPrice - 1 / buyPrice); break; case TradePLFormula.S_BxCSiO: decimal openPrice = (closePrice == buyPrice) ? sellPrice : buyPrice; tradePL = quantity * (sellPrice - buyPrice) / openPrice; break; default: throw new NotSupportedException(string.Format("{0} is not a supported TradePLFormula", tradePLFormula)); } return(tradePL); } catch (System.DivideByZeroException) { Logger.ErrorFormat("buyPrice = {0}, sellPrice= {1}, closePrice = {2}", buyPrice, sellPrice, closePrice); throw; } }
internal static decimal Calculate(TradePLFormula tradePLFormula, decimal quantity, decimal buyPrice, decimal sellPrice, decimal closePrice, CurrencyRate currencyRate) { var tradePL = Calculate(tradePLFormula, quantity, buyPrice, sellPrice, closePrice); return(currencyRate.Exchange(tradePL)); }
public static decimal CalculateValue(TradePLFormula tradePLFormula, decimal lot, Price price, decimal discountOfOdd, decimal contractSize) { decimal lotInteger = Math.Truncate(lot); decimal lotRemainder = lot - lotInteger; decimal marketValue = 0; decimal livePrice = (decimal)price; switch (tradePLFormula) { case TradePLFormula.S_BxCS: marketValue = lotInteger * contractSize * livePrice + lotRemainder * contractSize * livePrice * discountOfOdd; break; case TradePLFormula.S_BxCSiL: case TradePLFormula.S_BxCSiO: marketValue = lotInteger * contractSize + lotRemainder * contractSize * discountOfOdd; break; case TradePLFormula.Si1_Bi1xCSiL: livePrice = 1 / livePrice; marketValue = lotInteger * contractSize * livePrice + lotRemainder * contractSize * livePrice * discountOfOdd; break; default: throw new NotSupportedException(string.Format("{0} is not a supported TradePLFormula", tradePLFormula)); } return(marketValue); }
internal static decimal Calculate(Order order, Quotation quotation, DateTime?tradeDay) { try { if (order.IsRisky) { decimal buyPrice, sellPrice, closePrice; if (order.IsBuy) { buyPrice = (decimal)order.ExecutePrice; sellPrice = closePrice = (decimal)quotation.BuyPrice; } else { buyPrice = closePrice = (decimal)quotation.SellPrice; sellPrice = (decimal)order.ExecutePrice; } TradePLFormula tradePLFormula = order.Owner.SettingInstrument().TradePLFormula; decimal lot = order.LotBalance; decimal contractSize = order.Owner.ContractSize(tradeDay); return(Calculate(tradePLFormula, lot * contractSize, buyPrice, sellPrice, closePrice, order.Owner.CurrencyRate(null))); } else { return(0); } } catch (Exception ex) { Logger.ErrorFormat("order id = {0}, executePrice = {1}, buyPrice = {2}, sellPrice = {3}, tradeDay = {4}, order.Phase = {5}, tran.Id = {6}, account.Id = {7} ,error= {8}", order.Id, order.ExecutePrice, quotation.BuyPrice, quotation.SellPrice, tradeDay, order.Phase, order.Owner.Id, order.Owner.AccountId, ex); return(0m); } }
//Only Update the fields that should take effect in the past internal override void Update(IDBRow instrumentRow) { base.Update(instrumentRow); this._category = (InstrumentCategory)instrumentRow.GetColumn <int>("Category"); this._numeratorUnit = instrumentRow.GetColumn <int>("NumeratorUnit"); this._denominator = instrumentRow.GetColumn <int>("Denominator"); this._isNormal = instrumentRow.GetColumn <bool>("IsNormal"); this.DayOpenTime = (instrumentRow["DayOpenTime"] == DBNull.Value) ? default(DateTime) : (DateTime)instrumentRow["DayOpenTime"]; this.DayCloseTime = (instrumentRow["DayCloseTime"] == DBNull.Value) ? default(DateTime) : (DateTime)instrumentRow["DayCloseTime"]; if (instrumentRow.Contains("EndTime")) { _endTime = (instrumentRow["EndTime"] == DBNull.Value) ? default(DateTime) : (DateTime)instrumentRow["EndTime"]; } this.ValueDate = (instrumentRow["ValueDate"] == DBNull.Value) ? default(DateTime) : (DateTime)instrumentRow["ValueDate"]; this.NextDayOpenTime = (instrumentRow["NextDayOpenTime"] == DBNull.Value) ? default(DateTime) : (DateTime)instrumentRow["NextDayOpenTime"]; this._commissionFormula = (FeeFormula)instrumentRow.GetColumn <byte>("CommissionFormula"); this._levyFormula = (FeeFormula)instrumentRow.GetColumn <byte>("LevyFormula"); _otherFeeFormula = (FeeFormula)instrumentRow.GetColumn <byte>("OtherFeeFormula"); this._marginFormula = (MarginFormula)instrumentRow.GetColumn <byte>("MarginFormula"); this._tradePLFormula = (TradePLFormula)instrumentRow.GetColumn <byte>("TradePLFormula"); this._isExpired = this.DayOpenTime == default(DateTime) && this.DayCloseTime == default(DateTime) && this.ValueDate == default(DateTime) && this.NextDayOpenTime == default(DateTime); }
internal static decimal CalculateMarketValue(PhysicalOrder order, Price price, DateTime?tradeDay, out decimal valueAsMargin) { valueAsMargin = 0; decimal result = 0m; if (!order.IsPhysical) { return(result); } var physicalOpenOrder = order as PhysicalOrder; if ((physicalOpenOrder.PhysicalTradeSide == PhysicalTradeSide.Buy && physicalOpenOrder.IsPayoff) || physicalOpenOrder.PhysicalTradeSide == PhysicalTradeSide.Deposit) { TradePLFormula tradePLFormula = order.Owner.SettingInstrument(tradeDay).TradePLFormula; decimal lot = order.LotBalance, contractSize = order.Owner.ContractSize(tradeDay); decimal discountOfOdd = order.Owner.TradePolicyDetail(tradeDay).DiscountOfOdd; decimal marketValue = CalculateValue(tradePLFormula, lot, price, discountOfOdd, contractSize); valueAsMargin = order.Owner.CurrencyRate(tradeDay).Exchange(marketValue * order.Owner.TradePolicyDetail(tradeDay).ValueDiscountAsMargin); return(order.Owner.CurrencyRate(tradeDay).Exchange(marketValue)); } return(result); }
internal virtual ChangedItem Update(Quotation qutation) { ChangedItem changedItems = ChangedItem.None; if (_ask != qutation.Ask || _bid != qutation.Bid) { changedItems |= ChangedItem.Quotation; } var currencyRate = _owner.Owner.CurrencyRate(null); var settingInstrument = _owner.Owner.SettingInstrument(); if (_currencyRateIn != currencyRate.RateIn || _currencyRateOut != currencyRate.RateOut) { changedItems |= ChangedItem.CurrecnyRate; } if (_tradePLFormula != settingInstrument.TradePLFormula) { changedItems |= ChangedItem.TradePLFormula; } if (_marginFormula != settingInstrument.MarginFormula) { changedItems |= ChangedItem.MarginFormula; } if (_lotBlance != _owner.LotBalance) { changedItems |= ChangedItem.LotBalance; } _ask = qutation.Ask; _bid = qutation.Bid; _marginFormula = settingInstrument.MarginFormula; _tradePLFormula = settingInstrument.TradePLFormula; _lotBlance = _owner.LotBalance; _currencyRateIn = currencyRate.RateIn; _currencyRateOut = currencyRate.RateOut; this.ChangedItem = changedItems; return(changedItems); }
internal static decimal Calculate(TradePLFormula tradePLFormula, decimal lot, decimal contractSize, decimal buyPrice, decimal sellPrice, decimal closePrice, int decimals) { decimal result = TradePLCalculator.Calculate(tradePLFormula, lot * contractSize, buyPrice, sellPrice, closePrice); return(Math.Round(result, decimals, MidpointRounding.AwayFromZero)); }
internal override void Update(XElement instrumentNode) { base.Update(instrumentNode); foreach (XAttribute attribute in instrumentNode.Attributes()) { switch (attribute.Name.ToString()) { case "ID": this._id = XmlConvert.ToGuid(attribute.Value); break; case "CurrencyID": this._currencyId = XmlConvert.ToGuid(attribute.Value); break; case "Code": this._code = attribute.Value; break; case "OriginCode": _originCode = attribute.Value; break; case "OriginInactiveTime": this.InactiveTime = XmlConvert.ToInt32(attribute.Value); break; case "Category": this._category = (InstrumentCategory)XmlConvert.ToInt32(attribute.Value); break; case "NumeratorUnit": this._numeratorUnit = XmlConvert.ToInt32(attribute.Value); break; case "Denominator": this._denominator = XmlConvert.ToInt32(attribute.Value); break; case "IsActive": this._isActive = XmlConvert.ToBoolean(attribute.Value); break; case "LastAcceptTimeSpan": this._lastAcceptTimeSpan = XmlConvert.ToInt32(attribute.Value); break; case "OrderTypeMask": this._orderTypeMask = XmlConvert.ToInt32(attribute.Value); break; case "MIT": this._mit = XmlConvert.ToBoolean(attribute.Value); break; case "AutoAcceptMaxLot": this.AutoAcceptMaxLot = XmlConvert.ToDecimal(attribute.Value); break; case "AutoCancelMaxLot": this.AutoCancelMaxLot = XmlConvert.ToDecimal(attribute.Value); break; case "IsAutoFill": this._isAutoFill = XmlConvert.ToBoolean(attribute.Value); break; case "MaxMinAdjust": this._maxMinAdjust = XmlConvert.ToInt32(attribute.Value); break; case "DayOpenTime": this.DayOpenTime = Convert.ToDateTime(attribute.Value); break; case "DayCloseTime": this.DayCloseTime = Convert.ToDateTime(attribute.Value); break; case "EndTime": _endTime = Convert.ToDateTime(attribute.Value); break; case "ValueDate": this.ValueDate = Convert.ToDateTime(attribute.Value); break; case "NextDayOpenTime": this.NextDayOpenTime = Convert.ToDateTime(attribute.Value); break; case "CommissionFormula": this._commissionFormula = (FeeFormula)XmlConvert.ToByte(attribute.Value); break; case "LevyFormula": this._levyFormula = (FeeFormula)XmlConvert.ToByte(attribute.Value); break; case "OtherFeeFormula": _otherFeeFormula = (FeeFormula)XmlConvert.ToByte(attribute.Value); break; case "MarginFormula": this._marginFormula = (MarginFormula)XmlConvert.ToByte(attribute.Value); break; case "TradePLFormula": this._tradePLFormula = (TradePLFormula)XmlConvert.ToByte(attribute.Value); break; case "InterestFormula": this._interestFormula = (InterestFormula)XmlConvert.ToByte(attribute.Value); break; case "InterestYearDays": this._interestYearDays = XmlConvert.ToInt32(attribute.Value); break; case "IsNormal": this._isNormal = XmlConvert.ToBoolean(attribute.Value); break; case "HitTimes": this._hitTimes = XmlConvert.ToInt32(attribute.Value); break; case "PenetrationPoint": this._penetrationPoint = XmlConvert.ToInt32(attribute.Value); break; case "UseSettlementPriceForInterest": this._useSettlementPriceForInterest = XmlConvert.ToBoolean(attribute.Value); break; case "CanPlacePendingOrderAtAnyTime": this._canPlacePendingOrderAtAnyTime = XmlConvert.ToBoolean(attribute.Value); break; case "AllowedSpotTradeOrderSides": this._allowedSpotTradeOrderSides = (AllowedOrderSides)XmlConvert.ToInt32(attribute.Value); break; case "PlaceSptMktTimeSpan": _placeSptMktTimeSpan = TimeSpan.FromSeconds(XmlConvert.ToInt32(attribute.Value)); break; case "HitPriceVariationForSTP": this.HitPriceVariationForSTP = XmlConvert.ToInt32(attribute.Value); break; case "AcceptIfDoneVariation": this._acceptIfDoneVariation = XmlConvert.ToInt32(attribute.Value); break; case "FirstOrderTime": _firstOrderTime = XmlConvert.ToInt32(attribute.Value); break; case "IsPriceEnabled": this._isPriceEnabled = XmlConvert.ToBoolean(attribute.Value); _priceEnableTime = DateTime.Now; break; case "AutoDQDelay": this.AutoDQDelay = TimeSpan.FromSeconds(XmlConvert.ToInt16(attribute.Value)); break; case "HolidayAlertDayPolicyID": this.HolidayAlertDayPolicyId = XmlConvert.ToGuid(attribute.Value); break; case "SummaryQuantity": this._summaryQuantity = XmlConvert.ToDecimal(attribute.Value); break; case "SpotPaymentTime": this.SpotPaymentTime = attribute.Value.Get <DateTime?>(); break; } } }
internal static decimal CalculateCommission(FeeFormula commissionFormula, TradePLFormula tradePLFormula, decimal unitCommission, decimal lot, decimal contractSize, Price price, CurrencyRate currencyRate, decimal tradePL = 0) { if (unitCommission > 1) { unitCommission = Math.Round(unitCommission, currencyRate.TargetCurrency.Decimals, MidpointRounding.AwayFromZero); } decimal commission = 0; switch (commissionFormula) { case FeeFormula.FixedAmount: commission = unitCommission * lot; commission = Math.Round(commission, currencyRate.TargetCurrency.Decimals, MidpointRounding.AwayFromZero); break; case FeeFormula.CS: commission = unitCommission * lot * contractSize; commission = -currencyRate.Exchange(-commission); break; case FeeFormula.CSDividePrice: commission = unitCommission * lot * contractSize / (decimal)price; commission = -currencyRate.Exchange(-commission); break; case FeeFormula.CSMultiplyPrice: commission = unitCommission * lot * contractSize * (decimal)price; commission = -currencyRate.Exchange(-commission); break; case FeeFormula.Pips: Price buyPrice, sellPrice; if ((int)tradePLFormula != 2) { buyPrice = price; sellPrice = price + (int)unitCommission; } else { buyPrice = price + (int)unitCommission; sellPrice = price; } Price closePrice = price; commission = TradePLCalculator.Calculate(tradePLFormula, lot, contractSize, (decimal)buyPrice, (decimal)sellPrice, (decimal)closePrice, currencyRate.SourceCurrency.Decimals); commission = -currencyRate.Exchange(-commission); break; case FeeFormula.PricePips: commission = 0; break; case FeeFormula.RealizedProfit: commission = tradePL > 0 ? unitCommission * tradePL : 0; break; case FeeFormula.RealizedLoss: commission = tradePL < 0 ? unitCommission * tradePL : 0; break; case FeeFormula.RealizedPL: commission = unitCommission * Math.Abs(tradePL); break; case FeeFormula.SharedPL: commission = unitCommission * tradePL; break; } return(commission); }
internal static decimal CalculateLevy(FeeFormula levyFormula, TradePLFormula tradePLFormula, decimal unitLevy, decimal lot, decimal contractSize, Price price, CurrencyRate currencyRate, decimal tradePL = 0) { if (unitLevy > 1) { unitLevy = Math.Round(unitLevy, currencyRate.TargetCurrency.Decimals, MidpointRounding.AwayFromZero); } decimal levy = 0; switch (levyFormula) { case FeeFormula.FixedAmount: levy = unitLevy * lot; levy = Math.Round(levy, currencyRate.TargetCurrency.Decimals, MidpointRounding.AwayFromZero); break; case FeeFormula.CS: levy = unitLevy * lot * contractSize; levy = -currencyRate.Exchange(-levy); break; case FeeFormula.CSDividePrice: levy = unitLevy * lot * contractSize / (decimal)price; levy = -currencyRate.Exchange(-levy); break; case FeeFormula.CSMultiplyPrice: levy = unitLevy * lot * contractSize * (decimal)price; levy = -currencyRate.Exchange(-levy); break; case FeeFormula.Pips: Price buyPrice, sellPrice; if ((int)tradePLFormula != 2) { buyPrice = price; sellPrice = price + (int)unitLevy; } else { buyPrice = price + (int)unitLevy; sellPrice = price; } Price closePrice = price; levy = TradePLCalculator.Calculate(tradePLFormula, lot, contractSize, (decimal)buyPrice, (decimal)sellPrice, (decimal)closePrice, currencyRate.SourceCurrency.Decimals); levy = -currencyRate.Exchange(-levy); break; case FeeFormula.PricePips: levy = 0; break; case FeeFormula.RealizedProfit: levy = tradePL > 0 ? unitLevy * tradePL : 0; break; case FeeFormula.RealizedLoss: levy = tradePL < 0 ? unitLevy * tradePL : 0; break; case FeeFormula.RealizedPL: levy = unitLevy * Math.Abs(tradePL); break; case FeeFormula.SharedPL: levy = unitLevy * tradePL; break; } return(levy); }
private static Price Calculate(TradePLFormula tradePLFormula, int numeratorUnit, int denominator, decimal lot, decimal contractSize, decimal openPrice, bool isOpenOnBuy, decimal tradePLThreshold) { decimal closePrice = 0; bool isGreatThan = true; decimal contractValue = (lot * contractSize); switch (tradePLFormula) { case TradePLFormula.S_BxCS: if (isOpenOnBuy) { closePrice = openPrice + tradePLThreshold / contractValue; } else { isGreatThan = false; closePrice = openPrice - tradePLThreshold / contractValue; } break; case TradePLFormula.S_BxCSiL: if (isOpenOnBuy) { closePrice = contractValue * openPrice / (contractValue - tradePLThreshold); } else { isGreatThan = false; closePrice = contractValue * openPrice / (contractValue + tradePLThreshold); } break; case TradePLFormula.Si1_Bi1xCSiL: if (isOpenOnBuy) { isGreatThan = false; closePrice = contractValue * openPrice / (contractValue + tradePLThreshold * openPrice); } else { closePrice = contractValue * openPrice / (contractValue - tradePLThreshold * openPrice); } break; case TradePLFormula.S_BxCSiO: if (isOpenOnBuy) { closePrice = openPrice + tradePLThreshold * openPrice / contractValue; } else { isGreatThan = false; closePrice = openPrice - tradePLThreshold * openPrice / contractValue; } break; } if (closePrice <= 0) { return(null); } if (tradePLThreshold < 0) { isGreatThan = !isGreatThan; } return(Price.Create((double)closePrice, numeratorUnit, denominator, isGreatThan)); }