﻿CREATE PROCEDURE [BO_CreateKnok]
	@HttpRequestInfo	NVARCHAR(MAX) = NULL,
	@UserId			bigint,
	@OperatorId		BIGINT = NULL, 
--	@ApiConsumerId	int,
	@Currency1		NVARCHAR(50) = NULL,
	@Currency2		NVARCHAR(50) = NULL,
	@ExchangeId		INT = NULL,
--  @TickerId		INT = NULL,
	@EntryPriceFrom				decimal(18,8) ,
	@EntryPriceTo				decimal(18,8) ,
	@ExitPriceFrom				decimal(18,8) ,
	@ExitPriceTo				decimal(18,8) ,
	@StopLoss				decimal(18,8) ,
	@Duration				INT,
	@PotentialProfitValue	decimal(18,8) = NULL,
	@PotentialProfit		INT = NULL,
	@HasTechnical		BIT = 0,
	@Technical_Header	NVARCHAR(MAX) = NULL,
	@Technical_Description	NVARCHAR(MAX) = NULL,
	@Technical_References	NVARCHAR(MAX) = NULL,
	@HasFundamental	BIT = 0,
	@Fundamental_Header	NVARCHAR(MAX) = NULL,
	@Fundamental_Description	NVARCHAR(MAX) = NULL,
	@Fundamental_References	NVARCHAR(MAX) = NULL,
	@Rate	decimal(18,8) = NULL,
	@CurrentPrice decimal(22, 8),
	@alr int = 0

    -- @CreationDate
    -- @PublishDate 
	-- @IsActive	BIT = 1
	AS
	DECLARE @TranStarted	BIT,
			@ERROR	SMALLINT,
			@RC	INT,
			@RowCount	INT,
			@ErrorMessage	VARCHAR(100)
	SET @TranStarted = 0 
	SET @RC	 = 0 
 BEGIN TRY      
	-- Save HttpRequestId --
	DECLARE @HttpRequestId	BIGINT = NULL
	IF @HttpRequestInfo IS NOT NULL
	BEGIN
	INSERT INTO HttpRequests (HttpRequestInfo) VALUES (@HttpRequestInfo)
	SET @HttpRequestId = SCOPE_IDENTITY()
	END
	
	DECLARE @CreationDate datetime2 = GETUTCDATE()
	-- SET @CreationDate = ISNULL(@CreationDate, [dbo].[FN_GetSystemTime]())
	DECLARE @TickerId INT = NULL
	DECLARE @TickerCurrency varchar(25)

	select @TickerId = t.TickerId, @TickerCurrency = t.Currency from Tickers t 
	left join Exchanges on Exchanges.ExchangeId = t.ExchangeId 
	where (t.Base=@Currency1 and t.NonBase=@Currency2) --or (t.NonBase=@Currency1 and t.Base=@Currency2) 
	and t.ExchangeId = @ExchangeId
	
	IF @TickerId IS NULL
	BEGIN
		SET @RC = 1	              
		SET @ErrorMessage = 'Couldn''t find symbol pair'
		RAISERROR (@ErrorMessage,16,1)        
    END

	INSERT INTO [dbo].[Signals] ([Currency1], [Currency2], [Currency], [ExchangeId], [TickerId], [CreatorUserId], EntryPriceFrom, [EntryPriceTo], ExitPriceFrom, ExitPriceTo, [StopLoss],[Duration], [HasTechnical], [Technical_Header], [Technical_Description], [Technical_References], [HasFundamental],  [Fundamental_Header], [Fundamental_Description],
	[Fundamental_References], [CreateDate], [PublishedDate], [PotentialProfit], [PotentialProfitValue], [KnokStatusId], [Ranks]) 
		VALUES (@Currency1, @Currency2, @TickerCurrency,  @ExchangeId, @TickerId, @UserId, @EntryPriceFrom, @EntryPriceTo,
		@ExitPriceFrom, @ExitPriceTo, @StopLoss, @Duration, @HasTechnical, @Technical_Header, @Technical_Description,
		@Technical_References, @HasFundamental, @Fundamental_Header, @Fundamental_Description, @Fundamental_References,
		@CreationDate, GETDATE(), @PotentialProfit, @PotentialProfitValue, 1, @Rate)


	DECLARE  @KnokId BIGINT = SCOPE_IDENTITY()

	--Update knok traiding pair rate data
	Select @alr =  COUNT(*) from [Knoks_Prices].dbo.[ActivePair] 
	where [Knoks_Prices].dbo.[ActivePair].ExchangeId = @ExchangeId 
	  and [Knoks_Prices].dbo.[ActivePair].Base =  @Currency1 and [Knoks_Prices].dbo.[ActivePair].NonBase =  @Currency2
	
	if (@alr = 0)
	begin 
		INSERT INTO [Knoks_Prices].dbo.[ActivePair]
			(ExchangeId, Base, NonBase, LastDate) 
		Values
			(@ExchangeId, @Currency1 , @Currency2, DATEADD(day, @Duration, @CreationDate))
	end
	else
	begin 
	  Update [Knoks_Prices].dbo.[ActivePair] set
	  LastDate = DATEADD(day, @Duration, @CreationDate) Where [Knoks_Prices].dbo.[ActivePair].ExchangeId = @ExchangeId 
	  and [Knoks_Prices].dbo.[ActivePair].Base =  @Currency1 and [Knoks_Prices].dbo.[ActivePair].NonBase =  @Currency2 
	end
	INSERT INTO [Knoks_Prices].[dbo].[CRT_Data_LiveChart]
			([CRTD_TargetName]
			,[CRTD_CreationDate]
			,[CRTD_FirstQuote]
			,[CRTD_LastQuote]
			,[CRTD_PairSymbol]
			,[CRTD_BidOpeningValue]
			,[CRTD_BidClosingValue]
			,[CRTD_BidLowValue]
			,[CRTD_BidHighValue]
			,[CRTD_MidOpeningValue]
			,[CRTD_MidClosingValue]
			,[CRTD_MidLowValue]
			,[CRTD_MidHighValue]
			,[CRTD_DateModified]
			,[CRTD_Rows]
			,[ExchangeId]) 
		Values
			('LiveChart'
			,@CreationDate
			,0
			,@CreationDate
			,@Currency1 + @Currency2
			,@CurrentPrice
			,@CurrentPrice
			,@CurrentPrice
			,@CurrentPrice
			,0
			,0
			,0
			,0
			,GETUTCDATE()
			,0
			,@ExchangeId
			);
	INSERT INTO [Knoks_Prices].[dbo].[CRT_Data_1Minute] 
			([CRTD_Period]
				,[CRTD_FirstQuote]
				,[CRTD_LastQuote]
				,[CRTD_PairSymbol]
				,[CRTD_BidOpeningValue]
				,[CRTD_BidClosingValue]
				,[CRTD_BidLowValue]
				,[CRTD_BidHighValue]
				,[CRTD_MidOpeningValue]
				,[CRTD_MidClosingValue]
				,[CRTD_MidLowValue]
				,[CRTD_MidHighValue]
				,[CRTD_DateIn]
				,[CRTD_Rows]
				,[ExchangeId] 
				)
			SELECT CRTD_CreationDate
				,0
				,@CreationDate
				,CRTD_PairSymbol
				,[CRTD_BidOpeningValue]
				,[CRTD_BidClosingValue]
				,[CRTD_BidLowValue]
				,[CRTD_BidHighValue]
				,0
				,0
				,0
				,0
				,GETUTCDATE()
				,0
				,[ExchangeId]
				FROM [Knoks_Prices].[dbo].[CRT_Data_LiveChart] (nolock)
				WHERE CRTD_ID = (SELECT TOP 1 lc.CRTD_ID from [Knoks_Prices].[dbo].[CRT_Data_LiveChart] lc (nolock)
					WHERE lc.ExchangeId = @ExchangeId AND lc.[CRTD_PairSymbol] = @Currency1 + @Currency2 
						AND dateadd(mi, datediff(mi, 0, lc.CRTD_CreationDate), 0) <= dateadd(mi, datediff(mi, 0, @CreationDate), 0) 
					ORDER BY lc.CRTD_CreationDate DESC)
	EXEC [Knoks_Prices].[dbo].RecalcAggregations

	EXEC BO_GetKnoksFull @KnokId

	RETURN @RC
 END TRY 
	 
  BEGIN CATCH  
	   
	--IF( @TranStarted = 1 )    
	--ROLLBACK TRANSACTION  
	 
	 
	EXEC USP_LogError            
	EXEC USP_RethrowError                       
   
	IF @RC = 0
		SET @RC = 1   ---- Unexpected Error	   
		                     
	RETURN @RC                        
  END CATCH
GO
