private double CalculateSpreadDiscount(NetPositionDTO currContract, NetPositionDTO nextContract, int spreadIndex) { double totalDiscount = 0; if (Math.Sign(nextContract.NetContracts) != Math.Sign(currContract.NetContracts))//we have a spread { double netSpread = Math.Min(Math.Abs(currContract.NetContracts), Math.Abs(nextContract.NetContracts)); if (netSpread != 0) { DailySettlementPrice DSP1 = DailySettlementPrices.Where(x => x.Symbol == currContract.Symbol).FirstOrDefault(); DailySettlementPrice DSP2 = DailySettlementPrices.Where(x => x.Symbol == nextContract.Symbol).FirstOrDefault(); if (spreadIndex == 1)//1-wide spread { totalDiscount += netSpread * Config.MarginPct * Config.OneWideCalDisc * (DSP1.Price.Value + DSP2.Price.Value); } else if (spreadIndex == 2)//2-wide spread { totalDiscount += netSpread * Config.MarginPct * Config.TwoWideCalDisc * (DSP1.Price.Value + DSP2.Price.Value); } else if (spreadIndex >= 3)//3-wide spread or wider { totalDiscount += netSpread * Config.MarginPct * Config.ThreeWideCalDisc * (DSP1.Price.Value + DSP2.Price.Value); } ; currContract.NetContracts -= (currContract.NetContracts > 0) ? netSpread : (-1 * netSpread); nextContract.NetContracts -= (nextContract.NetContracts > 0) ? netSpread : (-1 * netSpread); } } return(totalDiscount); }
private void DailySettlementThread(object param) { object[] paramArray = (object[])param; IWebSocketConnection socket = (IWebSocketConnection)paramArray[0]; WebSocketSubscribeMessage subscrMsg = (WebSocketSubscribeMessage)paramArray[1]; bool subscResp = false; try { while (true) { DailySettlementPrice dailySettl = DailySettlementPrices.Where(x => x.Symbol == subscrMsg.ServiceKey).FirstOrDefault(); if (dailySettl != null) { DoSend <DailySettlementPrice>(socket, dailySettl); Thread.Sleep(3000);//3 seconds if (!subscResp) { ProcessSubscriptionResponse(socket, "FP", subscrMsg.ServiceKey, subscrMsg.UUID); Thread.Sleep(2000); subscResp = true; } } else { DoLog(string.Format("Daily Settlement Price not found for symbol {0}...", subscrMsg.ServiceKey), MessageType.Information); break; } } } catch (Exception ex) { DoLog(string.Format("Critical error processing daily settlement price message: {0}...", ex.Message), MessageType.Error); } }
protected double?GetVMRequirement(List <ClientPosition> prevPositions, List <TradeDTO> todayTrades) { if (DailySettlementPrices.Length == TodayDailySettlementPrices.Length) { double vmReqs = 0; foreach (ClientPosition prevPos in prevPositions) { DailySettlementPrice prevDSP = DailySettlementPrices.Where(x => x.Symbol == prevPos.Symbol).FirstOrDefault(); DailySettlementPrice todayDSP = TodayDailySettlementPrices.Where(x => x.Symbol == prevPos.Symbol).FirstOrDefault(); if (prevDSP == null || !prevDSP.Price.HasValue) { throw new Exception(string.Format("Missing DSP for symbol {0}", prevPos.Symbol)); } if (todayDSP == null || !todayDSP.Price.HasValue) { throw new Exception(string.Format("Today DSP for symbol {0}", prevPos.Symbol)); } double prevPosVMReq = prevPos.Contracts * (todayDSP.Price.Value - prevDSP.Price.Value); double todayPosVMReq = 0; foreach (TradeDTO trade in todayTrades.Where(x => x.Symbol == prevPos.Symbol).ToList()) { if (trade.GetSignedExecutionSize() > 0) { todayPosVMReq += trade.ExecutionSize * (todayDSP.Price.Value - trade.ExecutionPrice); } else { todayPosVMReq += trade.ExecutionSize * (trade.ExecutionPrice - todayDSP.Price.Value); } } vmReqs += prevPosVMReq + todayPosVMReq; } return(vmReqs * -1);//Negative is that I earned profit, Positive is that I loss } else { return(null); } }
private DailySettlementPrice[] GetDSPs(Dictionary <string, double> DSPDicts) { List <DailySettlementPrice> DSPs = new List <DailySettlementPrice>(); foreach (string symbol in DSPDicts.Keys) { DailySettlementPrice DSP = new DailySettlementPrice(); DSP.Msg = "DailySettlementPrice"; DSP.Symbol = symbol; DSP.Price = DSPDicts[symbol]; DSPs.Add(DSP); } return(DSPs.ToArray()); }
//here I can work with just 1 security public double GetExposureChange(char side, double qty, string symbol, string firmId, ClientPosition[] Positions, List <OrderDTO> Orders) { double finalExposure = 0; double currentExposure = 0; double netContracts = 0; qty = (ClientOrderRecord._SIDE_BUY == side) ? qty : -1 * qty; netContracts = GetNetContracts(firmId, symbol, Positions, side, Orders); DailySettlementPrice DSP = DailySettlementPrices.Where(x => x.Symbol == symbol).FirstOrDefault(); if (DSP != null && DSP.Price.HasValue) { currentExposure = (Math.Abs(netContracts) * DSP.Price.Value); finalExposure = (Math.Abs(netContracts + qty) * DSP.Price.Value); } return(finalExposure - currentExposure); }
public double GetUsedCredit(string firmId, ClientPosition[] Positions) { List <NetPositionDTO> netPositionsArr = new List <NetPositionDTO>(); double creditUsed = 0; foreach (SecurityMasterRecord security in SecurityMasterRecords) { double netContracts = GetNetContracts(firmId, security.Symbol, Positions);; DailySettlementPrice DSP = DailySettlementPrices.Where(x => x.Symbol == security.Symbol).FirstOrDefault(); if (DSP != null && DSP.Price.HasValue && netContracts != 0) { creditUsed += Math.Abs(netContracts) * DSP.Price.Value; } if (security.MaturityDate != "") { netPositionsArr.Add(new NetPositionDTO() { AssetClass = security.AssetClass, Symbol = security.Symbol, MaturityDate = security.GetMaturityDate(), NetContracts = netContracts }); } DoLog(string.Format("Final Net Contracts for Security Id {0}:{1}", security.Symbol, netContracts), zHFT.Main.Common.Util.Constants.MessageType.Information); } if (Config.ImplementCalendarMarginDiscount) { string[] assetClasses = GetAvailableAssetClasses(); foreach (string assetClass in assetClasses) { creditUsed -= (CalculateCalendarMarginDiscounts(netPositionsArr.ToArray(), assetClass) / Config.MarginPct); } } return(creditUsed - GetPriorDayCredit(firmId)); }
protected double GetPotentialxMargin(char side, string firmId, ClientPosition[] Positions, List <OrderDTO> Orders) { double acumMargin = 0; foreach (SecurityMasterRecord security in SecurityMasterRecords) { double potentialNetContracts = GetNetContracts(firmId, security.Symbol, Positions, side, Orders); DoLog(string.Format("Potential Contracts for Security {0} after Orders:{1}", security.Symbol, potentialNetContracts), zHFT.Main.Common.Util.Constants.MessageType.Information); DailySettlementPrice DSP = DailySettlementPrices.Where(x => x.Symbol == security.Symbol).FirstOrDefault(); if (DSP != null && DSP.Price.HasValue) { acumMargin += Math.Abs(potentialNetContracts) * DSP.Price.Value * Config.MarginPct; } } //TODO : implement the calendar spreads margin calculation DoLog(string.Format("Acum Margin for FirmId {0} after Orders:{1}", firmId, acumMargin), zHFT.Main.Common.Util.Constants.MessageType.Information); return(acumMargin - GetFundedMargin(firmId)); }
protected double GetBaseMargin(string firmId, ClientPosition[] Positions, string symbol = null, DailySettlementPrice[] DSPsToUse = null) { double acumMargin = 0; foreach (SecurityMasterRecord security in SecurityMasterRecords.Where(x => (symbol == null || x.Symbol == symbol))) { double netContracts = GetNetContracts(firmId, security.Symbol, Positions); DailySettlementPrice DSP = DSPsToUse == null?DailySettlementPrices.Where(x => x.Symbol == security.Symbol).FirstOrDefault() : DSPsToUse.Where(x => x.Symbol == security.Symbol).FirstOrDefault(); if (DSP != null && DSP.Price.HasValue) { acumMargin += Math.Abs(netContracts) * DSP.Price.Value * Config.MarginPct; } DoLog(string.Format("Net Contracts for Security {0} :{1}", security.Symbol, netContracts), zHFT.Main.Common.Util.Constants.MessageType.Information); } //TODO : implement the calendar spreads margin calculation DoLog(string.Format("Base Margin for FirmId {0}:{1}", firmId, acumMargin), zHFT.Main.Common.Util.Constants.MessageType.Information); return(acumMargin); }
private static void ProcessEvent(WebSocketMessage msg) { if (msg is ClientLoginResponse) { ClientLoginResponse loginResp = (ClientLoginResponse)msg; if (loginResp.JsonWebToken != null) { ClientLoginResponse = loginResp; } DoLog(string.Format("Client successfully logged with token {0}", loginResp.JsonWebToken)); //3- Subscribe market data for Security //Market data will be delivered through many services, for the moment we will use // LS - LastSales will have all the information regarding the trades that took place (high, low, last, etc.) // LQ - QuoteService will tell us the the best offers (best buy and sell) that we have for a security. // It is what fills the red/green holders that we can see in the image! // When we select a Product (SPOT) and Pair (XBT-USD) in the combos, we will have to fill the instrument holder (story 74) // ---> In that context we only need the Quote (LQ) service // Only when we CLICK that instrument we will need the trades service (LS) to fill the header // ---> Then we can make this call //Of course, every time we subscribe to some security , we will have to ususcribe to another one. // That will be covered in the spec document RequestMarketData(Security); } else if (msg is LastSale) { //4.1 LastSale event arrived! We update the security in memory with the following fields LastSale lastSale = (LastSale)msg; lock (Security) { Security.MarketData.LastTradeDateTime = lastSale.GetLastTime(); Security.MarketData.MDTradeSize = lastSale.LastShares; Security.MarketData.Trade = lastSale.LastPrice; Security.MarketData.NominalVolume = lastSale.Volume; Security.MarketData.TradingSessionHighPrice = lastSale.High; Security.MarketData.TradingSessionLowPrice = lastSale.Low; Security.MarketData.OpeningPrice = lastSale.Open; Security.MarketData.NetChgPrevDay = lastSale.Change; } MarketDataRefresh(); } else if (msg is Quote) { //4.2 Quote event arrived! We update the security in memory with the following fields Quote quote = (Quote)msg; lock (Security) { Security.MarketData.BestBidPrice = quote.Bid; Security.MarketData.BestBidSize = quote.BidSize; Security.MarketData.BestAskPrice = quote.Ask; Security.MarketData.BestAskSize = quote.AskSize; } MarketDataRefresh(); } else if (msg is DailySettlementPrice) { //4.3 DailySettlementPrice event arrived! We update the security in memory with the following fields DailySettlementPrice DSP = (DailySettlementPrice)msg; lock (Security) { Security.MarketData.SettlementPrice = DSP.Price; } MarketDataRefresh(); } else if (msg is OfficialFixingPrice) { //4.4 DailySettlementPrice event arrived! We update the security in memory with the following fields OfficialFixingPrice fixingPrice = (OfficialFixingPrice)msg; lock (Security) { Security.MarketData.FIXPrice = fixingPrice.Price; } MarketDataRefresh(); } else if (msg is SubscriptionResponse) { SubscriptionResponse subscrResp = (SubscriptionResponse)msg; //We have to process this message to be sure that the subscription was fully processed } }