﻿CREATE FUNCTION [dbo].[API_KnokRanks]
(
	@knokId int
)
RETURNS @rankFactors TABLE
(
	RankId int,
	Code nchar(10),
	Measure DECIMAL (22, 8)
)
AS
BEGIN
	DECLARE @Duration int, @EntryRange DECIMAL (22, 8),@ExitRange DECIMAL (22, 8),@MinHighSpread DECIMAL (22, 8),@MinLowSpread DECIMAL (22, 8),
	@DistStopLoss DECIMAL (22, 8), @HasTechnical BIT, @HasFundamental BIT, @KnokserLevel int, @KnokserRank DECIMAL (22, 8)

	Select @Duration = k.Duration * 24, 
		@EntryRange = (k.EntryPriceTo- k.EntryPriceFrom)/k.EntryPriceFrom*100,
		@ExitRange = (k.ExitPriceTo- k.ExitPriceFrom)/k.ExitPriceFrom*100,
		@MinHighSpread = (k.ExitPriceFrom - k.EntryPriceTo)/k.EntryPriceTo*100, 
		@MinLowSpread = (k.ExitPriceTo - k.EntryPriceFrom)/k.EntryPriceFrom*100, 
		@DistStopLoss = (k.EntryPriceFrom - k.StopLoss)/k.EntryPriceFrom*100 , 
		@HasTechnical = k.HasTechnical, 
		@HasFundamental = k.HasFundamental, 
		@KnokserLevel = 0,
		@KnokserRank = rank.RankValue
		from Signals k 
		cross apply API_CalcKnokserRanks(k.CreatorUserId) as rank
		WHERE k.KnokId=@knokId
	INSERT @rankFactors (RankId, Code, Measure)	VALUES
	(1, 'Duration', @Duration),
	(1, 'EntryRange', @EntryRange),
	(1, 'ExitRange', @ExitRange),
	(1, 'MinHighSpr', @MinHighSpread),
	(1, 'MinLowSpr', @MinLowSpread),
	(1, 'DStopLoss', @DistStopLoss),
	(1, 'HasTA', @HasTechnical),
	(1, 'HasFA', @HasFundamental),
	(1, 'KnokserLev', @KnokserLevel),
	(1, 'KnokserR', @KnokserRank)
	RETURN
END
