﻿CREATE VIEW [dbo].[VW_EndedKnoks]
	AS SELECT k.Duration, k.CreateDate, k.KnokId KnokId, k.Currency1 Currency1, k.Currency2 Currency2, k.Currency, t.TickerDisplayName as MarketDisplayName, k.ExchangeId, k.CreatorUserId as UserId, 
		EntryPriceFrom, EntryPriceTo, ExitPriceFrom,  ExitPriceTo, StopLoss, e.ExchangeName, k.TickerId,
		
		(CASE 
			WHEN k.EntryPriceTouched = 1 AND k.ExitPriceTouched = 1 AND k.StopLossTouched = 0 
				THEN --if successful knok (knok that touched entry and exit) ;result = (mid exit -mid entry) / mid entry x 100
				(((k.ExitPriceFrom + ExitPriceTo) / 2) - ((k.EntryPriceFrom + EntryPriceTo) / 2)) / ((k.EntryPriceFrom + EntryPriceTo) / 2)
			WHEN (k.StopLossTouched = 0 AND k.ExitPriceTouched = 0 AND status.IsClosed = 0) OR status.IsClosed = 1
				THEN  --else; result =  (close rate -mid entry) / mid entry x 100
				IIF(ISNULL(k.CloseRate, 0) = 0, 0, (k.CloseRate - ((k.EntryPriceFrom + EntryPriceTo) / 2)) / ((k.EntryPriceFrom + EntryPriceTo) / 2))
			WHEN k.StopLossTouched = 1 
				THEN --if touched SL; result =  (SL -mid entry) / mid entry x 100
				(k.StopLoss - ((k.EntryPriceFrom + EntryPriceTo) / 2)) / ((k.EntryPriceFrom + EntryPriceTo) / 2)
			ELSE 0 -- Unknown				
		END) AS CurrentProfit,

		k.DistanceFromTarget,
		k.PotentialProfitValue, 
		k.CloseRate AS CurrentPrice,
		ISNULL(k.UserReview, 0) AS UserReview,
		(SELECT count(1) FROM UserKnoks uk WHERE uk.KnokId = k.KnokId) AS Purchases,
		u.HasAvatar, u.UserName, u.FirstName, u.LastName,
		k.ExitPriceTouched,
		(CASE 
			WHEN k.EntryPriceTouched = 1 AND k.ExitPriceTouched = 1 AND k.StopLossTouched = 0 THEN 4 -- Successful
			WHEN k.StopLossTouched = 0 AND k.ExitPriceTouched = 0 AND status.IsClosed = 0 THEN 1 -- ExitPriceMissed
			WHEN k.StopLossTouched = 1 THEN 2 -- Stop loss reached
			WHEN status.IsClosed = 1 THEN 3 --ClosedByKnokser
			ELSE 0 -- Unknown
		END) AS EndedStatus,
		-- amount of purchases * knok price * knokser commission (70%)
		(SELECT SUM(pk.Price) FROM UserKnoks uk
			INNER JOIN Signals pk ON pk.KnokId = uk.KnokId 
			WHERE pk.knokId = k.knokId
			GROUP BY uk.knokId) AS PricePoolData,
		CloseDate, CloseRate,
		CAST(ISNULL(s.Decimals, 8) AS smallint) AS Precision

	FROM [dbo].[Signals] k with(nolock) 
	LEFT JOIN [dbo].[_KnokStatuses] status on k.KnokStatusId = status.KnokStatusId
	LEFT JOIN [dbo].[Users] u on u.UserId = k.CreatorUserId
	LEFT JOIN [dbo].[Exchanges] e on e.ExchangeId = k.ExchangeId
	LEFT JOIN [dbo].[Tickers] t on t.TickerId = k.TickerId
	LEFT JOIN (select count(f.UserId) UserFollowers, f.FollowUserId userId from [dbo].[UserFollows] f group by f.FollowUserId) follow on follow.userId = k.CreatorUserId
	left join [dbo].[Symbols]  s on s.Symbol = k.Currency2
	Where (status.KnokStatusId = 5 OR status.KnokStatusId = 6) -- 5 - Resolved, 6 - Resolved and closed