USE [master]
GO
/****** Object:  Database [YB_Charts]    Script Date: 15/06/2017 15:02:35 ******/
CREATE DATABASE [YB_Charts]
-- CONTAINMENT = NONE
-- ON  PRIMARY 
--( NAME = N'YB_Charts', FILENAME = N'D:\MSSQL_Data\YB_Charts.mdf' , SIZE = 34546880KB , MAXSIZE = UNLIMITED, FILEGROWTH = 204800KB )
-- LOG ON 
--( NAME = N'YB_Charts_log', FILENAME = N'L:\MSSQL_Logs\YB_Charts_log.ldf' , SIZE = 6948928KB , MAXSIZE = 2048GB , FILEGROWTH = 204800KB )
GO
ALTER DATABASE [YB_Charts] SET COMPATIBILITY_LEVEL = 120
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [YB_Charts].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO
ALTER DATABASE [YB_Charts] SET ANSI_NULL_DEFAULT OFF 
GO
ALTER DATABASE [YB_Charts] SET ANSI_NULLS OFF 
GO
ALTER DATABASE [YB_Charts] SET ANSI_PADDING OFF 
GO
ALTER DATABASE [YB_Charts] SET ANSI_WARNINGS OFF 
GO
ALTER DATABASE [YB_Charts] SET ARITHABORT OFF 
GO
ALTER DATABASE [YB_Charts] SET AUTO_CLOSE OFF 
GO
ALTER DATABASE [YB_Charts] SET AUTO_SHRINK OFF 
GO
ALTER DATABASE [YB_Charts] SET AUTO_UPDATE_STATISTICS ON 
GO
ALTER DATABASE [YB_Charts] SET CURSOR_CLOSE_ON_COMMIT OFF 
GO
ALTER DATABASE [YB_Charts] SET CURSOR_DEFAULT  GLOBAL 
GO
ALTER DATABASE [YB_Charts] SET CONCAT_NULL_YIELDS_NULL OFF 
GO
ALTER DATABASE [YB_Charts] SET NUMERIC_ROUNDABORT OFF 
GO
ALTER DATABASE [YB_Charts] SET QUOTED_IDENTIFIER OFF 
GO
ALTER DATABASE [YB_Charts] SET RECURSIVE_TRIGGERS OFF 
GO
ALTER DATABASE [YB_Charts] SET  DISABLE_BROKER 
GO
ALTER DATABASE [YB_Charts] SET AUTO_UPDATE_STATISTICS_ASYNC OFF 
GO
ALTER DATABASE [YB_Charts] SET DATE_CORRELATION_OPTIMIZATION OFF 
GO
ALTER DATABASE [YB_Charts] SET TRUSTWORTHY OFF 
GO
ALTER DATABASE [YB_Charts] SET ALLOW_SNAPSHOT_ISOLATION OFF 
GO
ALTER DATABASE [YB_Charts] SET PARAMETERIZATION SIMPLE 
GO
ALTER DATABASE [YB_Charts] SET READ_COMMITTED_SNAPSHOT OFF 
GO
ALTER DATABASE [YB_Charts] SET HONOR_BROKER_PRIORITY OFF 
GO
ALTER DATABASE [YB_Charts] SET RECOVERY FULL 
GO
ALTER DATABASE [YB_Charts] SET  MULTI_USER 
GO
ALTER DATABASE [YB_Charts] SET PAGE_VERIFY CHECKSUM  
GO
ALTER DATABASE [YB_Charts] SET DB_CHAINING OFF 
GO
ALTER DATABASE [YB_Charts] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF ) 
GO
ALTER DATABASE [YB_Charts] SET TARGET_RECOVERY_TIME = 0 SECONDS 
GO
ALTER DATABASE [YB_Charts] SET DELAYED_DURABILITY = DISABLED 
GO
USE [YB_Charts]
GO
/****** Object:  User [reut.b]    Script Date: 15/06/2017 15:02:36 ******/
--CREATE USER [reut.b] FOR LOGIN [reut.b] WITH DEFAULT_SCHEMA=[dbo]
--GO
--/****** Object:  User [redshiftro]    Script Date: 15/06/2017 15:02:36 ******/
--CREATE USER [redshiftro] FOR LOGIN [redshiftro] WITH DEFAULT_SCHEMA=[dbo]
--GO
--/****** Object:  User [qauser]    Script Date: 15/06/2017 15:02:36 ******/
--CREATE USER [qauser] FOR LOGIN [qauser] WITH DEFAULT_SCHEMA=[dbo]
--GO
--/****** Object:  User [PRODIDC\SEC_Prod_TP_DB_RO]    Script Date: 15/06/2017 15:02:36 ******/
--CREATE USER [PRODIDC\SEC_Prod_TP_DB_RO] FOR LOGIN [PRODIDC\SEC_Prod_TP_DB_RO] WITH DEFAULT_SCHEMA=[dbo]
--GO
--/****** Object:  User [PRODIDC\max.u]    Script Date: 15/06/2017 15:02:36 ******/
--CREATE USER [PRODIDC\max.u] FOR LOGIN [PRODIDC\max.u] WITH DEFAULT_SCHEMA=[dbo]
--GO
--/****** Object:  User [dbrou]    Script Date: 15/06/2017 15:02:36 ******/
--CREATE USER [dbrou] FOR LOGIN [dbrou] WITH DEFAULT_SCHEMA=[dbo]
--GO
--ALTER ROLE [db_datareader] ADD MEMBER [reut.b]
--GO
--ALTER ROLE [db_datareader] ADD MEMBER [redshiftro]
--GO
--ALTER ROLE [db_datareader] ADD MEMBER [qauser]
--GO
--ALTER ROLE [db_datareader] ADD MEMBER [PRODIDC\SEC_Prod_TP_DB_RO]
--GO
--ALTER ROLE [db_datareader] ADD MEMBER [PRODIDC\max.u]
--GO
--ALTER ROLE [db_datareader] ADD MEMBER [dbrou]
GO
/****** Object:  UserDefinedFunction [dbo].[fnc_CRT_EndIntervalDate]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
--select [dbo].[fnc_CRT_EndIntervalDate] (GetDate(),@Year,@Month,@Week,@Day, @Hour, @Minute)
  select [dbo].[fnc_CRT_EndIntervalDate] (GetDate(),NULL , Null,   2 ,  Null ,Null, Null) 
*/

CREATE FUNCTION [dbo].[fnc_CRT_EndIntervalDate] (
									@Date datetime,
									@Year int,
									@Month int,
									@Week int,
									@Day int,
									@Hour int,
									@Minute int) returns datetime
as
begin
	declare @RoundedDate datetime

	set @RoundedDate = dateadd(millisecond, -datepart(millisecond, @Date) -datepart(second, @Date)*1000, @Date)

	if @Minute is not null
	Begin
		if @Minute > 0
			set @RoundedDate = dateadd(minute, datepart(minute, @RoundedDate) / @Minute * @Minute - datepart(minute, @RoundedDate), @RoundedDate)
			set @RoundedDate = dateadd(minute,@Minute,@RoundedDate)
	End
	Else Begin
		set @Minute = 60
		set @RoundedDate = dateadd(minute, datepart(minute, @RoundedDate) / @Minute * @Minute - datepart(minute, @RoundedDate), @RoundedDate)	
    End
--select  @Minute, @Date, @RoundedDate

	if @Hour is not null
		Begin
	
			set @RoundedDate = dateadd(hour, datepart(hour, @RoundedDate) / @Hour * @Hour - datepart(hour, @RoundedDate), @RoundedDate)
			set @RoundedDate = dateadd(hour,@Hour,@RoundedDate)
		End


--select  @Hour, @Date, @RoundedDate

	if @Day is not null
		Begin
			
			If @Day > 1
				set @RoundedDate = 	@RoundedDate - @Day +1
			set @RoundedDate = Cast(Convert(char(10),DateAdd(MINUTE,-DatePart(MINUTE,@RoundedDate), @RoundedDate),121) as datetime )
			--set @RoundedDate = dateadd(day, datepart(day, @RoundedDate) / @Day * @Day - datepart(day, @RoundedDate), @RoundedDate)
		
			IF DatePart(Year,@RoundedDate) < DatePart(Year,@Date)
				Set @RoundedDate = Cast( Cast(DatePart(Year,@Date) as varchar(4))+ '-01-01 00:00:00.000' as datetime)

			set @RoundedDate = dateadd(day,@Day,@RoundedDate)
			
		End



--select  @Day, @Date, @RoundedDate


	if @Week Is Not Null
	Begin
			
			select @RoundedDate = cast(floor(cast(@RoundedDate as float)) as datetime) 
			IF datepart(weekday, @RoundedDate) > 1

				set @RoundedDate = dateadd(day, -datepart(weekday, @RoundedDate)+1 , @RoundedDate)
			
			IF @Week > 1
				set @RoundedDate = dateadd(day, -7*(@Week-1) , @RoundedDate)


			IF DatePart(Year,@RoundedDate) < DatePart(Year,@Date)
				Set @RoundedDate = Cast( Cast(DatePart(Year,@Date) as varchar(4))+ '-01-01 00:00:00.000' as datetime)

			IF DatePart(dw,@RoundedDate) <> 1  
				Set @RoundedDate = DateAdd(day,-DatePart(dw,@RoundedDate)+1,@RoundedDate )

			--set @RoundedDate = dateadd(day,(7*(@Week+1)),@RoundedDate)
			set @RoundedDate = dateadd(week,@Week,@RoundedDate)

	End


		if @Month Is Not Null
		Begin

			Select @RoundedDate = Cast(Convert(char(7),@RoundedDate, 121  ) + '-01 00:00:00.000' as datetime)

			Set @RoundedDate = DateAdd(Month,-(@Month-1),@RoundedDate) 
			IF DatePart(Year,@RoundedDate) < DatePart(Year,@Date)
				Set @RoundedDate = Cast( Cast(DatePart(Year,@Date) as varchar(4))+ '-01-01 00:00:00.000' as datetime)

			set @RoundedDate = dateadd(Month,@Month,@RoundedDate)
		End

		if @Year Is Not Null
		Begin
			Set @RoundedDate = Cast( Cast(DatePart(Year,@Date) as varchar(4))+ '-01-01 00:00:00.000' as datetime)
			Set @RoundedDate = DateAdd(Year,-(@Year-1),@RoundedDate) 

			set @RoundedDate = dateadd(Year,@Year,@RoundedDate)
		End


    set @RoundedDate = dateadd(second,-1,@RoundedDate)
	set @RoundedDate = dateadd(millisecond,998,@RoundedDate)
	return @RoundedDate
end


GO
/****** Object:  UserDefinedFunction [dbo].[fnc_CRT_RoundDate]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


/*
--select [dbo].[fnc_CRT_RoundDate] (GetDate(),@Year,@Month,@Week,@Day,@Hour,@Minute)
  select [dbo].[fnc_CRT_RoundDate] (GetDate(),NULL ,Null,  2 ,Null ,Null, Null) 
*/

CREATE function [dbo].[fnc_CRT_RoundDate](@Date datetime,
									@Year int,
									@Month int,
									@Week int,
									@Day int,
									@Hour int,
									@Minute int) returns datetime
as
begin
	declare @RoundedDate datetime

	set @RoundedDate = dateadd(millisecond, -datepart(millisecond, @Date) -datepart(second, @Date)*1000, @Date)

	if @Minute is not null
	Begin
		if @Minute > 0
			set @RoundedDate = dateadd(minute, datepart(minute, @RoundedDate) / @Minute * @Minute - datepart(minute, @RoundedDate), @RoundedDate)

	End
	Else Begin
		set @Minute = 60
		set @RoundedDate = dateadd(minute, datepart(minute, @RoundedDate) / @Minute * @Minute - datepart(minute, @RoundedDate), @RoundedDate)	
    End
--select  @Minute, @Date, @RoundedDate

	if @Hour is not null
		Begin
	
			set @RoundedDate = dateadd(hour, datepart(hour, @RoundedDate) / @Hour * @Hour - datepart(hour, @RoundedDate), @RoundedDate)
		End


--select  @Hour, @Date, @RoundedDate

	if @Day is not null
		Begin
			
			If @Day > 1
				set @RoundedDate = 	@RoundedDate - @Day +1
			set @RoundedDate = Cast(Convert(char(10),DateAdd(MINUTE,-DatePart(MINUTE,@RoundedDate), @RoundedDate),121) as datetime )
			--set @RoundedDate = dateadd(day, datepart(day, @RoundedDate) / @Day * @Day - datepart(day, @RoundedDate), @RoundedDate)
		
			IF DatePart(Year,@RoundedDate) < DatePart(Year,@Date)
				Set @RoundedDate = Cast( Cast(DatePart(Year,@Date) as varchar(4))+ '-01-01 00:00:00.000' as datetime)

		End


				



--select  @Day, @Date, @RoundedDate


	if @Week Is Not Null
	Begin
			
			select @RoundedDate = cast(floor(cast(@RoundedDate as float)) as datetime) 
			IF datepart(weekday, @RoundedDate) > 1

				set @RoundedDate = dateadd(day, -datepart(weekday, @RoundedDate)+1 , @RoundedDate)
			
			IF @Week > 1
				set @RoundedDate = dateadd(day, -7*(@Week-1) , @RoundedDate)

			IF DatePart(Year,@RoundedDate) < DatePart(Year,@Date)
				Set @RoundedDate = Cast( Cast(DatePart(Year,@Date) as varchar(4))+ '-01-01 00:00:00.000' as datetime)


			IF DatePart(dw,@RoundedDate) <> 1  
				Set @RoundedDate = DateAdd(day,-DatePart(dw,@RoundedDate)+1,@RoundedDate )

			
	End


		if @Month Is Not Null
		Begin

			Select @RoundedDate = Cast(Convert(char(7),@RoundedDate, 121  ) + '-01 00:00:00.000' as datetime)

			Set @RoundedDate = DateAdd(Month,-(@Month-1),@RoundedDate) 
			IF DatePart(Year,@RoundedDate) < DatePart(Year,@Date)
				Set @RoundedDate = Cast( Cast(DatePart(Year,@Date) as varchar(4))+ '-01-01 00:00:00.000' as datetime)


		End

		if @Year Is Not Null
		Begin
			Set @RoundedDate = Cast( Cast(DatePart(Year,@Date) as varchar(4))+ '-01-01 00:00:00.000' as datetime)
			Set @RoundedDate = DateAdd(Year,-(@Year-1),@RoundedDate) 
		End

	return @RoundedDate
end


GO
/****** Object:  UserDefinedFunction [dbo].[fnc_CRT_StartIntervalDate]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[fnc_CRT_StartIntervalDate] (
									@Date datetime,
									@Year int=Null,
									@Month int=Null,
									@Week int=Null,
									@Day int=Null,
									@Hour int=Null,
									@Minute int=Null) returns datetime
as
begin
	declare @RoundedDate datetime

	set @RoundedDate = dateadd(millisecond, -datepart(millisecond, @Date) -datepart(second, @Date)*1000, @Date)

	if @Minute is not null
	Begin
		if @Minute > 0
			set @RoundedDate = dateadd(minute, datepart(minute, @RoundedDate) / @Minute * @Minute - datepart(minute, @RoundedDate), @RoundedDate)

	End
	Else Begin
		set @Minute = 60
		set @RoundedDate = dateadd(minute, datepart(minute, @RoundedDate) / @Minute * @Minute - datepart(minute, @RoundedDate), @RoundedDate)	
    End
--select  @Minute, @Date, @RoundedDate

	if @Hour is not null
		Begin
	
			set @RoundedDate = dateadd(hour, datepart(hour, @RoundedDate) / @Hour * @Hour - datepart(hour, @RoundedDate), @RoundedDate)
		End


--select  @Hour, @Date, @RoundedDate

	if @Day is not null
		Begin
			
			If @Day > 1
				set @RoundedDate = 	@RoundedDate - @Day +1
			set @RoundedDate = Cast(Convert(char(10),DateAdd(MINUTE,-DatePart(MINUTE,@RoundedDate), @RoundedDate),121) as datetime )
			--set @RoundedDate = dateadd(day, datepart(day, @RoundedDate) / @Day * @Day - datepart(day, @RoundedDate), @RoundedDate)
		
			IF DatePart(Year,@RoundedDate) < DatePart(Year,@Date)
				Set @RoundedDate = Cast( Cast(DatePart(Year,@Date) as varchar(4))+ '-01-01 00:00:00.000' as datetime)
		End



--select  @Day, @Date, @RoundedDate


	if @Week Is Not Null
	Begin
			
			select @RoundedDate = cast(floor(cast(@RoundedDate as float)) as datetime) 
			IF datepart(weekday, @RoundedDate) > 1

				set @RoundedDate = dateadd(day, -datepart(weekday, @RoundedDate)+1 , @RoundedDate)
			
			IF @Week > 1
				set @RoundedDate = dateadd(day, -7*(@Week-1) , @RoundedDate)


			IF DatePart(Year,@RoundedDate) < DatePart(Year,@Date)
				Set @RoundedDate = Cast( Cast(DatePart(Year,@Date) as varchar(4))+ '-01-01 00:00:00.000' as datetime)

			IF DatePart(dw,@RoundedDate) <> 1  
				Set @RoundedDate = DateAdd(day,-DatePart(dw,@RoundedDate)+1,@RoundedDate )

			
	End


		if @Month Is Not Null
		Begin

			Select @RoundedDate = Cast(Convert(char(7),@RoundedDate, 121  ) + '-01 00:00:00.000' as datetime)

			Set @RoundedDate = DateAdd(Month,-(@Month-1),@RoundedDate) 
			IF DatePart(Year,@RoundedDate) < DatePart(Year,@Date)
				Set @RoundedDate = Cast( Cast(DatePart(Year,@Date) as varchar(4))+ '-01-01 00:00:00.000' as datetime)


		End

		if @Year Is Not Null
		Begin
			Set @RoundedDate = Cast( Cast(DatePart(Year,@Date) as varchar(4))+ '-01-01 00:00:00.000' as datetime)
			Set @RoundedDate = DateAdd(Year,-(@Year-1),@RoundedDate) 
		End

	return @RoundedDate
end


GO
/****** Object:  Table [dbo].[ChartsTemplate]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ChartsTemplate](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Client] [varchar](100) NOT NULL,
	[User] [varchar](300) NOT NULL,
	[ChartName] [varchar](300) NOT NULL,
	[Symbol] [varchar](50) NOT NULL,
	[Resolution] [varchar](10) NOT NULL,
	[LastModified] [datetime] NOT NULL,
	[Content] [text] NOT NULL,
	[CreateDate] [datetime] NOT NULL DEFAULT (getutcdate()),
PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CRT_Data_15Minutes]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CRT_Data_15Minutes](
	[CRTD_ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL CONSTRAINT [DF_CRT_Data_15Minutes_CRTD_DateIn]  DEFAULT (getdate()),
 CONSTRAINT [PK_NC_dbo_CRT_Data_15Minutes_#CRTD_ID] PRIMARY KEY NONCLUSTERED 
(
	[CRTD_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CRT_Data_1Day]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CRT_Data_1Day](
	[CRTD_ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL CONSTRAINT [DF_CRT_Data_1Day_CRTD_DateIn]  DEFAULT (getdate()),
 CONSTRAINT [PK_NC_dbo_CRT_Data_1Day_#CRTD_ID] PRIMARY KEY NONCLUSTERED 
(
	[CRTD_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CRT_Data_1Hour]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CRT_Data_1Hour](
	[CRTD_ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL CONSTRAINT [DF_CRT_Data_1Hour_CRTD_DateIn]  DEFAULT (getdate()),
 CONSTRAINT [PK_NC_dbo_CRT_Data_1Hour_#CRTD_ID] PRIMARY KEY NONCLUSTERED 
(
	[CRTD_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CRT_Data_1Minute]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CRT_Data_1Minute](
	[CRTD_ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL CONSTRAINT [DF_CRT_Data_1Minute_CRTD_DateIn]  DEFAULT (getdate()),
	[CRTD_Rows] [int] NULL,
 CONSTRAINT [PK_NC_dbo_CRT_Data_1Minute_#CRTD_ID] PRIMARY KEY NONCLUSTERED 
(
	[CRTD_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CRT_Data_1Month]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CRT_Data_1Month](
	[CRTD_ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL CONSTRAINT [DF_CRT_Data_1Month_CRTD_DateIn]  DEFAULT (getdate()),
 CONSTRAINT [PK_NC_dbo_CRT_Data_1Month_#CRTD_ID] PRIMARY KEY NONCLUSTERED 
(
	[CRTD_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CRT_Data_1Week]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CRT_Data_1Week](
	[CRTD_ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL CONSTRAINT [DF_CRT_Data_1Week_CRTD_DateIn]  DEFAULT (getdate()),
 CONSTRAINT [PK_NC_dbo_CRT_Data_1Week_#CRTD_ID] PRIMARY KEY NONCLUSTERED 
(
	[CRTD_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CRT_Data_2Hours]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CRT_Data_2Hours](
	[CRTD_ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL CONSTRAINT [DF_CRT_Data_2Hours_CRTD_DateIn]  DEFAULT (getdate()),
 CONSTRAINT [PK_NC_dbo_CRT_Data_2Hours_#CRTD_ID] PRIMARY KEY NONCLUSTERED 
(
	[CRTD_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CRT_Data_30Minutes]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CRT_Data_30Minutes](
	[CRTD_ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL CONSTRAINT [DF_CRT_Data_30Minutes_CRTD_DateIn]  DEFAULT (getdate()),
 CONSTRAINT [PK_NC_dbo_CRT_Data_30Minutes_#CRTD_ID] PRIMARY KEY NONCLUSTERED 
(
	[CRTD_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CRT_Data_4Hours]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CRT_Data_4Hours](
	[CRTD_ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL CONSTRAINT [DF_CRT_Data_4Hours_CRTD_DateIn]  DEFAULT (getdate()),
 CONSTRAINT [PK_NC_dbo_CRT_Data_4Hours_#CRTD_ID] PRIMARY KEY NONCLUSTERED 
(
	[CRTD_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CRT_Data_5Minutes]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CRT_Data_5Minutes](
	[CRTD_ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL CONSTRAINT [DF_CRT_Data_5Minutes_CRTD_DateIn]  DEFAULT (getdate()),
 CONSTRAINT [PK_NC_dbo_CRT_Data_5Minutes_#CRTD_ID] PRIMARY KEY NONCLUSTERED 
(
	[CRTD_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CRT_Data_8Hours]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CRT_Data_8Hours](
	[CRTD_ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL CONSTRAINT [DF_CRT_Data_8Hours_CRTD_DateIn]  DEFAULT (getdate()),
 CONSTRAINT [PK_NC_dbo_CRT_Data_8Hours_#CRTD_ID] PRIMARY KEY NONCLUSTERED 
(
	[CRTD_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CRT_Data_LiveChart]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CRT_Data_LiveChart](
	[CRTD_ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[CRTD_TargetName] [varchar](50) NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateModified] [datetime] NOT NULL CONSTRAINT [DF_CRT_Data_LiveChart_CRTD_DateModified]  DEFAULT (getdate()),
	[CRTD_Rows] [int] NULL,
 CONSTRAINT [PK_NC_CRT_Data_LiveChart_#CRTD_ID] PRIMARY KEY NONCLUSTERED 
(
	[CRTD_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CRT_LastQuote]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CRT_LastQuote](
	[TableName] [varchar](20) NULL,
	[CRTD_PairSymbol] [varchar](50) NULL,
	[LAST_CRTD_Period] [datetime] NULL,
	[NEXT_CRTD_Period] [datetime] NULL,
	[Next_End_period] [datetime] NULL,
	[LastQuote] [datetime] NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CRT_Tasks]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CRT_Tasks](
	[CRTT_ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[CRTT_Name] [varchar](100) NOT NULL,
	[CRTT_TableName] [sysname] NOT NULL,
	[CRTT_Source_TableName] [sysname] NOT NULL,
	[CRTT_UnitDefinition] [varchar](15) NOT NULL,
	[CRTT_LastRun] [datetime] NULL,
	[CRTT_IsActive] [bit] NOT NULL CONSTRAINT [DF_CRT_Tasks_CRTT_IsActive]  DEFAULT ((1)),
	[CRTT_LastRowCount] [int] NULL,
	[CRTT_LastModifiedDate] [datetime] NULL,
 CONSTRAINT [PK_CRT_Tasks] PRIMARY KEY CLUSTERED 
(
	[CRTT_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Eli_Daily_Nov16]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Eli_Daily_Nov16](
	[CRTD_Period] [varchar](50) NULL,
	[CRTD_FirstQuote] [varchar](50) NULL,
	[CRTD_LastQuote] [varchar](50) NULL,
	[CRTD_PairSymbol] [varchar](50) NULL,
	[CRTD_BidOpeningValue] [float] NULL,
	[CRTD_BidClosingValue] [float] NULL,
	[CRTD_BidLowValue] [float] NULL,
	[CRTD_BidHighValue] [float] NULL,
	[CRTD_MidOpeningValue] [float] NULL,
	[CRTD_MidClosingValue] [float] NULL,
	[CRTD_MidLowValue] [float] NULL,
	[CRTD_MidHighValue] [float] NULL,
	[CRTD_DateIn] [float] NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Eli_Monthly_Nov16]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Eli_Monthly_Nov16](
	[Ticker] [varchar](50) NULL,
	[CRTD_Period] [varchar](50) NULL,
	[CRTD_FirstQuote] [varchar](50) NULL,
	[CRTD_LastQuote] [varchar](50) NULL,
	[CRTD_PairSymbol] [varchar](50) NULL,
	[CRTD_BidOpeningValue] [float] NULL,
	[CRTD_BidClosingValue] [float] NULL,
	[CRTD_BidLowValue] [float] NULL,
	[CRTD_BidHighValue] [float] NULL,
	[CRTD_MidOpeningValue] [float] NULL,
	[CRTD_MidClosingValue] [float] NULL,
	[CRTD_MidLowValue] [float] NULL,
	[CRTD_MidHighValue] [float] NULL,
	[CRTD_DateIn] [float] NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Eli_Weekly_Nov16]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Eli_Weekly_Nov16](
	[CRTD_Period] [varchar](50) NULL,
	[CRTD_FirstQuote] [varchar](50) NULL,
	[CRTD_LastQuote] [varchar](50) NULL,
	[CRTD_PairSymbol] [varchar](50) NULL,
	[CRTD_BidOpeningValue] [float] NULL,
	[CRTD_BidClosingValue] [float] NULL,
	[CRTD_BidLowValue] [float] NULL,
	[CRTD_BidHighValue] [float] NULL,
	[CRTD_MidOpeningValue] [float] NULL,
	[CRTD_MidClosingValue] [float] NULL,
	[CRTD_MidLowValue] [float] NULL,
	[CRTD_MidHighValue] [float] NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ETF-Daily-Nov16]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ETF-Daily-Nov16](
	[CRTD_Period] [varchar](50) NULL,
	[CRTD_FirstQuote] [datetime] NULL,
	[CRTD_LastQuote] [datetime] NULL,
	[CRTD_PairSymbol] [varchar](50) NULL,
	[CRTD_BidOpeningValue] [float] NULL,
	[CRTD_BidClosingValue] [float] NULL,
	[CRTD_BidLowValue] [float] NULL,
	[CRTD_BidHighValue] [float] NULL,
	[CRTD_MidOpeningValue] [float] NULL,
	[CRTD_MidClosingValue] [float] NULL,
	[CRTD_MidLowValue] [float] NULL,
	[CRTD_MidHighValue] [float] NULL,
	[CRTD_DateIn] [float] NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[HistData]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[HistData](
	[HD_Date] [datetime] NULL,
	[HD_Time] [varchar](10) NULL,
	[HD_Open] [float] NULL,
	[HD_High] [float] NULL,
	[HD_Low] [float] NULL,
	[HD_Close] [float] NULL,
	[HD_Volume] [bigint] NULL,
	[HD_Interval] [int] NULL,
	[HD_StockName] [varchar](50) NULL,
	[HD_InstrumentSymbol] [varchar](10) NULL,
	[HD_FileName] [varchar](50) NULL,
	[TargetTable] [varchar](100) NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[MinIds]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MinIds](
	[TableName] [sysname] NOT NULL,
	[MinId] [bigint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[StudyTemplate]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[StudyTemplate](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Client] [varchar](100) NOT NULL,
	[User] [varchar](300) NOT NULL,
	[TemplateName] [varchar](300) NOT NULL,
	[Content] [text] NOT NULL,
	[CreateDate] [datetime] NOT NULL DEFAULT (getutcdate()),
PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TMP_CRT_Data_1Month]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TMP_CRT_Data_1Month](
	[CRTD_ID] [int] IDENTITY(1,1) NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TMP_Data_15Minutes]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TMP_Data_15Minutes](
	[CRTD_ID] [int] IDENTITY(-101392,-1) NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TMP_Data_1Day]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TMP_Data_1Day](
	[CRTD_ID] [int] IDENTITY(-185516,-1) NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TMP_Data_1Hour]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TMP_Data_1Hour](
	[CRTD_ID] [int] IDENTITY(-80779,-1) NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TMP_Data_1Minute]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TMP_Data_1Minute](
	[CRTD_ID] [int] IDENTITY(-66579,-1) NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TMP_Data_1Month]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TMP_Data_1Month](
	[CRTD_ID] [int] IDENTITY(-34688,-1) NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TMP_Data_1Week]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TMP_Data_1Week](
	[CRTD_ID] [int] IDENTITY(-95995,-1) NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TMP_Data_30Minutes]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TMP_Data_30Minutes](
	[CRTD_ID] [int] IDENTITY(-86192,-1) NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TMP_Data_4Hours]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TMP_Data_4Hours](
	[CRTD_ID] [int] IDENTITY(-115905,-1) NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TMP_Data_5Minutes]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TMP_Data_5Minutes](
	[CRTD_ID] [int] IDENTITY(-172049,-1) NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[YP_CRT_Data_15Minutes]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[YP_CRT_Data_15Minutes](
	[CRTD_ID] [int] NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[YP_CRT_Data_1Day]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[YP_CRT_Data_1Day](
	[CRTD_ID] [int] NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[YP_CRT_Data_1Hour]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[YP_CRT_Data_1Hour](
	[CRTD_ID] [int] NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[YP_CRT_Data_1Minute]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[YP_CRT_Data_1Minute](
	[CRTD_ID] [int] NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[YP_CRT_Data_1Month]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[YP_CRT_Data_1Month](
	[CRTD_ID] [int] NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[YP_CRT_Data_1Week]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[YP_CRT_Data_1Week](
	[CRTD_ID] [int] NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[YP_CRT_Data_2Hours]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[YP_CRT_Data_2Hours](
	[CRTD_ID] [int] NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[YP_CRT_Data_30Minutes]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[YP_CRT_Data_30Minutes](
	[CRTD_ID] [int] NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[YP_CRT_Data_4Hours]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[YP_CRT_Data_4Hours](
	[CRTD_ID] [int] NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[YP_CRT_Data_5Minutes]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[YP_CRT_Data_5Minutes](
	[CRTD_ID] [int] NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[YP_CRT_Data_8Hours]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[YP_CRT_Data_8Hours](
	[CRTD_ID] [int] NOT NULL,
	[CRTD_Period] [datetime] NOT NULL,
	[CRTD_FirstQuote] [datetime] NOT NULL,
	[CRTD_LastQuote] [datetime] NOT NULL,
	[CRTD_PairSymbol] [varchar](50) NOT NULL,
	[CRTD_BidOpeningValue] [float] NOT NULL,
	[CRTD_BidClosingValue] [float] NOT NULL,
	[CRTD_BidLowValue] [float] NOT NULL,
	[CRTD_BidHighValue] [float] NOT NULL,
	[CRTD_MidOpeningValue] [float] NOT NULL,
	[CRTD_MidClosingValue] [float] NOT NULL,
	[CRTD_MidLowValue] [float] NOT NULL,
	[CRTD_MidHighValue] [float] NOT NULL,
	[CRTD_DateIn] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_ChartsTemplate_Client_User]    Script Date: 15/06/2017 15:02:37 ******/
CREATE NONCLUSTERED INDEX [IX_ChartsTemplate_Client_User] ON [dbo].[ChartsTemplate]
(
	[Client] ASC,
	[User] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_CRT_Data_15Minutes_CRTD_PairSymbol_Period_INC]    Script Date: 15/06/2017 15:02:37 ******/
CREATE NONCLUSTERED INDEX [IX_CRT_Data_15Minutes_CRTD_PairSymbol_Period_INC] ON [dbo].[CRT_Data_15Minutes]
(
	[CRTD_PairSymbol] ASC,
	[CRTD_Period] DESC
)
INCLUDE ( 	[CRTD_BidOpeningValue],
	[CRTD_BidClosingValue],
	[CRTD_BidLowValue],
	[CRTD_BidHighValue],
	[CRTD_MidOpeningValue],
	[CRTD_MidClosingValue],
	[CRTD_MidLowValue],
	[CRTD_MidHighValue]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_CRT_Data_1Day_CRTD_PairSymbol_Period_INC]    Script Date: 15/06/2017 15:02:37 ******/
CREATE NONCLUSTERED INDEX [IX_CRT_Data_1Day_CRTD_PairSymbol_Period_INC] ON [dbo].[CRT_Data_1Day]
(
	[CRTD_PairSymbol] ASC,
	[CRTD_Period] DESC
)
INCLUDE ( 	[CRTD_BidOpeningValue],
	[CRTD_BidClosingValue],
	[CRTD_BidLowValue],
	[CRTD_BidHighValue],
	[CRTD_MidOpeningValue],
	[CRTD_MidClosingValue],
	[CRTD_MidLowValue],
	[CRTD_MidHighValue]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_CRT_Data_1Hour_CRTD_PairSymbol_Period_INC]    Script Date: 15/06/2017 15:02:37 ******/
CREATE NONCLUSTERED INDEX [IX_CRT_Data_1Hour_CRTD_PairSymbol_Period_INC] ON [dbo].[CRT_Data_1Hour]
(
	[CRTD_PairSymbol] ASC,
	[CRTD_Period] DESC
)
INCLUDE ( 	[CRTD_BidOpeningValue],
	[CRTD_BidClosingValue],
	[CRTD_BidLowValue],
	[CRTD_BidHighValue],
	[CRTD_MidOpeningValue],
	[CRTD_MidClosingValue],
	[CRTD_MidLowValue],
	[CRTD_MidHighValue]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_CRT_Data_1Minute_CRTD_PairSymbol_Period_INC]    Script Date: 15/06/2017 15:02:37 ******/
CREATE NONCLUSTERED INDEX [IX_CRT_Data_1Minute_CRTD_PairSymbol_Period_INC] ON [dbo].[CRT_Data_1Minute]
(
	[CRTD_PairSymbol] ASC,
	[CRTD_Period] DESC
)
INCLUDE ( 	[CRTD_ID],
	[CRTD_BidOpeningValue],
	[CRTD_BidLowValue],
	[CRTD_BidHighValue],
	[CRTD_MidOpeningValue],
	[CRTD_MidLowValue],
	[CRTD_MidHighValue],
	[CRTD_BidClosingValue],
	[CRTD_MidClosingValue]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_CRTD_PairSymbol_CRTD_Period_INC]    Script Date: 15/06/2017 15:02:37 ******/
CREATE NONCLUSTERED INDEX [IX_CRTD_PairSymbol_CRTD_Period_INC] ON [dbo].[CRT_Data_1Minute]
(
	[CRTD_PairSymbol] ASC,
	[CRTD_Period] ASC
)
INCLUDE ( 	[CRTD_FirstQuote],
	[CRTD_LastQuote],
	[CRTD_BidOpeningValue],
	[CRTD_BidClosingValue],
	[CRTD_BidLowValue],
	[CRTD_BidHighValue],
	[CRTD_MidOpeningValue],
	[CRTD_MidClosingValue],
	[CRTD_MidLowValue],
	[CRTD_MidHighValue]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [ix_CRTD_Period_INC]    Script Date: 15/06/2017 15:02:37 ******/
CREATE NONCLUSTERED INDEX [ix_CRTD_Period_INC] ON [dbo].[CRT_Data_1Minute]
(
	[CRTD_Period] ASC
)
INCLUDE ( 	[CRTD_LastQuote],
	[CRTD_PairSymbol]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_CRT_Data_1Month_CRTD_PairSymbol_Period_INC]    Script Date: 15/06/2017 15:02:37 ******/
CREATE NONCLUSTERED INDEX [IX_CRT_Data_1Month_CRTD_PairSymbol_Period_INC] ON [dbo].[CRT_Data_1Month]
(
	[CRTD_PairSymbol] ASC,
	[CRTD_Period] DESC
)
INCLUDE ( 	[CRTD_ID],
	[CRTD_BidClosingValue],
	[CRTD_MidClosingValue]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_CRT_Data_1Week_CRTD_PairSymbol_Period_INC]    Script Date: 15/06/2017 15:02:37 ******/
CREATE NONCLUSTERED INDEX [IX_CRT_Data_1Week_CRTD_PairSymbol_Period_INC] ON [dbo].[CRT_Data_1Week]
(
	[CRTD_PairSymbol] ASC,
	[CRTD_Period] DESC
)
INCLUDE ( 	[CRTD_BidOpeningValue],
	[CRTD_BidClosingValue],
	[CRTD_BidLowValue],
	[CRTD_BidHighValue],
	[CRTD_MidOpeningValue],
	[CRTD_MidClosingValue],
	[CRTD_MidLowValue],
	[CRTD_MidHighValue]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_CRT_Data_2Hours_CRTD_PairSymbol_Period_INC]    Script Date: 15/06/2017 15:02:37 ******/
CREATE NONCLUSTERED INDEX [IX_CRT_Data_2Hours_CRTD_PairSymbol_Period_INC] ON [dbo].[CRT_Data_2Hours]
(
	[CRTD_PairSymbol] ASC,
	[CRTD_Period] DESC
)
INCLUDE ( 	[CRTD_BidOpeningValue],
	[CRTD_BidClosingValue],
	[CRTD_BidLowValue],
	[CRTD_BidHighValue],
	[CRTD_MidOpeningValue],
	[CRTD_MidClosingValue],
	[CRTD_MidLowValue],
	[CRTD_MidHighValue]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_CRT_Data_30Minutes_CRTD_PairSymbol_Period_INC]    Script Date: 15/06/2017 15:02:37 ******/
CREATE NONCLUSTERED INDEX [IX_CRT_Data_30Minutes_CRTD_PairSymbol_Period_INC] ON [dbo].[CRT_Data_30Minutes]
(
	[CRTD_PairSymbol] ASC,
	[CRTD_Period] DESC
)
INCLUDE ( 	[CRTD_BidOpeningValue],
	[CRTD_BidClosingValue],
	[CRTD_BidLowValue],
	[CRTD_BidHighValue],
	[CRTD_MidOpeningValue],
	[CRTD_MidClosingValue],
	[CRTD_MidLowValue],
	[CRTD_MidHighValue]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_CRT_Data_4Hours_CRTD_PairSymbol_Period_INC]    Script Date: 15/06/2017 15:02:37 ******/
CREATE NONCLUSTERED INDEX [IX_CRT_Data_4Hours_CRTD_PairSymbol_Period_INC] ON [dbo].[CRT_Data_4Hours]
(
	[CRTD_PairSymbol] ASC,
	[CRTD_Period] DESC
)
INCLUDE ( 	[CRTD_BidOpeningValue],
	[CRTD_BidClosingValue],
	[CRTD_BidLowValue],
	[CRTD_BidHighValue],
	[CRTD_MidOpeningValue],
	[CRTD_MidClosingValue],
	[CRTD_MidLowValue],
	[CRTD_MidHighValue]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_CRT_Data_5Minutes_CRTD_PairSymbol_Period_INC]    Script Date: 15/06/2017 15:02:37 ******/
CREATE NONCLUSTERED INDEX [IX_CRT_Data_5Minutes_CRTD_PairSymbol_Period_INC] ON [dbo].[CRT_Data_5Minutes]
(
	[CRTD_PairSymbol] ASC,
	[CRTD_Period] DESC
)
INCLUDE ( 	[CRTD_BidOpeningValue],
	[CRTD_BidClosingValue],
	[CRTD_BidLowValue],
	[CRTD_BidHighValue],
	[CRTD_MidOpeningValue],
	[CRTD_MidClosingValue],
	[CRTD_MidLowValue],
	[CRTD_MidHighValue]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_CRT_Data_8Hours_CRTD_PairSymbol_Period_INC]    Script Date: 15/06/2017 15:02:37 ******/
CREATE NONCLUSTERED INDEX [IX_CRT_Data_8Hours_CRTD_PairSymbol_Period_INC] ON [dbo].[CRT_Data_8Hours]
(
	[CRTD_PairSymbol] ASC,
	[CRTD_Period] DESC
)
INCLUDE ( 	[CRTD_BidOpeningValue],
	[CRTD_BidClosingValue],
	[CRTD_BidLowValue],
	[CRTD_BidHighValue],
	[CRTD_MidOpeningValue],
	[CRTD_MidClosingValue],
	[CRTD_MidLowValue],
	[CRTD_MidHighValue]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_CRT_Data_LiveChart_PairSymbol_TargetName_INC]    Script Date: 15/06/2017 15:02:37 ******/
CREATE NONCLUSTERED INDEX [IX_CRT_Data_LiveChart_PairSymbol_TargetName_INC] ON [dbo].[CRT_Data_LiveChart]
(
	[CRTD_PairSymbol] ASC,
	[CRTD_TargetName] ASC
)
INCLUDE ( 	[CRTD_Period],
	[CRTD_BidOpeningValue],
	[CRTD_BidClosingValue],
	[CRTD_BidLowValue],
	[CRTD_BidHighValue],
	[CRTD_MidOpeningValue],
	[CRTD_MidClosingValue],
	[CRTD_MidLowValue],
	[CRTD_MidHighValue]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [ix_CRTD_PairSymbol]    Script Date: 15/06/2017 15:02:37 ******/
CREATE NONCLUSTERED INDEX [ix_CRTD_PairSymbol] ON [dbo].[CRT_LastQuote]
(
	[CRTD_PairSymbol] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [ix_TableName]    Script Date: 15/06/2017 15:02:37 ******/
CREATE NONCLUSTERED INDEX [ix_TableName] ON [dbo].[CRT_LastQuote]
(
	[TableName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_StudyTemplate_Client_User]    Script Date: 15/06/2017 15:02:37 ******/
CREATE NONCLUSTERED INDEX [IX_StudyTemplate_Client_User] ON [dbo].[StudyTemplate]
(
	[Client] ASC,
	[User] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_StudyTemplate_Client_User_TemplateName]    Script Date: 15/06/2017 15:02:37 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_StudyTemplate_Client_User_TemplateName] ON [dbo].[StudyTemplate]
(
	[Client] ASC,
	[User] ASC,
	[TemplateName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[Charts_HistoricalData_Process]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Charts_HistoricalData_Process]

AS

Truncate table [YB_Charts].dbo.YP_CRT_Data_1Minute
Truncate table [YB_Charts].dbo.YP_CRT_Data_5Minutes
Truncate table [YB_Charts].dbo.YP_CRT_Data_15Minutes
Truncate table [YB_Charts].dbo.YP_CRT_Data_30Minutes
Truncate table [YB_Charts].dbo.YP_CRT_Data_1Hour
Truncate table [YB_Charts].dbo.YP_CRT_Data_2Hours
Truncate table [YB_Charts].dbo.YP_CRT_Data_4Hours
Truncate table [YB_Charts].dbo.YP_CRT_Data_8Hours
Truncate table [YB_Charts].dbo.YP_CRT_Data_1Day
Truncate table [YB_Charts].dbo.YP_CRT_Data_1Week
Truncate table [YB_Charts].dbo.YP_CRT_Data_1Month


---- select * from YP_CRT_Data_1Week where CRTD_PairSymbol = 'BACUSD'
---- select * from CRT_Data_1Week where CRTD_PairSymbol = 'BACUSD'

--------------------------------------------
---- Upload Source Data
--------------------------------------------

--YP_CRT_Data_1Minute
INSERT INTO [YB_Charts].dbo.[YP_CRT_Data_1Minute]
           ([CRTD_ID]
           ,[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])

 Select HD_Id AS  CRTD_ID    
		,Cast(convert(char(10),HD_Date,121) + ' ' + convert(Char(8),HD_Hour,108)  	as datetime)  AS CRTD_Period 
        ,Cast(convert(char(10),HD_Date,121) + ' ' + convert(Char(8),HD_Hour,108)  	as datetime)  AS CRTD_FirstQuote
        ,Cast(convert(char(10),HD_Date,121) + ' ' + convert(Char(6),HD_Hour,108) + '59.997' 	as datetime)  AS CRTD_LastQuote
        ,II.[InstrumentSymbol] AS CRTD_PairSymbol
        ,[HD_Open] AS CRTD_BidOpeningValue
        ,[HD_Close] AS CRTD_BidClosingValue
        ,[HD_Low] AS CRTD_BidLowValue
        ,[HD_High] AS CRTD_BidHighValue
        ,[HD_Open] AS CRTD_MidOpeningValue
        ,[HD_Close] AS CRTD_MidClosingValue
        ,[HD_Low] AS CRTD_MidLowValue
        ,[HD_High] AS CRTD_MidHighValue
        ,GetDate() AS CRTD_DateIn
  FROM YB_Hist.[dbo].[Hist_Data_1Minute] HD
  Inner Join YB_Main.dbo.Instruments II with (nolock)
  ON HD.[HD_PairSymbol] collate SQL_Latin1_General_CP1_CI_AS = II.InstrumentSymbol
 


--YP_CRT_Data_5Minutes
INSERT INTO [YB_Charts].dbo.[YP_CRT_Data_5Minutes]
           ([CRTD_ID]
           ,[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])

 Select HD_Id AS  CRTD_ID    
		,Cast(convert(char(10),HD_Date,121) + ' ' + convert(Char(8),HD_Hour,108)  	as datetime)  AS CRTD_Period 
        ,Cast(convert(char(10),HD_Date,121) + ' ' + convert(Char(8),HD_Hour,108)  	as datetime)  AS CRTD_FirstQuote
        ,Cast(convert(char(10),HD_Date,121) + ' ' + convert(Char(6),DateAdd(minute,4,HD_Hour),108) + '59.997' 	as datetime)  AS CRTD_LastQuote
        ,II.[InstrumentSymbol] AS CRTD_PairSymbol
        ,[HD_Open] AS CRTD_BidOpeningValue
        ,[HD_Close] AS CRTD_BidClosingValue
        ,[HD_Low] AS CRTD_BidLowValue
        ,[HD_High] AS CRTD_BidHighValue
        ,[HD_Open] AS CRTD_MidOpeningValue
        ,[HD_Close] AS CRTD_MidClosingValue
        ,[HD_Low] AS CRTD_MidLowValue
        ,[HD_High] AS CRTD_MidHighValue
        ,GetDate() AS CRTD_DateIn
  FROM YB_Hist.[dbo].[Hist_Data_5Minutes] HD
  Inner Join YB_Main.dbo.Instruments II with (nolock)
  ON HD.[HD_PairSymbol] collate SQL_Latin1_General_CP1_CI_AS = II.InstrumentSymbol


--YP_CRT_Data_15Minutes
INSERT INTO [YB_Charts].dbo.[YP_CRT_Data_15Minutes]
           ([CRTD_ID]
           ,[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])

 Select HD_Id AS  CRTD_ID    
		,Cast(convert(char(10),HD_Date,121) + ' ' + convert(Char(8),HD_Hour,108)  	as datetime)  AS CRTD_Period 
        ,Cast(convert(char(10),HD_Date,121) + ' ' + convert(Char(8),HD_Hour,108)  	as datetime)  AS CRTD_FirstQuote
        ,Cast(convert(char(10),HD_Date,121) + ' ' + convert(Char(6),DateAdd(minute,14,HD_Hour),108) + '59.997' 	as datetime)  AS CRTD_LastQuote
        ,II.[InstrumentSymbol] AS CRTD_PairSymbol
        ,[HD_Open] AS CRTD_BidOpeningValue
        ,[HD_Close] AS CRTD_BidClosingValue
        ,[HD_Low] AS CRTD_BidLowValue
        ,[HD_High] AS CRTD_BidHighValue
        ,[HD_Open] AS CRTD_MidOpeningValue
        ,[HD_Close] AS CRTD_MidClosingValue
        ,[HD_Low] AS CRTD_MidLowValue
        ,[HD_High] AS CRTD_MidHighValue
        ,GetDate() AS CRTD_DateIn
  FROM YB_Hist.[dbo].[Hist_Data_15Minutes] HD
  Inner Join YB_Main.dbo.Instruments II with (nolock)
  ON HD.[HD_PairSymbol] collate SQL_Latin1_General_CP1_CI_AS = II.InstrumentSymbol


--YP_CRT_Data_30Minutes
INSERT INTO [YB_Charts].dbo.[YP_CRT_Data_30Minutes]
           ([CRTD_ID]
           ,[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])

 Select HD_Id AS  CRTD_ID    
		,Cast(convert(char(10),HD_Date,121) + ' ' + convert(Char(8),HD_Hour,108)  	as datetime)  AS CRTD_Period 
        ,Cast(convert(char(10),HD_Date,121) + ' ' + convert(Char(8),HD_Hour,108)  	as datetime)  AS CRTD_FirstQuote
        ,Cast(convert(char(10),HD_Date,121) + ' ' + convert(Char(6),DateAdd(minute,29,HD_Hour),108) + '59.997' 	as datetime)  AS CRTD_LastQuote
        ,II.[InstrumentSymbol] AS CRTD_PairSymbol
        ,[HD_Open] AS CRTD_BidOpeningValue
        ,[HD_Close] AS CRTD_BidClosingValue
        ,[HD_Low] AS CRTD_BidLowValue
        ,[HD_High] AS CRTD_BidHighValue
        ,[HD_Open] AS CRTD_MidOpeningValue
        ,[HD_Close] AS CRTD_MidClosingValue
        ,[HD_Low] AS CRTD_MidLowValue
        ,[HD_High] AS CRTD_MidHighValue
        ,GetDate() AS CRTD_DateIn
  FROM YB_Hist.[dbo].[Hist_Data_30Minutes] HD
  Inner Join YB_Main.dbo.Instruments II with (nolock)
  ON HD.[HD_PairSymbol] collate SQL_Latin1_General_CP1_CI_AS = II.InstrumentSymbol
 

--YP_CRT_Data_1Hour
INSERT INTO [YB_Charts].dbo.[YP_CRT_Data_1Hour]
           ([CRTD_ID]
           ,[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])

 Select HD_Id AS  CRTD_ID    
		,Cast(convert(char(10),HD_Date,121) + ' ' + convert(Char(2),HD_Hour,108) + ':00:00'	as datetime)  AS CRTD_Period 
        ,Cast(convert(char(10),HD_Date,121) + ' ' + convert(Char(8),HD_Hour,108)  	as datetime)  AS CRTD_FirstQuote
         ,Cast(convert(char(10),HD_Date,121) + ' ' + convert(Char(6),DateAdd(minute,29,HD_Hour),108) + '59.997' 	as datetime)  AS CRTD_LastQuote
        ,II.[InstrumentSymbol] AS CRTD_PairSymbol
        ,[HD_Open] AS CRTD_BidOpeningValue
        ,[HD_Close] AS CRTD_BidClosingValue
        ,[HD_Low] AS CRTD_BidLowValue
        ,[HD_High] AS CRTD_BidHighValue
        ,[HD_Open] AS CRTD_MidOpeningValue
        ,[HD_Close] AS CRTD_MidClosingValue
        ,[HD_Low] AS CRTD_MidLowValue
        ,[HD_High] AS CRTD_MidHighValue
        ,GetDate() AS CRTD_DateIn
  FROM YB_Hist.[dbo].[Hist_Data_1Hour] HD
  Inner Join YB_Main.dbo.Instruments II with (nolock)
  ON HD.[HD_PairSymbol] collate SQL_Latin1_General_CP1_CI_AS = II.InstrumentSymbol
 

--YP_CRT_Data_4Hours
INSERT INTO [YB_Charts].dbo.[YP_CRT_Data_4Hours]
           ([CRTD_ID]
           ,[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])

 Select HD_Id AS  CRTD_ID    
		,CAST
			(
				CASE WHEN 	
				SUBSTRING(CONVERT(char(10), HD_Date, 112),7,2)<13 THEN 
					
					SUBSTRING(CONVERT(char(10), HD_Date, 112),1,4)+'-'+
					SUBSTRING(CONVERT(char(10), HD_Date, 112),7,2)+'-'+
					SUBSTRING(CONVERT(char(10), HD_Date, 112),5,2)
					
				ELSE CONVERT(char(10), HD_Date, 121)
				END 

				+ ' ' + CONVERT(CHAR(8),HD_Hour,108)  	AS DATETIME
			)  AS CRTD_Period
  		,CAST
			(
				CASE WHEN 	
				SUBSTRING(CONVERT(char(10), HD_Date, 112),7,2)<13 THEN 
					
					SUBSTRING(CONVERT(char(10), HD_Date, 112),1,4)+'-'+
					SUBSTRING(CONVERT(char(10), HD_Date, 112),7,2)+'-'+
					SUBSTRING(CONVERT(char(10), HD_Date, 112),5,2)
					
				ELSE CONVERT(char(10), HD_Date, 121)
				END 

				+ ' ' + CONVERT(CHAR(8),HD_Hour,108)  	AS DATETIME
			)  AS CRTD_FirstQuote
        ,Cast(convert(char(10),HD_Date,121) + ' ' + convert(Char(6),HD_Hour,108) + '59.997' 	as datetime)  AS CRTD_LastQuote
        ,II.[InstrumentSymbol] AS CRTD_PairSymbol
        ,[HD_Open] AS CRTD_BidOpeningValue
        ,[HD_Close] AS CRTD_BidClosingValue
        ,[HD_Low] AS CRTD_BidLowValue
        ,[HD_High] AS CRTD_BidHighValue
        ,[HD_Open] AS CRTD_MidOpeningValue
        ,[HD_Close] AS CRTD_MidClosingValue
        ,[HD_Low] AS CRTD_MidLowValue
        ,[HD_High] AS CRTD_MidHighValue
        ,GetDate() AS CRTD_DateIn
  FROM YB_Hist.[dbo].[Hist_Data_4Hours] HD
  Inner Join YB_Main.dbo.Instruments II with (nolock)
  ON HD.[HD_PairSymbol] collate SQL_Latin1_General_CP1_CI_AS = II.InstrumentSymbol
 


--YP_CRT_Data_1Day
INSERT INTO [YB_Charts].dbo.[YP_CRT_Data_1Day]
           ([CRTD_ID]
           ,[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])

 Select HD_Id AS  CRTD_ID    
		,CAST
			(
				CASE WHEN 	
				SUBSTRING(CONVERT(char(10), HD_Date, 112),7,2)<13 THEN 
					
					SUBSTRING(CONVERT(char(10), HD_Date, 112),1,4)+'-'+
					SUBSTRING(CONVERT(char(10), HD_Date, 112),7,2)+'-'+
					SUBSTRING(CONVERT(char(10), HD_Date, 112),5,2)
					
				ELSE CONVERT(char(10), HD_Date, 121)
				END 

				+ ' ' + CONVERT(CHAR(8),HD_Hour,108)  	AS DATETIME
			)  AS CRTD_Period
  		,CAST
			(
				CASE WHEN 	
				SUBSTRING(CONVERT(char(10), HD_Date, 112),7,2)<13 THEN 
					
					SUBSTRING(CONVERT(char(10), HD_Date, 112),1,4)+'-'+
					SUBSTRING(CONVERT(char(10), HD_Date, 112),7,2)+'-'+
					SUBSTRING(CONVERT(char(10), HD_Date, 112),5,2)
					
				ELSE CONVERT(char(10), HD_Date, 121)
				END 

				+ ' ' + CONVERT(CHAR(8),HD_Hour,108)  	AS DATETIME
			)  AS CRTD_FirstQuote
        ,Cast(convert(char(10),HD_Date,121) + ' 23:59:59.997' 	as datetime)  AS CRTD_LastQuote
        ,II.[InstrumentSymbol] AS CRTD_PairSymbol
        ,[HD_Open] AS CRTD_BidOpeningValue
        ,[HD_Close] AS CRTD_BidClosingValue
        ,[HD_Low] AS CRTD_BidLowValue
        ,[HD_High] AS CRTD_BidHighValue
        ,[HD_Open] AS CRTD_MidOpeningValue
        ,[HD_Close] AS CRTD_MidClosingValue
        ,[HD_Low] AS CRTD_MidLowValue
        ,[HD_High] AS CRTD_MidHighValue
        ,GetDate() AS CRTD_DateIn
  FROM YB_Hist.[dbo].[Hist_Data_1Day] HD
  Inner Join YB_Main.dbo.Instruments II with (nolock)
  ON HD.[HD_PairSymbol] collate SQL_Latin1_General_CP1_CI_AS = II.InstrumentSymbol
 

--YP_CRT_Data_1Week
INSERT INTO [YB_Charts].dbo.[YP_CRT_Data_1Week]
           ([CRTD_ID]
           ,[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])

 Select HD_Id AS  CRTD_ID    
		,CAST
			(
				CASE WHEN 	
				SUBSTRING(CONVERT(char(10), HD_Date, 112),7,2)<13 THEN 
					
					SUBSTRING(CONVERT(char(10), HD_Date, 112),1,4)+'-'+
					SUBSTRING(CONVERT(char(10), HD_Date, 112),7,2)+'-'+
					SUBSTRING(CONVERT(char(10), HD_Date, 112),5,2)
					
				ELSE CONVERT(char(10), HD_Date, 121)
				END 

				+ ' ' + CONVERT(CHAR(8),HD_Hour,108)  	AS DATETIME
			)  AS CRTD_Period
  		,CAST
			(
				CASE WHEN 	
				SUBSTRING(CONVERT(char(10), HD_Date, 112),7,2)<13 THEN 
					
					SUBSTRING(CONVERT(char(10), HD_Date, 112),1,4)+'-'+
					SUBSTRING(CONVERT(char(10), HD_Date, 112),7,2)+'-'+
					SUBSTRING(CONVERT(char(10), HD_Date, 112),5,2)
					
				ELSE CONVERT(char(10), HD_Date, 121)
				END 

				+ ' ' + CONVERT(CHAR(8),HD_Hour,108)  	AS DATETIME
			)  AS CRTD_FirstQuote
        ,Cast(convert(char(10),DateAdd(day,6,HD_Date),121) +  ' 23:59:59.997'  	as datetime)  AS CRTD_LastQuote
        ,II.[InstrumentSymbol] AS CRTD_PairSymbol
        ,[HD_Open] AS CRTD_BidOpeningValue
        ,[HD_Close] AS CRTD_BidClosingValue
        ,[HD_Low] AS CRTD_BidLowValue
        ,[HD_High] AS CRTD_BidHighValue
        ,[HD_Open] AS CRTD_MidOpeningValue
        ,[HD_Close] AS CRTD_MidClosingValue
        ,[HD_Low] AS CRTD_MidLowValue
        ,[HD_High] AS CRTD_MidHighValue
        ,GetDate() AS CRTD_DateIn
  FROM YB_Hist.[dbo].[Hist_Data_1Week] HD
  Inner Join YB_Main.dbo.Instruments II with (nolock)
  ON HD.[HD_PairSymbol] collate SQL_Latin1_General_CP1_CI_AS = II.InstrumentSymbol
 

--YP_CRT_Data_1Month
INSERT INTO [YB_Charts].dbo.[YP_CRT_Data_1Month]
           ([CRTD_ID]
           ,[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])

 Select HD_Id AS  CRTD_ID    
		,CAST
			(
				CASE WHEN 	
				SUBSTRING(CONVERT(char(10), HD_Date, 112),7,2)<13 THEN 
					
					SUBSTRING(CONVERT(char(10), HD_Date, 112),1,4)+'-'+
					SUBSTRING(CONVERT(char(10), HD_Date, 112),7,2)+'-'+
					SUBSTRING(CONVERT(char(10), HD_Date, 112),5,2)
					
				ELSE CONVERT(char(10), HD_Date, 121)
				END 

				+ ' ' + CONVERT(CHAR(8),HD_Hour,108)  	AS DATETIME
			)  AS CRTD_Period
  		,CAST
			(
				CASE WHEN 	
				SUBSTRING(CONVERT(char(10), HD_Date, 112),7,2)<13 THEN 
					
					SUBSTRING(CONVERT(char(10), HD_Date, 112),1,4)+'-'+
					SUBSTRING(CONVERT(char(10), HD_Date, 112),7,2)+'-'+
					SUBSTRING(CONVERT(char(10), HD_Date, 112),5,2)
					
				ELSE CONVERT(char(10), HD_Date, 121)
				END 

				+ ' ' + CONVERT(CHAR(8),HD_Hour,108)  	AS DATETIME
			)  AS CRTD_FirstQuote
        ,Cast(convert(char(10),EOMonth(HD_Date),121) +  ' 23:59:59.997'  	as datetime)  AS CRTD_LastQuote
        ,II.[InstrumentSymbol] AS CRTD_PairSymbol
        ,[HD_Open] AS CRTD_BidOpeningValue
        ,[HD_Close] AS CRTD_BidClosingValue
        ,[HD_Low] AS CRTD_BidLowValue
        ,[HD_High] AS CRTD_BidHighValue
        ,[HD_Open] AS CRTD_MidOpeningValue
        ,[HD_Close] AS CRTD_MidClosingValue
        ,[HD_Low] AS CRTD_MidLowValue
        ,[HD_High] AS CRTD_MidHighValue
        ,GetDate() AS CRTD_DateIn
  FROM YB_Hist.[dbo].[Hist_Data_1Month] HD
  Inner Join YB_Main.dbo.Instruments II with (nolock)
  ON HD.[HD_PairSymbol] collate SQL_Latin1_General_CP1_CI_AS = II.InstrumentSymbol
 

   ----------------------------------------------
  ------ Remove Data from target by Import Data
  ----------------------------------------------
  /*
  SELECT *	INTO [YB_Charts].[dbo].[CRT_Data_1Day_BAK_2016_12_21] FROM [YB_Charts].[dbo].[CRT_Data_1Day]


  SELECT *		  
 FROM [YB_Charts].[dbo].[CRT_Data_1Day] with (nolock)  
 WHERE  CRTD_ID <0 
 AND CRTD_PairSymbol IN
 (
 SELECT DISTINCT CRTD_PairSymbol FROM [YB_Charts].[dbo].[YP_CRT_Data_1Day] 
 )

  DELETE		  
 FROM [YB_Charts].[dbo].[CRT_Data_1Day]   
 WHERE  CRTD_ID <0 
 AND CRTD_PairSymbol IN
 (
 SELECT DISTINCT CRTD_PairSymbol FROM [YB_Charts].[dbo].[YP_CRT_Data_1Day] 
 )


  SELECT *	INTO [YB_Charts].[dbo].[CRT_Data_4Hours_BAK_2016_12_21] FROM [YB_Charts].[dbo].[CRT_Data_4Hours]

  SELECT *		  
 FROM [YB_Charts].[dbo].[CRT_Data_4Hours] with (nolock)  
 WHERE  CRTD_ID <0 
 AND CRTD_PairSymbol IN
 (
 SELECT DISTINCT CRTD_PairSymbol FROM [YB_Charts].[dbo].[YP_CRT_Data_4Hours] 
 )

 DELETE	  
 FROM [YB_Charts].[dbo].[CRT_Data_4Hours] 
  WHERE  CRTD_ID <0 
 AND CRTD_PairSymbol IN
 (
 SELECT DISTINCT CRTD_PairSymbol FROM [YB_Charts].[dbo].[YP_CRT_Data_4Hours] 
 )

 SELECT *	INTO [YB_Charts].[dbo].[CRT_Data_1Month_BAK_2016_12_21] FROM [YB_Charts].[dbo].[CRT_Data_1Month]

  SELECT *		  
 FROM [YB_Charts].[dbo].[CRT_Data_1Month] with (nolock)  
 WHERE  CRTD_ID <0 
 AND CRTD_PairSymbol IN
 (
 SELECT DISTINCT CRTD_PairSymbol FROM [YB_Charts].[dbo].[YP_CRT_Data_1Month] 
 )

 DELETE  
 FROM [YB_Charts].[dbo].[CRT_Data_1Month]  
 WHERE  CRTD_ID <0 
 AND CRTD_PairSymbol IN
 (
 SELECT DISTINCT CRTD_PairSymbol FROM [YB_Charts].[dbo].[YP_CRT_Data_1Month] 
 )
 
  SELECT *	INTO [YB_Charts].[dbo].[CRT_Data_1Week_BAK_2016_12_21] FROM [YB_Charts].[dbo].[CRT_Data_1Week]

  SELECT *		  
 FROM [YB_Charts].[dbo].[CRT_Data_1Week] with (nolock)  
 WHERE  CRTD_ID <0 
 AND CRTD_PairSymbol IN
 (
 SELECT DISTINCT CRTD_PairSymbol FROM [YB_Charts].[dbo].[YP_CRT_Data_1Week] 
 )

 DELETE	  
 FROM [YB_Charts].[dbo].[CRT_Data_1Week]  
 WHERE  CRTD_ID <0 
 AND CRTD_PairSymbol IN
 (
 SELECT DISTINCT CRTD_PairSymbol FROM [YB_Charts].[dbo].[YP_CRT_Data_1Week] 
 )

 */
  --select * from YB_Hist.[dbo].[Hist_Data_1Month] order by 2
  ----------------------------------------------
  ------ Insert Data to target Charts Tables
  ----------------------------------------------
  
  SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

       declare @MinId bigint
	   declare @Sql varchar(max)

/*
 select top 1 * from CRT_Data_5Minutes	 Order by 1 
 select top 1 * from CRT_Data_15Minutes	 Order by 1 
 select top 1 * from CRT_Data_30Minutes	 Order by 1 
 select top 1 * from CRT_Data_1Hour		 Order by 1 
 select top 1 * from CRT_Data_2Hours	 Order by 1 
 select top 1 * from CRT_Data_4Hours	 Order by 1 
 select top 1 * from CRT_Data_8Hours     Order by 1 
 select top 1 * from CRT_Data_1Day		 Order by 1 
 select top 1 * from CRT_Data_1Week		 Order by 1 
 select top 1 * from CRT_Data_1Month	 Order by 1 
*/

  IF EXISTS (select 1 from [YB_Charts].dbo.[YP_CRT_Data_1Minute]) 
  BEGIN

		
      RAISERROR ('Processing Data 1Minute', 0, 1) WITH NOWAIT
	  ----------------------------
	  ---- YP_CRT_Data_1Minute
	  ----------------------------
	  IF Object_ID('YB_Charts.dbo.TMP_Data_1Minute')  IS NOT NULL
		Drop Table YB_Charts.dbo.TMP_Data_1Minute

	   --DECLARE @MinId bigint
	   --DECLARE @Sql varchar(max)
       select top 1 @MinId= [CRTD_ID] -1 from CRT_Data_1Minute ORDER BY 1 
       If @MinId >=0 SET @MinId = -1


		select @Sql = 'CREATE TABLE [YB_Charts].dbo.[TMP_Data_1Minute](
			[CRTD_ID] [int] IDENTITY(' + cast(@MinId as varchar(10))+ ',-1) NOT NULL,
			[CRTD_Period] [datetime] NOT NULL,
			[CRTD_FirstQuote] [datetime] NOT NULL,
			[CRTD_LastQuote] [datetime] NOT NULL,
			[CRTD_PairSymbol] [varchar](50) NOT NULL,
			[CRTD_BidOpeningValue] [float] NOT NULL,
			[CRTD_BidClosingValue] [float] NOT NULL,
			[CRTD_BidLowValue] [float] NOT NULL,
			[CRTD_BidHighValue] [float] NOT NULL,
			[CRTD_MidOpeningValue] [float] NOT NULL,
			[CRTD_MidClosingValue] [float] NOT NULL,
			[CRTD_MidLowValue] [float] NOT NULL,
			[CRTD_MidHighValue] [float] NOT NULL,
			[CRTD_DateIn] [datetime] NOT NULL )'

		exec (@Sql) 


		  ;With MinPeriodsPerSymbol AS
		(
			SELECT [CRTD_PairSymbol], Min([CRTD_Period]) MinOfPeriod 
			FROM [YB_Charts].dbo.[CRT_Data_1Minute] with (nolock)
			Group By [CRTD_PairSymbol]
		)

		INSERT INTO [YB_Charts].dbo.[TMP_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])
		  SELECT 
			   CC.[CRTD_Period]
			  ,CC.[CRTD_FirstQuote]
			  ,CC.[CRTD_LastQuote]
			  ,CC.[CRTD_PairSymbol]
			  ,CC.[CRTD_BidOpeningValue]
			  ,CC.[CRTD_BidClosingValue]
			  ,CC.[CRTD_BidLowValue]
			  ,CC.[CRTD_BidHighValue]
			  ,CC.[CRTD_MidOpeningValue]
			  ,CC.[CRTD_MidClosingValue]
			  ,CC.[CRTD_MidLowValue]
			  ,CC.[CRTD_MidHighValue]
			  ,CC.[CRTD_DateIn]	
	
	  FROM [YB_Charts].dbo.[YP_CRT_Data_1Minute] CC
	  LEFT JOIN [YB_Charts].dbo.[CRT_Data_1Minute] XX with (nolock)
	  ON CC.[CRTD_Period] = XX.[CRTD_Period] 
		 AND CC.CRTD_PairSymbol = XX.CRTD_PairSymbol
	  LEFT JOIN MinPeriodsPerSymbol PS
	  ON CC.[CRTD_PairSymbol] = PS.[CRTD_PairSymbol]
  
	  where XX.[CRTD_ID] IS NULL
	  AND CC.[CRTD_Period] < IsNull(PS.MinOfPeriod,GetDate())
	  Order by [CRTD_PairSymbol],[CRTD_Period] DESC


	   -- select * from #CRTD_1Minute  Order by CRTD_PairSymbol,CRTD_Period desc
	   -- select * from CRT_Data_1Minute where  CRTD_PairSymbol = 'AAPLUSD' Order by CRTD_PairSymbol,CRTD_Period desc

	    SET IDENTITY_INSERT [YB_Charts].dbo.[CRT_Data_1Minute] ON
		INSERT INTO [YB_Charts].dbo.[CRT_Data_1Minute]
				   ([CRTD_ID]
				   ,[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]
				   )
		SELECT		
					[CRTD_ID]
				   ,[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]
		FROM	[YB_Charts].dbo.TMP_Data_1Minute
		ORDER BY CRTD_PairSymbol,CRTD_Period DESC
		SET IDENTITY_INSERT [YB_Charts].dbo.[CRT_Data_1Minute] OFF


  End

  IF EXISTS (select 1 from [YB_Charts].dbo.[YP_CRT_Data_5Minutes]) 
  BEGIN
	
	  RAISERROR ('Processing Data 5Minutes', 0, 1) WITH NOWAIT
	  ----------------------------
	  ---- YP_CRT_Data_5Minutes
	  ----------------------------
	  IF Object_ID('YB_Charts..TMP_Data_5Minutes')  IS NOT NULL
		Drop Table YB_Charts.dbo.TMP_Data_5Minutes

	   --declare @MinId bigint
	   --declare @Sql varchar(max)
       select top 1 @MinId= [CRTD_ID] -1 from CRT_Data_5Minutes ORDER BY 1 
       If @MinId >=0 SET @MinId = -1


		select @Sql = 'CREATE TABLE [YB_Charts].dbo.[TMP_Data_5Minutes](
			[CRTD_ID] [int] IDENTITY(' + cast(@MinId as varchar(10))+ ',-1) NOT NULL,
			[CRTD_Period] [datetime] NOT NULL,
			[CRTD_FirstQuote] [datetime] NOT NULL,
			[CRTD_LastQuote] [datetime] NOT NULL,
			[CRTD_PairSymbol] [varchar](50) NOT NULL,
			[CRTD_BidOpeningValue] [float] NOT NULL,
			[CRTD_BidClosingValue] [float] NOT NULL,
			[CRTD_BidLowValue] [float] NOT NULL,
			[CRTD_BidHighValue] [float] NOT NULL,
			[CRTD_MidOpeningValue] [float] NOT NULL,
			[CRTD_MidClosingValue] [float] NOT NULL,
			[CRTD_MidLowValue] [float] NOT NULL,
			[CRTD_MidHighValue] [float] NOT NULL,
			[CRTD_DateIn] [datetime] NOT NULL )'

		exec (@Sql) 




		;With MinPeriodsPerSymbol AS
		(
			SELECT [CRTD_PairSymbol], Min([CRTD_Period]) MinOfPeriod 
			FROM [YB_Charts].dbo.[CRT_Data_5Minutes] with (nolock)
			Group By [CRTD_PairSymbol]
		)


		INSERT INTO [YB_Charts].dbo.[TMP_Data_5Minutes]
				   ([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])
		  SELECT 
			   CC.[CRTD_Period]
			  ,CC.[CRTD_FirstQuote]
			  ,CC.[CRTD_LastQuote]
			  ,CC.[CRTD_PairSymbol]
			  ,CC.[CRTD_BidOpeningValue]
			  ,CC.[CRTD_BidClosingValue]
			  ,CC.[CRTD_BidLowValue]
			  ,CC.[CRTD_BidHighValue]
			  ,CC.[CRTD_MidOpeningValue]
			  ,CC.[CRTD_MidClosingValue]
			  ,CC.[CRTD_MidLowValue]
			  ,CC.[CRTD_MidHighValue]
			  ,CC.[CRTD_DateIn]	

	  FROM [YB_Charts].dbo.[YP_CRT_Data_5Minutes] CC
	  LEFT JOIN [dbo].[CRT_Data_5Minutes] XX with (nolock)
	  ON CC.[CRTD_Period] = XX.[CRTD_Period] 
		 AND CC.CRTD_PairSymbol = XX.CRTD_PairSymbol
	  LEFT JOIN MinPeriodsPerSymbol PS
	  ON CC.[CRTD_PairSymbol] = PS.[CRTD_PairSymbol]
  
	  where XX.[CRTD_ID] IS NULL
	  AND CC.[CRTD_Period] < IsNull(PS.MinOfPeriod,GetDate())
	  Order by [CRTD_PairSymbol],[CRTD_Period] DESC

	  --  select * from #CRTD_5Minutes  Order by CRTD_PairSymbol,CRTD_Period desc
	  -- select * from CRT_Data_5Minutes where  CRTD_PairSymbol = 'AAPLUSD' Order by CRTD_PairSymbol,CRTD_Period desc

	    SET IDENTITY_INSERT [YB_Charts].dbo.[CRT_Data_5Minutes] ON
		INSERT INTO [YB_Charts].dbo.[CRT_Data_5Minutes]
				   ([CRTD_ID]
				   ,[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]
				   )
		SELECT		
					[CRTD_ID]
				   ,[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]
		FROM	[YB_Charts].dbo.[TMP_Data_5Minutes]
		ORDER BY CRTD_PairSymbol,CRTD_Period DESC
		SET IDENTITY_INSERT [YB_Charts].dbo.[CRT_Data_5Minutes] OFF


  End

  IF EXISTS (select 1 from [YB_Charts].dbo.[YP_CRT_Data_15Minutes]) 
  BEGIN

	  RAISERROR ('Processing Data 15Minutes', 0, 1) WITH NOWAIT
  
	  ----------------------------
	  ---- YP_CRT_Data_15Minutes
	  ----------------------------
	  IF Object_ID('YB_Charts.dbo.TMP_Data_15Minutes')  IS NOT NULL
		Drop Table YB_Charts.dbo.TMP_Data_15Minutes

	   --declare @MinId bigint
	   --declare @Sql varchar(max)
       select top 1 @MinId= [CRTD_ID] -1 from [YB_Charts].dbo.CRT_Data_15Minutes ORDER BY 1 
       If @MinId >=0 SET @MinId = -1

	   SELECT @Sql = 'CREATE TABLE [YB_Charts].dbo.[TMP_Data_15Minutes](
			[CRTD_ID] [int] IDENTITY(' + cast(@MinId as varchar(10))+ ',-1) NOT NULL,
			[CRTD_Period] [datetime] NOT NULL,
			[CRTD_FirstQuote] [datetime] NOT NULL,
			[CRTD_LastQuote] [datetime] NOT NULL,
			[CRTD_PairSymbol] [varchar](50) NOT NULL,
			[CRTD_BidOpeningValue] [float] NOT NULL,
			[CRTD_BidClosingValue] [float] NOT NULL,
			[CRTD_BidLowValue] [float] NOT NULL,
			[CRTD_BidHighValue] [float] NOT NULL,
			[CRTD_MidOpeningValue] [float] NOT NULL,
			[CRTD_MidClosingValue] [float] NOT NULL,
			[CRTD_MidLowValue] [float] NOT NULL,
			[CRTD_MidHighValue] [float] NOT NULL,
			[CRTD_DateIn] [datetime] NOT NULL )'

		exec (@Sql) 



		;With MinPeriodsPerSymbol AS
		(
			SELECT [CRTD_PairSymbol], Min([CRTD_Period]) MinOfPeriod 
			FROM [YB_Charts].dbo.[CRT_Data_15Minutes] with (nolock)
			Group By [CRTD_PairSymbol]
		)

		INSERT INTO [YB_Charts].dbo.[TMP_Data_15Minutes]
				   ([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])
		  SELECT 
			   CC.[CRTD_Period]
			  ,CC.[CRTD_FirstQuote]
			  ,CC.[CRTD_LastQuote]
			  ,CC.[CRTD_PairSymbol]
			  ,CC.[CRTD_BidOpeningValue]
			  ,CC.[CRTD_BidClosingValue]
			  ,CC.[CRTD_BidLowValue]
			  ,CC.[CRTD_BidHighValue]
			  ,CC.[CRTD_MidOpeningValue]
			  ,CC.[CRTD_MidClosingValue]
			  ,CC.[CRTD_MidLowValue]
			  ,CC.[CRTD_MidHighValue]
			  ,CC.[CRTD_DateIn]	
	  FROM [YB_Charts].dbo.[YP_CRT_Data_15Minutes] CC
	  LEFT JOIN [YB_Charts].dbo.[CRT_Data_15Minutes] XX with (nolock)
	  ON CC.[CRTD_Period] = XX.[CRTD_Period] 
		 AND CC.CRTD_PairSymbol = XX.CRTD_PairSymbol
	  LEFT JOIN MinPeriodsPerSymbol PS
	  ON CC.[CRTD_PairSymbol] = PS.[CRTD_PairSymbol]
  
	  where XX.[CRTD_ID] IS NULL
	  AND CC.[CRTD_Period] < IsNull(PS.MinOfPeriod,GetDate())
	  Order by [CRTD_PairSymbol],[CRTD_Period] DESC

	  --  select * from #CRTD_15Minutes  Order by CRTD_PairSymbol,CRTD_Period desc
	  -- select * from CRT_Data_15Minutes where  CRTD_PairSymbol = 'AAPLUSD' Order by CRTD_PairSymbol,CRTD_Period desc

	    SET IDENTITY_INSERT [YB_Charts].dbo.[CRT_Data_15Minutes] ON
		INSERT INTO [YB_Charts].dbo.[CRT_Data_15Minutes]
				   ([CRTD_ID]
				   ,[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]
				   )
		SELECT		
					[CRTD_ID]
				   ,[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]
		FROM	[YB_Charts].dbo.[TMP_Data_15Minutes]
		ORDER BY CRTD_PairSymbol,CRTD_Period DESC
		SET IDENTITY_INSERT [CRT_Data_15Minutes] OFF


  END	

  IF EXISTS (select 1 from [YP_CRT_Data_30Minutes]) 
  BEGIN

	  RAISERROR ('Processing Data 30Minutes', 0, 1) WITH NOWAIT

	  ----------------------------
	  ---- YP_CRT_Data_30Minutes
	  ----------------------------
	  IF Object_ID('YB_Charts.dbo.TMP_Data_30Minutes')  IS NOT NULL
		Drop Table YB_Charts.dbo.TMP_Data_30Minutes

	   --declare @MinId bigint
	   --declare @Sql varchar(max)
       select top 1 @MinId= [CRTD_ID] -1 from [YB_Charts].dbo.CRT_Data_30Minutes     Order by 1 
       If @MinId >=0 SET @MinId = -1

	   SELECT @Sql = 'CREATE TABLE [YB_Charts].dbo.[TMP_Data_30Minutes](
			[CRTD_ID] [int] IDENTITY(' + cast(@MinId as varchar(10))+ ',-1) NOT NULL,
			[CRTD_Period] [datetime] NOT NULL,
			[CRTD_FirstQuote] [datetime] NOT NULL,
			[CRTD_LastQuote] [datetime] NOT NULL,
			[CRTD_PairSymbol] [varchar](50) NOT NULL,
			[CRTD_BidOpeningValue] [float] NOT NULL,
			[CRTD_BidClosingValue] [float] NOT NULL,
			[CRTD_BidLowValue] [float] NOT NULL,
			[CRTD_BidHighValue] [float] NOT NULL,
			[CRTD_MidOpeningValue] [float] NOT NULL,
			[CRTD_MidClosingValue] [float] NOT NULL,
			[CRTD_MidLowValue] [float] NOT NULL,
			[CRTD_MidHighValue] [float] NOT NULL,
			[CRTD_DateIn] [datetime] NOT NULL )'

		exec (@Sql) 


		;With MinPeriodsPerSymbol AS
		(
			SELECT [CRTD_PairSymbol], Min([CRTD_Period]) MinOfPeriod 
			FROM [YB_Charts].dbo.[CRT_Data_30Minutes] with (nolock)
			Group By [CRTD_PairSymbol]
		)

		INSERT INTO [YB_Charts].dbo.[TMP_Data_30Minutes]
				   ([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])
		  SELECT 
			   CC.[CRTD_Period]
			  ,CC.[CRTD_FirstQuote]
			  ,CC.[CRTD_LastQuote]
			  ,CC.[CRTD_PairSymbol]
			  ,CC.[CRTD_BidOpeningValue]
			  ,CC.[CRTD_BidClosingValue]
			  ,CC.[CRTD_BidLowValue]
			  ,CC.[CRTD_BidHighValue]
			  ,CC.[CRTD_MidOpeningValue]
			  ,CC.[CRTD_MidClosingValue]
			  ,CC.[CRTD_MidLowValue]
			  ,CC.[CRTD_MidHighValue]
			  ,CC.[CRTD_DateIn]	
	  FROM [YB_Charts].dbo.[YP_CRT_Data_30Minutes] CC
	  LEFT JOIN [YB_Charts].dbo.[CRT_Data_30Minutes] XX with (nolock)
	  ON CC.[CRTD_Period] = XX.[CRTD_Period] 
		 AND CC.CRTD_PairSymbol = XX.CRTD_PairSymbol
	  LEFT JOIN MinPeriodsPerSymbol PS
	  ON CC.[CRTD_PairSymbol] = PS.[CRTD_PairSymbol]
  
	  where XX.[CRTD_ID] IS NULL
	  AND CC.[CRTD_Period] < IsNull(PS.MinOfPeriod,GetDate())
	  Order by [CRTD_PairSymbol],[CRTD_Period] DESC

	  --  select * from #CRTD_30Minutes  Order by CRTD_PairSymbol,CRTD_Period desc
	  -- select * from CRT_Data_30Minutes where  CRTD_PairSymbol = 'AAPLUSD' Order by CRTD_PairSymbol,CRTD_Period desc

	    SET IDENTITY_INSERT [YB_Charts].dbo.[CRT_Data_30Minutes] ON
		INSERT INTO [YB_Charts].dbo.[CRT_Data_30Minutes]
				   ([CRTD_ID]
				   ,[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]
				   )
		SELECT		
					[CRTD_ID]
				   ,[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]
		FROM	[YB_Charts].dbo.[TMP_Data_30Minutes]
		ORDER BY CRTD_PairSymbol,CRTD_Period DESC
		SET IDENTITY_INSERT [YB_Charts].dbo.[CRT_Data_30Minutes] OFF


  End

  
  IF EXISTS (select 1 from [YB_Charts].dbo.[YP_CRT_Data_1Hour]) 
  BEGIN

     RAISERROR ('Processing Data 1Hour', 0, 1) WITH NOWAIT
   
	  ----------------------------
	  ---- YP_CRT_Data_1Hour
	  ----------------------------
	  IF Object_ID('YB_Charts.dbo.TMP_Data_1Hour')  IS NOT NULL
		Drop Table YB_Charts.dbo.[TMP_Data_1Hour]

       -- declare @MinId bigint
	   -- declare @Sql varchar(max)
       select top 1 @MinId= [CRTD_ID] -1 from [YB_Charts].dbo.CRT_Data_1Hour     Order by 1 
       If @MinId >=0 SET @MinId = -1

	   SELECT @Sql = 'CREATE TABLE [YB_Charts].dbo.[dbo].[TMP_Data_1Hour](
			[CRTD_ID] [int] IDENTITY(' + cast(@MinId as varchar(10))+ ',-1) NOT NULL,
			[CRTD_Period] [datetime] NOT NULL,
			[CRTD_FirstQuote] [datetime] NOT NULL,
			[CRTD_LastQuote] [datetime] NOT NULL,
			[CRTD_PairSymbol] [varchar](50) NOT NULL,
			[CRTD_BidOpeningValue] [float] NOT NULL,
			[CRTD_BidClosingValue] [float] NOT NULL,
			[CRTD_BidLowValue] [float] NOT NULL,
			[CRTD_BidHighValue] [float] NOT NULL,
			[CRTD_MidOpeningValue] [float] NOT NULL,
			[CRTD_MidClosingValue] [float] NOT NULL,
			[CRTD_MidLowValue] [float] NOT NULL,
			[CRTD_MidHighValue] [float] NOT NULL,
			[CRTD_DateIn] [datetime] NOT NULL )'

		exec (@Sql) 


		;With MinPeriodsPerSymbol AS
		(
			SELECT [CRTD_PairSymbol], Min([CRTD_Period]) MinOfPeriod 
			FROM [YB_Charts].dbo.[CRT_Data_1Hour] with (nolock)
			Group By [CRTD_PairSymbol]
		)


		INSERT INTO [YB_Charts].dbo.[TMP_Data_1Hour]
				   ([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])
		  SELECT 
			   CC.[CRTD_Period]
			  ,CC.[CRTD_FirstQuote]
			  ,CC.[CRTD_LastQuote]
			  ,CC.[CRTD_PairSymbol]
			  ,CC.[CRTD_BidOpeningValue]
			  ,CC.[CRTD_BidClosingValue]
			  ,CC.[CRTD_BidLowValue]
			  ,CC.[CRTD_BidHighValue]
			  ,CC.[CRTD_MidOpeningValue]
			  ,CC.[CRTD_MidClosingValue]
			  ,CC.[CRTD_MidLowValue]
			  ,CC.[CRTD_MidHighValue]
			  ,CC.[CRTD_DateIn]	
		  FROM [YB_Charts].dbo.[YP_CRT_Data_1Hour] CC
		  LEFT JOIN [YB_Charts].dbo.[CRT_Data_1Hour] XX with (nolock)
		  ON CC.[CRTD_Period] = XX.[CRTD_Period] 
			 AND CC.CRTD_PairSymbol = XX.CRTD_PairSymbol
		  LEFT JOIN MinPeriodsPerSymbol PS
		  ON CC.[CRTD_PairSymbol] = PS.[CRTD_PairSymbol]
  
		  where XX.[CRTD_ID] IS NULL
		  AND CC.[CRTD_Period] < IsNull(PS.MinOfPeriod,GetDate())
		  Order by [CRTD_PairSymbol],[CRTD_Period] DESC

		  --  select * from #CRTD_1Hour  Order by CRTD_PairSymbol,CRTD_Period desc
		  -- select * from CRT_Data_1Hour where  CRTD_PairSymbol = 'AAPLUSD' Order by CRTD_PairSymbol,CRTD_Period desc

	    SET IDENTITY_INSERT [YB_Charts].dbo.[CRT_Data_1Hour] ON
		INSERT INTO [YB_Charts].dbo.[CRT_Data_1Hour]
				   ([CRTD_ID]
				   ,[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]
				   )
		SELECT		
					[CRTD_ID]
				   ,[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]
		FROM	[YB_Charts].dbo.[TMP_Data_1Hour]
		ORDER BY CRTD_PairSymbol,CRTD_Period DESC
		SET IDENTITY_INSERT [YB_Charts].dbo.[CRT_Data_1Hour] OFF


  End

  IF EXISTS (select 1 from [YB_Charts].dbo.[YP_CRT_Data_2Hours]) 
  BEGIN

     RAISERROR ('Processing Data 2Hours', 0, 1) WITH NOWAIT
  
	  ----------------------------
	  ---- YP_CRT_Data_2Hours
	  ----------------------------
	  IF Object_ID('YB_Charts..TMP_Data_2Hours')  IS NOT NULL
		Drop Table YB_Charts..TMP_Data_2Hours


       select top 1 @MinId= [CRTD_ID] -1 from [YB_Charts].dbo.CRT_Data_2Hours     Order by 1 
       If @MinId >=0 SET @MinId = -1

	   SELECT @Sql = 'CREATE TABLE [YB_Charts].dbo.[dbo].[TMP_Data_2Hours](
			[CRTD_ID] [int] IDENTITY(' + cast(@MinId as varchar(10))+ ',-1) NOT NULL,
			[CRTD_Period] [datetime] NOT NULL,
			[CRTD_FirstQuote] [datetime] NOT NULL,
			[CRTD_LastQuote] [datetime] NOT NULL,
			[CRTD_PairSymbol] [varchar](50) NOT NULL,
			[CRTD_BidOpeningValue] [float] NOT NULL,
			[CRTD_BidClosingValue] [float] NOT NULL,
			[CRTD_BidLowValue] [float] NOT NULL,
			[CRTD_BidHighValue] [float] NOT NULL,
			[CRTD_MidOpeningValue] [float] NOT NULL,
			[CRTD_MidClosingValue] [float] NOT NULL,
			[CRTD_MidLowValue] [float] NOT NULL,
			[CRTD_MidHighValue] [float] NOT NULL,
			[CRTD_DateIn] [datetime] NOT NULL )'

		exec (@Sql) 



		;With MinPeriodsPerSymbol AS
		(
			SELECT [CRTD_PairSymbol], Min([CRTD_Period]) MinOfPeriod 
			FROM [YB_Charts].dbo.[CRT_Data_2Hours] with (nolock)
			Group By [CRTD_PairSymbol]
		)


		INSERT INTO [YB_Charts].dbo.[TMP_Data_2Hours]
				   ([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])
		  SELECT 
			   CC.[CRTD_Period]
			  ,CC.[CRTD_FirstQuote]
			  ,CC.[CRTD_LastQuote]
			  ,CC.[CRTD_PairSymbol]
			  ,CC.[CRTD_BidOpeningValue]
			  ,CC.[CRTD_BidClosingValue]
			  ,CC.[CRTD_BidLowValue]
			  ,CC.[CRTD_BidHighValue]
			  ,CC.[CRTD_MidOpeningValue]
			  ,CC.[CRTD_MidClosingValue]
			  ,CC.[CRTD_MidLowValue]
			  ,CC.[CRTD_MidHighValue]
			  ,CC.[CRTD_DateIn]	

	  FROM [YB_Charts].dbo.[YP_CRT_Data_2Hours] CC
	  LEFT JOIN [dbo].[CRT_Data_2Hours] XX with (nolock)
	  ON CC.[CRTD_Period] = XX.[CRTD_Period] 
		 AND CC.CRTD_PairSymbol = XX.CRTD_PairSymbol
	  LEFT JOIN MinPeriodsPerSymbol PS
	  ON CC.[CRTD_PairSymbol] = PS.[CRTD_PairSymbol]
  
	  where XX.[CRTD_ID] IS NULL
	  AND CC.[CRTD_Period] < IsNull(PS.MinOfPeriod,GetDate())
	  Order by [CRTD_PairSymbol],[CRTD_Period] DESC


	 --  select * from #CRTD_2Hours  Order by CRTD_PairSymbol,CRTD_Period desc
	 -- select * from CRT_Data_2Hours where  CRTD_PairSymbol = 'AAPLUSD' Order by CRTD_PairSymbol,CRTD_Period desc

	    SET IDENTITY_INSERT [YB_Charts].dbo.[CRT_Data_2Hours] ON
		INSERT INTO [YB_Charts].dbo.[CRT_Data_2Hours]
				   ([CRTD_ID]
				   ,[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]
				   )
		SELECT		
					[CRTD_ID]
				   ,[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]
		FROM	TMP_Data_2Hours
		ORDER BY CRTD_PairSymbol,CRTD_Period DESC
		SET IDENTITY_INSERT [YB_Charts].dbo.[CRT_Data_2Hours] OFF


  End


  IF EXISTS (select 1 from [YP_CRT_Data_4Hours]) 
  BEGIN
  
      RAISERROR ('Processing Data 4Hours', 0, 1) WITH NOWAIT
	  ----------------------------
	  ---- YP_CRT_Data_4Hours
	  ----------------------------
	  IF Object_ID('YB_Charts.dbo.TMP_Data_4Hours')  IS NOT NULL
		Drop Table YB_Charts.dbo.TMP_Data_4Hours


	   --declare @MinId bigint
	   --declare @Sql varchar(max)
       select top 1 @MinId= [CRTD_ID] -1 from CRT_Data_4Hours     Order by 1 
       If @MinId >=0 SET @MinId = -1

	   SELECT @Sql = 'CREATE TABLE [dbo].[TMP_Data_4Hours](
			[CRTD_ID] [int] IDENTITY(' + cast(@MinId as varchar(10))+ ',-1) NOT NULL,
			[CRTD_Period] [datetime] NOT NULL,
			[CRTD_FirstQuote] [datetime] NOT NULL,
			[CRTD_LastQuote] [datetime] NOT NULL,
			[CRTD_PairSymbol] [varchar](50) NOT NULL,
			[CRTD_BidOpeningValue] [float] NOT NULL,
			[CRTD_BidClosingValue] [float] NOT NULL,
			[CRTD_BidLowValue] [float] NOT NULL,
			[CRTD_BidHighValue] [float] NOT NULL,
			[CRTD_MidOpeningValue] [float] NOT NULL,
			[CRTD_MidClosingValue] [float] NOT NULL,
			[CRTD_MidLowValue] [float] NOT NULL,
			[CRTD_MidHighValue] [float] NOT NULL,
			[CRTD_DateIn] [datetime] NOT NULL )'

		exec (@Sql) 

		;With MinPeriodsPerSymbol AS
		(
			SELECT [CRTD_PairSymbol], Min([CRTD_Period]) MinOfPeriod 
			FROM [dbo].[CRT_Data_4Hours] with (nolock)
			Group By [CRTD_PairSymbol]
		)


		INSERT INTO [dbo].[TMP_Data_4Hours]
				   ([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])
		  SELECT 
			   CC.[CRTD_Period]
			  ,CC.[CRTD_FirstQuote]
			  ,CC.[CRTD_LastQuote]
			  ,CC.[CRTD_PairSymbol]
			  ,CC.[CRTD_BidOpeningValue]
			  ,CC.[CRTD_BidClosingValue]
			  ,CC.[CRTD_BidLowValue]
			  ,CC.[CRTD_BidHighValue]
			  ,CC.[CRTD_MidOpeningValue]
			  ,CC.[CRTD_MidClosingValue]
			  ,CC.[CRTD_MidLowValue]
			  ,CC.[CRTD_MidHighValue]
			  ,CC.[CRTD_DateIn]	
	
	  FROM [dbo].[YP_CRT_Data_4Hours] CC
	  LEFT JOIN [dbo].[CRT_Data_4Hours] XX with (nolock)
	  ON CC.[CRTD_Period] = XX.[CRTD_Period] 
		 AND CC.CRTD_PairSymbol = XX.CRTD_PairSymbol
	  LEFT JOIN MinPeriodsPerSymbol PS
	  ON CC.[CRTD_PairSymbol] = PS.[CRTD_PairSymbol]
  
	  where XX.[CRTD_ID] IS NULL
	  AND CC.[CRTD_Period] < IsNull(PS.MinOfPeriod,GetDate())
	  Order by [CRTD_PairSymbol],[CRTD_Period] DESC

	 --  select * from #CRTD_4Hours  Order by CRTD_PairSymbol,CRTD_Period desc
	 -- select * from CRT_Data_4Hours where  CRTD_PairSymbol = 'AAPLUSD' Order by CRTD_PairSymbol,CRTD_Period desc

	    SET IDENTITY_INSERT [CRT_Data_4Hours] ON
		INSERT INTO [dbo].[CRT_Data_4Hours]
				   ([CRTD_ID]
				   ,[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]
				   )
		SELECT		
					[CRTD_ID]
				   ,[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]
		FROM	TMP_Data_4Hours 
		ORDER BY CRTD_PairSymbol,CRTD_Period DESC
		SET IDENTITY_INSERT [CRT_Data_4Hours] OFF


  End


  IF EXISTS (select 1 from [YP_CRT_Data_8Hours]) 
  BEGIN

     RAISERROR ('Processing Data 8Hours', 0, 1) WITH NOWAIT

	  ----------------------------
	  ---- YP_CRT_Data_8Hours
	  ----------------------------
	  IF Object_ID('YB_Charts..TMP_Data_8Hours')  IS NOT NULL
		Drop Table YB_Charts..TMP_Data_8Hours


	   --declare @MinId bigint
	   --declare @Sql varchar(max)
       select top 1 @MinId= [CRTD_ID] -1 from CRT_Data_8Hours     Order by 1 
       If @MinId >=0 SET @MinId = -1

	   SELECT @Sql = 'CREATE TABLE [dbo].[TMP_Data_8Hours](
			[CRTD_ID] [int] IDENTITY(' + cast(@MinId as varchar(10))+ ',-1) NOT NULL,
			[CRTD_Period] [datetime] NOT NULL,
			[CRTD_FirstQuote] [datetime] NOT NULL,
			[CRTD_LastQuote] [datetime] NOT NULL,
			[CRTD_PairSymbol] [varchar](50) NOT NULL,
			[CRTD_BidOpeningValue] [float] NOT NULL,
			[CRTD_BidClosingValue] [float] NOT NULL,
			[CRTD_BidLowValue] [float] NOT NULL,
			[CRTD_BidHighValue] [float] NOT NULL,
			[CRTD_MidOpeningValue] [float] NOT NULL,
			[CRTD_MidClosingValue] [float] NOT NULL,
			[CRTD_MidLowValue] [float] NOT NULL,
			[CRTD_MidHighValue] [float] NOT NULL,
			[CRTD_DateIn] [datetime] NOT NULL )'

		exec (@Sql) 




		;With MinPeriodsPerSymbol AS
		(
			SELECT [CRTD_PairSymbol], Min([CRTD_Period]) MinOfPeriod 
			FROM [dbo].[CRT_Data_8Hours] with (nolock)
			Group By [CRTD_PairSymbol]
		)


		INSERT INTO [dbo].[TMP_Data_8Hours]
				   ([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])
		  SELECT 
			   CC.[CRTD_Period]
			  ,CC.[CRTD_FirstQuote]
			  ,CC.[CRTD_LastQuote]
			  ,CC.[CRTD_PairSymbol]
			  ,CC.[CRTD_BidOpeningValue]
			  ,CC.[CRTD_BidClosingValue]
			  ,CC.[CRTD_BidLowValue]
			  ,CC.[CRTD_BidHighValue]
			  ,CC.[CRTD_MidOpeningValue]
			  ,CC.[CRTD_MidClosingValue]
			  ,CC.[CRTD_MidLowValue]
			  ,CC.[CRTD_MidHighValue]
			  ,CC.[CRTD_DateIn]	
	  FROM [dbo].[YP_CRT_Data_8Hours] CC
	  LEFT JOIN [dbo].[CRT_Data_8Hours] XX with (nolock)
	  ON CC.[CRTD_Period] = XX.[CRTD_Period] 
		 AND CC.CRTD_PairSymbol = XX.CRTD_PairSymbol
	  LEFT JOIN MinPeriodsPerSymbol PS
	  ON CC.[CRTD_PairSymbol] = PS.[CRTD_PairSymbol]
  
	  where XX.[CRTD_ID] IS NULL
	  AND CC.[CRTD_Period] < IsNull(PS.MinOfPeriod,GetDate())
	  Order by [CRTD_PairSymbol],[CRTD_Period] DESC

	 --  select * from #CRTD_8Hours  Order by CRTD_PairSymbol,CRTD_Period desc
	 -- select * from CRT_Data_8Hours where  CRTD_PairSymbol = 'AAPLUSD' Order by CRTD_PairSymbol,CRTD_Period desc

	    SET IDENTITY_INSERT [CRT_Data_8Hours] ON
		INSERT INTO [dbo].[CRT_Data_8Hours]
				   ([CRTD_ID]
				   ,[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]
				   )
		SELECT		
					[CRTD_ID]
				   ,[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]
		FROM	#CRTD_8Hours 
		ORDER BY CRTD_PairSymbol,CRTD_Period DESC
		SET IDENTITY_INSERT [CRT_Data_8Hours] OFF

	 

  End

  IF EXISTS (select 1 from [YP_CRT_Data_1Day]) 
  BEGIN

      RAISERROR ('Processing Data 1Day', 0, 1) WITH NOWAIT

	  ----------------------------
	  ---- YP_CRT_Data_1Day
	  ----------------------------
	  IF Object_ID('YB_Charts..TMP_Data_1Day')  IS NOT NULL
		Drop Table YB_Charts..TMP_Data_1Day


	   --declare @MinId bigint
	   --declare @Sql varchar(max)
       select top 1 @MinId= [CRTD_ID] -1 from CRT_Data_1Day     Order by 1 
       If @MinId >=0 SET @MinId = -1

	   SELECT @Sql = 'CREATE TABLE [dbo].[TMP_Data_1Day](
			[CRTD_ID] [int] IDENTITY(' + cast(@MinId as varchar(10))+ ',-1) NOT NULL,
			[CRTD_Period] [datetime] NOT NULL,
			[CRTD_FirstQuote] [datetime] NOT NULL,
			[CRTD_LastQuote] [datetime] NOT NULL,
			[CRTD_PairSymbol] [varchar](50) NOT NULL,
			[CRTD_BidOpeningValue] [float] NOT NULL,
			[CRTD_BidClosingValue] [float] NOT NULL,
			[CRTD_BidLowValue] [float] NOT NULL,
			[CRTD_BidHighValue] [float] NOT NULL,
			[CRTD_MidOpeningValue] [float] NOT NULL,
			[CRTD_MidClosingValue] [float] NOT NULL,
			[CRTD_MidLowValue] [float] NOT NULL,
			[CRTD_MidHighValue] [float] NOT NULL,
			[CRTD_DateIn] [datetime] NOT NULL )'

		exec (@Sql) 



		;With MinPeriodsPerSymbol AS
		(
			SELECT [CRTD_PairSymbol], Min([CRTD_Period]) MinOfPeriod 
			FROM [dbo].[CRT_Data_1Day] with (nolock)
			Group By [CRTD_PairSymbol]
		)


		INSERT INTO [dbo].[TMP_Data_1Day]
				   ([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])
		  SELECT 
			   CC.[CRTD_Period]
			  ,CC.[CRTD_FirstQuote]
			  ,CC.[CRTD_LastQuote]
			  ,CC.[CRTD_PairSymbol]
			  ,CC.[CRTD_BidOpeningValue]
			  ,CC.[CRTD_BidClosingValue]
			  ,CC.[CRTD_BidLowValue]
			  ,CC.[CRTD_BidHighValue]
			  ,CC.[CRTD_MidOpeningValue]
			  ,CC.[CRTD_MidClosingValue]
			  ,CC.[CRTD_MidLowValue]
			  ,CC.[CRTD_MidHighValue]
			  ,CC.[CRTD_DateIn]	
	  FROM [dbo].[YP_CRT_Data_1Day] CC
	  LEFT JOIN [dbo].[CRT_Data_1Day] XX with (nolock)
	  ON CC.[CRTD_Period] = XX.[CRTD_Period] 
		 AND CC.CRTD_PairSymbol = XX.CRTD_PairSymbol
	  LEFT JOIN MinPeriodsPerSymbol PS
	  ON CC.[CRTD_PairSymbol] = PS.[CRTD_PairSymbol]
  
	  where XX.[CRTD_ID] IS NULL
	  AND CC.[CRTD_Period] < IsNull(PS.MinOfPeriod,GetDate())
	  Order by [CRTD_PairSymbol],[CRTD_Period] DESC

	 --  select * from #CRTD_1Day  Order by CRTD_PairSymbol,CRTD_Period desc
	 -- select * from CRT_Data_1Day where  CRTD_PairSymbol = 'AAPLUSD' Order by CRTD_PairSymbol,CRTD_Period desc

	    SET IDENTITY_INSERT [CRT_Data_1Day] ON
		INSERT INTO [dbo].[CRT_Data_1Day]
				   ([CRTD_ID]
				   ,[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]
				   )
		SELECT		
					[CRTD_ID]
				   ,[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]
		FROM	[TMP_Data_1Day] 
		ORDER BY CRTD_PairSymbol,CRTD_Period DESC
		SET IDENTITY_INSERT [CRT_Data_1Day] OFF

  End

  
  IF EXISTS (select 1 from [YP_CRT_Data_1Week]) 
  BEGIN

      RAISERROR ('Processing Data 1Week', 0, 1) WITH NOWAIT

	  ----------------------------
	  ---- YP_CRT_Data_1Week
	  ----------------------------
	  IF Object_ID('YB_Charts..TMP_Data_1Week')  IS NOT NULL
		Drop Table YB_Charts..TMP_Data_1Week


       --declare @MinId bigint
	   --declare @Sql varchar(max)
       select top 1 @MinId= [CRTD_ID] -1 from [CRT_Data_1Week]     Order by 1 
       If @MinId >=0 SET @MinId = -1

	   SELECT @Sql = 'CREATE TABLE [dbo].[TMP_Data_1Week](
			[CRTD_ID] [int] IDENTITY(' + cast(@MinId as varchar(10))+ ',-1) NOT NULL,
			[CRTD_Period] [datetime] NOT NULL,
			[CRTD_FirstQuote] [datetime] NOT NULL,
			[CRTD_LastQuote] [datetime] NOT NULL,
			[CRTD_PairSymbol] [varchar](50) NOT NULL,
			[CRTD_BidOpeningValue] [float] NOT NULL,
			[CRTD_BidClosingValue] [float] NOT NULL,
			[CRTD_BidLowValue] [float] NOT NULL,
			[CRTD_BidHighValue] [float] NOT NULL,
			[CRTD_MidOpeningValue] [float] NOT NULL,
			[CRTD_MidClosingValue] [float] NOT NULL,
			[CRTD_MidLowValue] [float] NOT NULL,
			[CRTD_MidHighValue] [float] NOT NULL,
			[CRTD_DateIn] [datetime] NOT NULL )'

		exec (@Sql) 



		;With MinPeriodsPerSymbol AS
		(
			SELECT [CRTD_PairSymbol], Min([CRTD_Period]) MinOfPeriod 
			FROM [dbo].[CRT_Data_1Week] with (nolock)
			Group By [CRTD_PairSymbol]
		)


		INSERT INTO [dbo].[TMP_Data_1Week]
				   ([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])
		  SELECT 
			   CC.[CRTD_Period]
			  ,CC.[CRTD_FirstQuote]
			  ,CC.[CRTD_LastQuote]
			  ,CC.[CRTD_PairSymbol]
			  ,CC.[CRTD_BidOpeningValue]
			  ,CC.[CRTD_BidClosingValue]
			  ,CC.[CRTD_BidLowValue]
			  ,CC.[CRTD_BidHighValue]
			  ,CC.[CRTD_MidOpeningValue]
			  ,CC.[CRTD_MidClosingValue]
			  ,CC.[CRTD_MidLowValue]
			  ,CC.[CRTD_MidHighValue]
			  ,CC.[CRTD_DateIn]
		  FROM [dbo].[YP_CRT_Data_1Week] CC
		  LEFT JOIN [dbo].[CRT_Data_1Week] XX with (nolock)
		  ON CC.[CRTD_Period] = XX.[CRTD_Period] 
			 AND CC.CRTD_PairSymbol = XX.CRTD_PairSymbol
		  LEFT JOIN MinPeriodsPerSymbol PS
		  ON CC.[CRTD_PairSymbol] = PS.[CRTD_PairSymbol]
  
		  where XX.[CRTD_ID] IS NULL
		  AND CC.[CRTD_Period] < IsNull(PS.MinOfPeriod,GetDate())
		  Order by [CRTD_PairSymbol],[CRTD_Period] DESC


	 --  select * from #CRTD_1Week  Order by CRTD_PairSymbol,CRTD_Period desc
	 -- select * from CRT_Data_1Week where  CRTD_PairSymbol = 'AAPLUSD' Order by CRTD_PairSymbol,CRTD_Period desc

	    SET IDENTITY_INSERT [CRT_Data_1Week] ON
		INSERT INTO [dbo].[CRT_Data_1Week]
				   ([CRTD_ID]
				   ,[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]
				   )
		SELECT		
					[CRTD_ID]
				   ,[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]
		FROM	[TMP_Data_1Week]
		ORDER BY CRTD_PairSymbol,CRTD_Period DESC
		SET IDENTITY_INSERT [CRT_Data_1Week] OFF




  End

  IF EXISTS (select 1 from [YP_CRT_Data_1Month]) 
  BEGIN

      RAISERROR ('Processing Data 1Month', 0, 1) WITH NOWAIT
	  ----------------------------
	  --- YP_CRT_Data_1Month
	  ----------------------------
	  IF Object_ID('YB_Charts..TMP_Data_1Month')  IS NOT NULL
		Drop Table YB_Charts..TMP_Data_1Month

	   --declare @MinId bigint
	   --declare @Sql varchar(max)

       select top 1 @MinId= [CRTD_ID] -1 from CRT_Data_1Month     Order by 1 
       If @MinId >=0 SET @MinId = -1

	   SELECT @Sql = 'CREATE TABLE [dbo].[TMP_Data_1Month](
			[CRTD_ID] [int] IDENTITY(' + cast(@MinId as varchar(10))+ ',-1) NOT NULL,
			[CRTD_Period] [datetime] NOT NULL,
			[CRTD_FirstQuote] [datetime] NOT NULL,
			[CRTD_LastQuote] [datetime] NOT NULL,
			[CRTD_PairSymbol] [varchar](50) NOT NULL,
			[CRTD_BidOpeningValue] [float] NOT NULL,
			[CRTD_BidClosingValue] [float] NOT NULL,
			[CRTD_BidLowValue] [float] NOT NULL,
			[CRTD_BidHighValue] [float] NOT NULL,
			[CRTD_MidOpeningValue] [float] NOT NULL,
			[CRTD_MidClosingValue] [float] NOT NULL,
			[CRTD_MidLowValue] [float] NOT NULL,
			[CRTD_MidHighValue] [float] NOT NULL,
			[CRTD_DateIn] [datetime] NOT NULL )'

		exec (@Sql) 
	


	  DECLARE @CurrMonth date

	  SELECT @CurrMonth = cast(DateAdd(day , -datePart(day,getdate())+1, getdate()) as date)

	   ;With MinPeriodsPerSymbol AS
		(
			SELECT [CRTD_PairSymbol], Min([CRTD_Period]) MinOfPeriod 
			FROM [dbo].[CRT_Data_1Month] with (nolock)
			Group By [CRTD_PairSymbol]
		)	


	INSERT INTO [dbo].[TMP_Data_1Month]
			   ([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])
	  SELECT 
		   CC.[CRTD_Period]
		  ,CC.[CRTD_FirstQuote]
		  ,CC.[CRTD_LastQuote]
		  ,CC.[CRTD_PairSymbol]
		  ,CC.[CRTD_BidOpeningValue]
		  ,CC.[CRTD_BidClosingValue]
		  ,CC.[CRTD_BidLowValue]
		  ,CC.[CRTD_BidHighValue]
		  ,CC.[CRTD_MidOpeningValue]
		  ,CC.[CRTD_MidClosingValue]
		  ,CC.[CRTD_MidLowValue]
		  ,CC.[CRTD_MidHighValue]
		  ,CC.[CRTD_DateIn]
	
	  FROM [dbo].[YP_CRT_Data_1Month] CC
	  LEFT JOIN [dbo].[CRT_Data_1Month] XX
	  ON CC.[CRTD_Period] = XX.[CRTD_Period] 
	  AND CC.CRTD_PairSymbol = XX.CRTD_PairSymbol
	  LEFT JOIN MinPeriodsPerSymbol PS
	  ON CC.[CRTD_PairSymbol] = PS.[CRTD_PairSymbol]
  
	  where XX.[CRTD_ID] IS NULL
	  AND cast(dateadd(day,-datepart(day,CC.[CRTD_Period])+1, CC.[CRTD_Period]) as date) < @CurrMonth
	  AND CC.[CRTD_Period] < IsNull(PS.MinOfPeriod,GetDate())
	  Order by [CRTD_PairSymbol],[CRTD_Period] DESC

	-- select * from #CRTD_1Month  Order by CRTD_PairSymbol,CRTD_Period desc
	-- select * from CRT_Data_1Month where  CRTD_PairSymbol = 'AAPLUSD' Order by CRTD_PairSymbol,CRTD_Period desc


    SET IDENTITY_INSERT [CRT_Data_1Month] ON
	INSERT INTO [dbo].[CRT_Data_1Month]
				   ([CRTD_ID]
				   ,[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]
				   )
     SELECT		
					[CRTD_ID]
				   ,[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]
		FROM	[TMP_Data_1Month]  
		ORDER BY CRTD_PairSymbol,CRTD_Period DESC
		SET IDENTITY_INSERT [CRT_Data_1Month] OFF



	  


  End


  /*

    select top 5000 * from CRT_Data_1Minute where CRTD_PairSymbol = 'AAPLUSD'
  and cast([CRTD_Period] as date) = '2016-06-07'
  order by [CRTD_Period]

  select * from #CRTD_1Minute  where CRTD_PairSymbol = 'AAPLUSD' order by CRTD_PairSymbol,CRTD_Period desc
  */



GO
/****** Object:  StoredProcedure [dbo].[CRT_Agg_All_Except1Minute]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[CRT_Agg_All_Except1Minute]
	@i_CRTT_ID int = null
AS
/*=============================================
 Author: Ariel Meran
 Create date: 7/12/2016
 Description: Agg the records from CRT_Data_1Minute to the other CRT tables
 Debug:
 select * from CRT_LastQuote where Next_End_period<lastQuote
 and tablename='CRT_Data_5Minutes'
 and CRTD_PairSymbol='BACUSD' 
SELECT * from  CRT_Data_1Minute A (nolock)
where CRTD_PairSymbol='EURCZK'
and A.CRTD_Period>='2016-12-13 10:05:00.000'
 =============================================*/
SET NOCOUNT ON
declare @SQL Nvarchar(max),@TableName sysname,@Source_TableName sysname,@UnitDefinition varchar(15),@rowcount int,
		@TimeUnit varchar(10),@TimeInterval varchar(10)

create table #temp (CRTD_Period datetime,
					CRTD_FirstQuote datetime,
					CRTD_LastQuote  datetime,
					CRTD_PairSymbol varchar(15),
					CRTD_BidOpeningValue float ,
					CRTD_BidClosingValue float ,
					CRTD_BidLowValue float ,
					CRTD_BidHighValue float ,
					CRTD_MidOpeningValue float ,
					CRTD_MidClosingValue float ,
					CRTD_MidLowValue float ,
					CRTD_MidHighValue float,
					StartIntervalDate datetime,
					EndIntervalDate datetime)

create index ix_StartIntervalDate on #temp(StartIntervalDate) 

create table #temp1 (StartPeriod datetime,
					EndPeriod datetime,
					First_Quote datetime,
					Last_Quote datetime,
					CRTD_PairSymbol varchar(15),
					BidMin_Value float,
					BidMax_Value float,
					MidMin_Value float,
					MidMax_Value float,
					BidOpen_Value float,
					BidClose_Value float,
					MidOpen_Value float,
					MidClose_Value float)	

create table #ChangedQuote
	(CRTD_PairSymbol varchar(50),
	 NEXT_CRTD_Period dateTime,
	 LastQuote dateTime)

create table #LastQuote
(CRTD_PairSymbol varchar(20),
max_LastQuote datetime)

insert into #LastQuote
select B.CRTD_PairSymbol,max([CRTD_LastQuote]) as max_LastQuote
from CRT_Data_1Minute B (nolock)							
where B.CRTD_Period>getdate()-7
group by B.CRTD_PairSymbol

update A
set LastQuote=B.max_LastQuote
from CRT_LastQuote A
	inner join #LastQuote B on A.CRTD_PairSymbol=B.CRTD_PairSymbol

--Insert new symbols to CRT_LastQuote
insert into CRT_LastQuote(TableName,CRTD_PairSymbol,LAST_CRTD_Period,LastQuote)
SELECT distinct TableName,B.CRTD_PairSymbol ,'2015-01-01',max_LastQuote
from  CRT_LastQuote A
	cross JOIN #LastQuote B 
where not exists(select 1 from CRT_LastQuote C where C.TableName=A.TableName and B.CRTD_PairSymbol=C.CRTD_PairSymbol)

declare cTasks cursor local static for
	select CRTT_TableName, CRTT_Source_TableName, CRTT_UnitDefinition
	from CRT_tasks with (nolock)
	where CRTT_Name <> '1Minute'
	and CRTT_IsActive = 1 and CRTT_Source_TableName <> '' and (CRTT_ID = @i_CRTT_ID or @i_CRTT_ID is null)
	order by CRTT_ID
open cTasks
fetch next from cTasks into @TableName, @Source_TableName, @UnitDefinition
while @@fetch_status = 0
	begin/*1*/	
		set @TimeUnit=substring(@UnitDefinition,1,1)
		set @TimeInterval=substring(@UnitDefinition,2,4)
		SELECT @TimeUnit=CASE @TimeUnit when 'N' then 'minute'
										when 'H' then 'hour'
										when 'D' then 'day'
										when 'W' then 'Week'
										when 'M' then 'Month'		
							end															

		Set @SQL =
		'update CRT_LastQuote
		 set NEXT_CRTD_Period=dateadd('+@TimeUnit+','+@TimeInterval+', (dateadd('+@TimeUnit+', datediff('+@TimeUnit+',0,LAST_CRTD_Period) / '+@TimeInterval+' * '+@TimeInterval+', 0)))
		 where TableName='''+@TableName+''''
		 exec(@SQL)

		Set @SQL =
		'update CRT_LastQuote
		 set Next_End_period=dateadd('+@TimeUnit+','+@TimeInterval+', (dateadd('+@TimeUnit+', datediff('+@TimeUnit+',0,NEXT_CRTD_Period) / '+@TimeInterval+' * '+@TimeInterval+', 0)))
		 where TableName='''+@TableName+''''
		 exec(@SQL)

        truncate table #ChangedQuote
        insert into #ChangedQuote(CRTD_PairSymbol,NEXT_CRTD_Period,LastQuote)
		select CRTD_PairSymbol,NEXT_CRTD_Period,LastQuote
		from CRT_LastQuote
		where TableName=@TableName
		and Next_End_period<LastQuote

		if @@rowcount>0-- there is no need to do anything if there is no quotes after the next time interval at the destination table
		  begin/*2*/
			truncate table #temp
			truncate table #temp1
			
			set @SQL = 
			'insert into #temp(CRTD_Period,CRTD_FirstQuote,CRTD_LastQuote,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_BidClosingValue,CRTD_BidLowValue,CRTD_BidHighValue,CRTD_MidOpeningValue,
							   CRTD_MidClosingValue,CRTD_MidLowValue,CRTD_MidHighValue,StartIntervalDate,EndIntervalDate)
			SELECT CRTD_Period ,CRTD_FirstQuote ,CRTD_LastQuote ,A.CRTD_PairSymbol ,CRTD_BidOpeningValue ,CRTD_BidClosingValue  
				  ,CRTD_BidLowValue ,CRTD_BidHighValue ,CRTD_MidOpeningValue ,CRTD_MidClosingValue ,CRTD_MidLowValue ,CRTD_MidHighValue,
				  dateadd('+@TimeUnit+', datediff('+@TimeUnit+',0,CRTD_Period) /'+ @TimeInterval+' * '+@TimeInterval+', 0) as StartIntervalDate,
				  dateadd('+@TimeUnit+','+@TimeInterval+', (dateadd('+@TimeUnit+', datediff('+@TimeUnit+',0,CRTD_Period) / '+@TimeInterval+' * '+@TimeInterval+', 0))) as EndIntervalDate
			from  ' + quotename(@Source_TableName) + ' A with (nolock,forceseek)
				inner join #ChangedQuote B on A.CRTD_PairSymbol=B.CRTD_PairSymbol 
			where A.CRTD_Period>=B.NEXT_CRTD_Period'
				
			if @TimeUnit='Week'--reduce 1 day so the week will be from sunday to saturday
				begin
					set @SQL=replace(@SQL,'as StartIntervalDate','-1 as StartIntervalDate')
					set @SQL=replace(@SQL,'as EndIntervalDate','-1 as EndIntervalDate')
				end

			exec sp_executesql @SQL
			
			--delete records which already exists
			set @SQL = 'delete from A 
						from #temp A 
							inner join '+ quotename(@TableName) + 'B on A.StartIntervalDate=B.CRTD_Period and A.CRTD_PairSymbol=B.CRTD_PairSymbol'
			exec(@sql)
									
			insert into #temp1
					(StartPeriod, EndPeriod, First_Quote, Last_Quote, CRTD_PairSymbol, BidMin_Value, BidMax_Value, MidMin_Value, MidMax_Value)			
			select  StartIntervalDate,
					EndIntervalDate,
					min(CRTD_FirstQuote) First_Quote, max(CRTD_LastQuote) Last_Quote, 
					CRTD_PairSymbol,
					min(CRTD_BidLowValue) BidMin_Value, max(CRTD_BidHighValue) BidMax_Value, 
					min(CRTD_MidLowValue) MidMin_Value, max(CRTD_MidHighValue) MidMax_Value			 
			from #temp
			group by StartIntervalDate,EndIntervalDate,CRTD_PairSymbol
				
			update A
			set BidOpen_Value = B.CRTD_BidOpeningValue,
				MidOpen_Value = B.CRTD_MidOpeningValue
			FROM #temp1 A
				INNER JOIN (select StartIntervalDate,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_MidOpeningValue,ROW_NUMBER() over (partition by CRTD_PairSymbol,StartIntervalDate order by crtd_period) as rownum
							from #temp) B ON A.CRTD_PairSymbol = B.CRTD_PairSymbol and A.StartPeriod=B.StartIntervalDate
			where B.rownum=1

			update A
			set BidClose_Value = B.CRTD_BidClosingValue,
				MidClose_Value = B.CRTD_MidClosingValue
			FROM #temp1 A
				INNER JOIN (select StartIntervalDate,CRTD_PairSymbol,CRTD_BidClosingValue,CRTD_MidClosingValue,ROW_NUMBER() over (partition by CRTD_PairSymbol,StartIntervalDate order by crtd_period desc) as rownum
							from #temp) B ON A.CRTD_PairSymbol = B.CRTD_PairSymbol and A.StartPeriod=B.StartIntervalDate
			where B.rownum=1
--delete records where there are no quotes until the top interval range. For example: if a time interval is between 10:00 to 10:15, it should verify there are quotes after 10:15		
			delete from A
			from #temp1 A
				inner join #ChangedQuote B on A.CRTD_PairSymbol=B.CRTD_PairSymbol 
			where A.EndPeriod>B.LastQuote

			begin try
				begin tran		
				Set @SQL =
				'update A
				 set LAST_CRTD_Period=B.StartPeriod,
					 NEXT_CRTD_Period=B.EndPeriod
				 from CRT_LastQuote A
					inner join (select CRTD_PairSymbol, max(StartPeriod) as StartPeriod, max(EndPeriod) as EndPeriod 
							    from #temp1 
								group by CRTD_PairSymbol) as B on A.CRTD_PairSymbol=B.CRTD_PairSymbol 
				 where TableName='''+@TableName+''''
				 exec(@SQL)

				Set @SQL =
				'update CRT_LastQuote
				 set Next_End_period=dateadd('+@TimeUnit+','+@TimeInterval+', (dateadd('+@TimeUnit+', datediff('+@TimeUnit+',0,NEXT_CRTD_Period) / '+@TimeInterval+' * '+@TimeInterval+', 0)))
				 where TableName='''+@TableName+''''
				 exec(@SQL)

				set @SQL = 
				'insert into ' + quotename(@TableName) + 
				'(CRTD_Period, CRTD_FirstQuote, CRTD_LastQuote, CRTD_PairSymbol,
					CRTD_BidOpeningValue, CRTD_BidClosingValue, CRTD_BidLowValue,CRTD_BidHighValue,
					CRTD_MidOpeningValue, CRTD_MidClosingValue, CRTD_MidLowValue,CRTD_MidHighValue)
				select StartPeriod, First_Quote, Last_Quote, A.CRTD_PairSymbol, BidOpen_Value, BidClose_Value, BidMin_Value, BidMax_Value,
						MidOpen_Value, MidClose_Value, MidMin_Value, MidMax_Value
				from #temp1 A'					
				exec(@SQL)			

				commit tran
			end try
			begin catch
				rollback;
				THROW;
			end catch
			--exec CRT_UpdateTasks_LastRun @CRTT_ID			
		end/*2*/
	Else print 'no new data for '+@TableName
	fetch next from cTasks into  @TableName, @Source_TableName, @UnitDefinition
end/*1*/
close cTasks
deallocate cTasks

drop table #temp
drop table #temp1
drop table #ChangedQuote



GO
/****** Object:  StoredProcedure [dbo].[CRT_BreakDownUnitDefinition]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[CRT_BreakDownUnitDefinition]
		@UnitDefinition varchar(15),
		@Year int output,
		@Month int output,
		@Week int output,
		@Day int output,
		@Hour int output,
		@Minute int output
as

set @Year = null
set @Month = null
set @Week = null
set @Day = null
set @Hour = null
set @Minute = null

declare @i_UnitDefinition varchar(16),
		@i int,
		@CurrentChar varchar(1),
		@CurrentValue varchar(2),
		@CurrentUnit char(1)

set @i_UnitDefinition = @UnitDefinition + 'E'

set @i = 1

while @i <= len(@i_UnitDefinition)
begin
	set @CurrentChar = substring(@i_UnitDefinition, @i, 1)

	if isnumeric(@CurrentChar) = 1
		set @CurrentValue = @CurrentValue + @CurrentChar
	else
	begin
		if @CurrentValue <> ''
		begin
			if @CurrentUnit = 'N'
				set @Minute = cast(@CurrentValue as int)
			else if @CurrentUnit = 'H'
				set @Hour = cast(@CurrentValue as int)
			else if @CurrentUnit = 'D'
				set @Day = cast(@CurrentValue as int)
			else if @CurrentUnit = 'W'
				set @Week = cast(@CurrentValue as int)
			else if @CurrentUnit = 'M'
				set @Month = cast(@CurrentValue as int)
			else if @CurrentUnit = 'Y'
				set @Year = cast(@CurrentValue as int)
		end
		set @CurrentUnit = @CurrentChar
		set @CurrentValue = ''
	end
	set @i = @i + 1
end


GO
/****** Object:  StoredProcedure [dbo].[CRT_UpdateTasks_LastRun]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[CRT_UpdateTasks_LastRun]

	
 @i_CRTT_ID int = null

AS

--- exec CRT_UpdateTasks_LastRun 2

set nocount ON



declare @i_Year			int,
		@i_Month		int,
		@i_Week			int,
		@i_Day			int,
		@i_Hour			int,
		@i_Minute		int,

		@CRTT_ID			int,
		@TableName			sysname,
		@Source_TableName	sysname,
		@UnitDefinition		varchar(15),
		@LastRun			datetime,
		@EndOfLastRun		datetime,
		@AffectedRows		int,
		@sql				varchar(max)


declare cTasks cursor local static for
	select CRTT_ID, CRTT_TableName, CRTT_Source_TableName, CRTT_UnitDefinition, CRTT_LastRun
	from CRT_tasks with (nolock)
	where 1=1 
	and CRTT_Name <> '1Minute'
	and CRTT_IsActive = 1 and CRTT_Source_TableName <> '' and (CRTT_ID = @i_CRTT_ID or @i_CRTT_ID is null)
	order by 1

open cTasks

fetch next from cTasks into @CRTT_ID, @TableName, @Source_TableName, @UnitDefinition, @LastRun

while @@fetch_status = 0
begin
	--raiserror('Update Tasks from table %s...', 0, 1, @TableName) WITH NOWAIT

	--SELECT @TableName TableName, @LastRun LastRun, @1Min_MinDate [1Min_MinDate], @1Min_MaxDate [1Min_MaxDate], @1Min_Period [1Min_Period]


		set @SQL = 'Update [dbo].[CRT_Tasks] set [CRTT_LastModifiedDate] = GetDate(), [CRTT_LastRun] = (select Max(CRTD_Period) from ' 
		+ quotename(@TableName) + ' with (nolock)) where [CRTT_ID] = ' + cast(@CRTT_ID as varchar(10)) 
		

		--select @SQL
		exec (@SQL)


	fetch next from cTasks into @CRTT_ID, @TableName, @Source_TableName, @UnitDefinition, @LastRun
end
close cTasks
deallocate cTasks
GO
/****** Object:  StoredProcedure [dbo].[GetData]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[GetData]
	@pair  varchar(50),
	@start DATETIME,
	@end DATETIME, 
	@resolution varchar(10)
AS

SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

/*
---- Example :
Exec [GetData] 'EURUSD','2015-06-01', '2015-06-05','1'
*/


IF @resolution = '5' 
		SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_5Minutes]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]
    

ELSE IF @resolution = '15' 
		SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_15Minutes]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]

ELSE IF @resolution = '30' 
		SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_30Minutes]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]

ELSE IF @resolution = '60' 
		SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_1Hour]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]

ELSE IF @resolution = '120' 
		SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_2Hours]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]

ELSE IF @resolution = '240' 
		SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_4Hours]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]

ELSE IF @resolution = '480' 
		SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_8Hours]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]

ELSE IF @resolution = 'D' 
		SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_1Day]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]

ELSE IF @resolution = 'W' 
		SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_1Week]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]

ELSE IF @resolution = 'M' 
		SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_1Month]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]

ELSE
		SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_1Minute]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
   ORDER BY [CRTD_Period]
RETURN 0

GO
/****** Object:  StoredProcedure [dbo].[USP_ChartsTemplate_AddOrUpdate]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[USP_ChartsTemplate_AddOrUpdate]
	@client VARCHAR(100),
	@user VARCHAR(300),
	@chartName VARCHAR(300), 
	@symbol VARCHAR(50),
	@resolution VARCHAR(10),
	@lastModified DATETIME,
	@content TEXT, 
	@chartId BIGINT = NULL
AS
	MERGE [ChartsTemplate] as ct
	USING (VALUES(@chartId, @client,@user, @chartName,@symbol,@resolution,@lastModified,@content)) as s ([ChartId], [Client], [User], [ChartName], [Symbol], [Resolution], [LastModified], [Content])
	ON ct.[Id] = s.[ChartId] AND ct.[User] = s.[User] AND ct.[Client]=s.[Client] 
	WHEN MATCHED
		THEN UPDATE 
			SET [ChartName] = s.[ChartName],
				[Symbol] = s.[Symbol],
				[Resolution] = s.[Resolution],
				[LastModified] = s.[LastModified], --NEED REVIEW: possiblyu better fill from db like GETUTCDATE()
				[Content] = s.[Content]
				
	WHEN NOT MATCHED THEN 
		INSERT ([Client], [User], [ChartName], [Symbol], [Resolution], [LastModified], [Content])
		VALUES (@client,  @user,  @chartName,  @symbol,  @resolution,  @lastModified,  @content)
	;

	SELECT SCOPE_IDENTITY()
RETURN 0

GO
/****** Object:  StoredProcedure [dbo].[USP_ChartsTemplate_Delete]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[USP_ChartsTemplate_Delete]
	@client VARCHAR(100),
	@user VARCHAR(300),
	@chartId BIGINT
AS
	DELETE FROM [ChartsTemplate]
	WHERE [Id] = @chartId AND [User] = @user AND [Client]=@client 
RETURN 0

GO
/****** Object:  StoredProcedure [dbo].[USP_ChartsTemplate_GetChart]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[USP_ChartsTemplate_GetChart]
	@client VARCHAR(100),
	@user VARCHAR(300),
	@chartId BIGINT
AS
	SELECT [Id], [ChartName], [LastModified], [Content]
	FROM [ChartsTemplate]
	WHERE [Id]=@chartId AND [Client]=@client AND [User]=@user 

RETURN 0

GO
/****** Object:  StoredProcedure [dbo].[USP_ChartsTemplate_GetChartList]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[USP_ChartsTemplate_GetChartList]
	@client VARCHAR(100),
	@user VARCHAR(300)
AS
	SELECT [Id], [ChartName], [LastModified], [Symbol], [Resolution]
	FROM [ChartsTemplate]
	WHERE [Client]=@client AND [User]=@user
RETURN 0

GO
/****** Object:  StoredProcedure [dbo].[USP_CRT_Agg_1Minute]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[USP_CRT_Agg_1Minute]

	@StartDate datetime = NULL,
	@1MinFromStartDate Bit = 0
	
AS
SET NOCOUNT ON

declare @EndDate datetime,
		@RowsAffected int,
		@RowsToProcess int

SET	@RowsAffected = 0

SET @EndDate = dateadd(millisecond, -datepart(millisecond, getdate()) -datepart(second, getdate())*1000 - 3, getdate())
IF @StartDate is NULL
	Begin
		select @StartDate = Max([CRTD_Period]) from [dbo].[CRT_Data_1Minute]
		select @StartDate = isnull(@StartDate, DateAdd(minute,-1,Cast(convert(char(16), getdate(),121) as datetime))) 
	End

ELSE 
	Begin
		set @StartDate = Cast(convert(char(16), @StartDate,121) as datetime)
		IF @1MinFromStartDate = 1 
		Begin
			Set @EndDate = DateAdd(minute, 1 , @StartDate)
			set @EndDate = dateadd(millisecond, -datepart(millisecond, @EndDate) -datepart(second, @EndDate)*1000 - 3, @EndDate)
		End
	End

--select @StartDate StartDate , @EndDate EndDate
if @StartDate >= @EndDate 
	Begin
		print 'Start Date is not greater than End Date'
		return

	End
IF Exists (select 1 from CRT_Data_1Minute where [CRTD_Period] > @StartDate)
	Begin
		select 'Period Already Exists' as [Reason]
		return
	End
select top 0 
	 cast([Id] as bigint) AS [Id],
       [PairSymbol],
      [BidReceivedDate],
      [Bid],
	  [Mid]
into #QuotesHist
from YB_Quotes.dbo.[SpotRatesHistory] with (nolock)

IF cast(@StartDate as date) = cast(@EndDate as date)
	Begin
		insert 	into #QuotesHist
		select [Id],[PairSymbol],[BidReceivedDate],[Bid],[Mid]
		from YB_Quotes.dbo.[SpotRatesHistory] with (nolock)
		where 1=1
		and cast([BidReceivedDate] as date) = cast(@StartDate as date)
		and [BidReceivedDate] between @StartDate and  @EndDate
	End
Else 
	Begin
		insert 	into #QuotesHist
		select [Id],[PairSymbol],[BidReceivedDate],[Bid],[Mid]
		from YB_Quotes.dbo.[SpotRatesHistory] with (nolock)
		where 1=1
		and [BidReceivedDate] between @StartDate and  @EndDate	
	End

select
       [PairSymbol],
       convert(varchar(16),[BidReceivedDate],121) as [minute],
       min([Bid]) as  Bid_Low ,  --- Low
	   max([Bid]) as  Bid_High, --- High
	   min([Mid]) as  Mid_Low ,  --- Low
	   max([Mid]) as  Mid_High, --- High
	   Count([Id]) as Cnt
into #c2
from #QuotesHist with (nolock)
where 1=1
and [BidReceivedDate] between @StartDate and  @EndDate
--and [PairSymbol] = 'EURUSD'
group by convert(varchar(16), [BidReceivedDate] ,121) ,[PairSymbol]

select
       [PairSymbol],
	   convert(varchar(16),[BidReceivedDate] ,121) as [minute],
	   [BidReceivedDate] AS [DateQuote],
	    
       [Bid] AS Bid_Val,
	   [Mid] AS Mid_Val,
	   ROW_NUMBER() over (partition by [PairSymbol],convert(varchar(16),[BidReceivedDate] ,121) order by [BidReceivedDate] ) as Bid_start,
       ROW_NUMBER() over (partition by [PairSymbol],convert(varchar(16),[BidReceivedDate] ,121) order by [BidReceivedDate] desc) as Bid_end
into #c3
from #QuotesHist with (nolock)
where 1=1
and [BidReceivedDate] between @StartDate and  @EndDate
--and [PairSymbol] = 'EURUSD'

select
       CM.[CRTD_PairSymbol] AS PairSymbol,
	   CM.CRTD_Period AS [minute],
	   CM.[CRTD_BidClosingValue] ,
	   CM.[CRTD_MidClosingValue] 	
into #c4	    
from YB_Charts.[dbo].[CRT_Data_1Minute] CM with (nolock)
	Inner Join #c2 as c2 ON CM.[CRTD_PairSymbol] = c2.[PairSymbol] collate SQL_Latin1_General_CP1_CI_AS and  CM.CRTD_Period =   DateAdd(minute, -1, c2.[minute])
where 1=1

create index ix_c2 on #c2(PairSymbol,[minute])
create index ix_c3 on #c3(PairSymbol,[minute])
create index ix_c3_Bid_start on #c3(Bid_start)
create index ix_c3_Bid_end on #c3(Bid_end)
create index ix_c4 on #c4(PairSymbol,[minute])

INSERT INTO [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])
select  distinct c2.[minute] [CRTD_Period], 
		c3.[DateQuote] [CRTD_FirstQuote],
		c3_Bid.[DateQuote] [CRTD_LastQuote],
		c2.PairSymbol,
		IsNull(c4.[CRTD_BidClosingValue],c3.Bid_Val)    as Bid_OpenValue,  
		IsNull(c3_Bid.Bid_Val,0)   as Bid_CloseValue, 
		Bid_Low, 
		Bid_High,
		IsNull(c4.[CRTD_MidClosingValue],c3.Mid_Val)     as Mid_OpenValue, 
		IsNull(c3_Bid.Mid_Val,0)  as Mid_CloseValue, 
		Mid_Low,
		Mid_High,
		GetDate() As Date_Inserted,
		c2.Cnt
from   #c2 as c2
       Inner join #c3 as c3 on c2.[PairSymbol] = c3.[PairSymbol] and c2.[minute] = c3.[minute] and Bid_start =1
       Inner join #c3 as c3_Bid on c2.[PairSymbol] = c3_Bid.[PairSymbol] and c2.[minute] = c3_Bid.[minute] and c3_Bid.Bid_end =1
	   left join #c4 as c4 on c2.[PairSymbol] = c4.[PairSymbol]  collate SQL_Latin1_General_CP1_CI_AS and c2.[minute] = DateAdd(minute,1,c4.[minute]) 
Where 1=1
and Not Exists (select 1 from [CRT_Data_1Minute] XX with (nolock) where XX.[CRTD_PairSymbol] = c2.PairSymbol collate SQL_Latin1_General_CP1_CI_AS 
	            and XX.[CRTD_Period] = c2.[minute])
order by 1,4

select @RowsAffected = @@RowCount
 
update CRT_Tasks
set CRTT_LastRun = @EndDate,
	CRTT_LastRowCount = @RowsAffected,
	CRTT_LastModifiedDate = GetDate()
where CRTT_TableName = 'CRT_Data_1Minute'
			
--select @RowsToProcess RowsToProcess, @RowsAffected RowsAffected
--select * from CRT_Tasks where CRTT_ID = 1
print Cast (@RowsAffected as varchar(10)) + ' Rows Processed'


--- select top 100 * from [dbo].[CRT_Data_1Minute] order by 1 desc
--- select * from [CRT_Tasks]

drop table #QuotesHist
drop table #c2
drop table #c3
drop table #c4


GO
/****** Object:  StoredProcedure [dbo].[USP_CRT_Agg_1Minute_2016_11_30]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create procedure [dbo].[USP_CRT_Agg_1Minute_2016_11_30]

	@StartDate datetime = NULL,
	@1MinFromStartDate Bit = 0
	
AS


SET NOCOUNT ON

declare @EndDate datetime,
		@RowsAffected int,
		@RowsToProcess int

SET	@RowsAffected = 0

SET @EndDate = dateadd(millisecond, -datepart(millisecond, getdate()) -datepart(second, getdate())*1000 - 3, getdate())

IF @StartDate is NULL
Begin


    --set @StartDate = DateAdd(minute,-1,Cast(convert(char(16), getdate(),121) as datetime))
	
	--select @StartDate = isnull(CRTT_LastRun, DateAdd(minute,-1,Cast(convert(char(16), getdate(),121) as datetime))) from CRT_Tasks with (nolock) where CRTT_TableName = 'CRT_Data_1Minute'
	select @StartDate = Max([CRTD_Period]) from [dbo].[CRT_Data_1Minute]
	select @StartDate = isnull(@StartDate, DateAdd(minute,-1,Cast(convert(char(16), getdate(),121) as datetime))) 
	--- select  isnull(CRTT_LastRun, DateAdd(minute,-1,Cast(convert(char(16), getdate(),121) as datetime))) from CRT_Tasks with (nolock) where CRTT_TableName = 'CRT_Data_1Minute'
	
End

ELSE Begin

	set @StartDate = Cast(convert(char(16), @StartDate,121) as datetime)
	IF @1MinFromStartDate = 1 
	Begin
		Set @EndDate = DateAdd(minute, 1 , @StartDate)
		set @EndDate = dateadd(millisecond, -datepart(millisecond, @EndDate) -datepart(second, @EndDate)*1000 - 3, @EndDate)
	End

End

--select @StartDate StartDate , @EndDate EndDate

if @StartDate >= @EndDate 
Begin
		print 'Start Date is not greater than End Date'
		return

End
IF Exists (select 1 from CRT_Data_1Minute where [CRTD_Period] > @StartDate)
Begin
		select 'Period Already Exists' as [Reason]
		return
End


select top 0 
	 cast([Id] as bigint) AS [Id],
       [PairSymbol],
      [BidReceivedDate],
      [Bid],
	  [Mid]
into #QuotesHist
from YB_Quotes.dbo.[SpotRatesHistory] with (nolock)



IF cast(@StartDate as date) = cast(@EndDate as date)
Begin
	insert 	into #QuotesHist
	select [Id],
       [PairSymbol],
      [BidReceivedDate],
      [Bid],
	  
	  [Mid]

	from YB_Quotes.dbo.[SpotRatesHistory] with (nolock)
	where 1=1
	and cast([BidReceivedDate] as date) = cast(@StartDate as date)
	and [BidReceivedDate] between @StartDate and  @EndDate
	--and [PairSymbol] = 'EURUSD'

End
Else Begin

		insert 	into #QuotesHist
		select [Id],
       [PairSymbol],
      [BidReceivedDate],
      [Bid],
	  
	  [Mid]

	from YB_Quotes.dbo.[SpotRatesHistory] with (nolock)
	where 1=1
	and [BidReceivedDate] between @StartDate and  @EndDate
	--and [PairSymbol] = 'EURUSD'



End




;with c2 as (
select
       [PairSymbol],
       convert(varchar(16),[BidReceivedDate],121) as [minute],
       min([Bid]) as  Bid_Low ,  --- Low
	   max([Bid]) as  Bid_High, --- High
	   min([Mid]) as  Mid_Low ,  --- Low
	   max([Mid]) as  Mid_High, --- High

	   Count([Id]) as Cnt
from #QuotesHist with (nolock)
where 1=1
and [BidReceivedDate] between @StartDate and  @EndDate
--and [PairSymbol] = 'EURUSD'
group by convert(varchar(16), [BidReceivedDate] ,121) ,[PairSymbol]
)

, c3 as (
select
       [PairSymbol],
	   convert(varchar(16),[BidReceivedDate] ,121) as [minute],
	   [BidReceivedDate] AS [DateQuote],
	    
       [Bid] AS Bid_Val,
	   [Mid] AS Mid_Val,
	   ROW_NUMBER() over (partition by [PairSymbol],convert(varchar(16),[BidReceivedDate] ,121) order by [BidReceivedDate] ) as Bid_start,
       ROW_NUMBER() over (partition by [PairSymbol],convert(varchar(16),[BidReceivedDate] ,121) order by [BidReceivedDate] desc) as Bid_end
from #QuotesHist with (nolock)
where 1=1
and [BidReceivedDate] between @StartDate and  @EndDate
--and [PairSymbol] = 'EURUSD'
)
,c4 as (
select
       CM.[CRTD_PairSymbol] AS PairSymbol,
	   CM.CRTD_Period AS [minute],
	   CM.[CRTD_BidClosingValue] ,
	   CM.[CRTD_MidClosingValue] 
	
	    
from YB_Charts.[dbo].[CRT_Data_1Minute] CM with (nolock)
Inner Join c2 
  ON CM.[CRTD_PairSymbol] = c2.[PairSymbol] collate SQL_Latin1_General_CP1_CI_AS 
  and  CM.CRTD_Period =   DateAdd(minute, -1, c2.[minute])
where 1=1

)



INSERT INTO [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])

select  distinct c2.[minute] [CRTD_Period], 
		c3.[DateQuote] [CRTD_FirstQuote],
		c3_Bid.[DateQuote] [CRTD_LastQuote],
		c2.PairSymbol,
		IsNull(c4.[CRTD_BidClosingValue],c3.Bid_Val)    as Bid_OpenValue,  
		IsNull(c3_Bid.Bid_Val,0)   as Bid_CloseValue, 
		Bid_Low, 
		Bid_High,
		IsNull(c4.[CRTD_MidClosingValue],c3.Mid_Val)     as Mid_OpenValue, 
		IsNull(c3_Bid.Mid_Val,0)  as Mid_CloseValue, 
		Mid_Low,
		Mid_High,
		GetDate() As Date_Inserted,
		c2.Cnt

from   c2
       Inner join c3  on c2.[PairSymbol] = c3.[PairSymbol] and c2.[minute] = c3.[minute] and Bid_start =1
       Inner join c3 as c3_Bid on c2.[PairSymbol] = c3_Bid.[PairSymbol] and c2.[minute] = c3_Bid.[minute] and c3_Bid.Bid_end =1
	   left join c4  on c2.[PairSymbol] = c4.[PairSymbol]  collate SQL_Latin1_General_CP1_CI_AS and c2.[minute] = DateAdd(minute,1,c4.[minute]) 
Where 1=1
and Not Exists (select 1 from [CRT_Data_1Minute] XX with (nolock) where XX.[CRTD_PairSymbol] = c2.PairSymbol collate SQL_Latin1_General_CP1_CI_AS 
	            and XX.[CRTD_Period] = c2.[minute])
order by 1,4

select @RowsAffected = @@RowCount
 
 			update CRT_Tasks
			set CRTT_LastRun = @EndDate,
				CRTT_LastRowCount = @RowsAffected,
				CRTT_LastModifiedDate = GetDate()
			where CRTT_TableName = 'CRT_Data_1Minute'
			
--select @RowsToProcess RowsToProcess, @RowsAffected RowsAffected
--select * from CRT_Tasks where CRTT_ID = 1
print Cast (@RowsAffected as varchar(10)) + ' Rows Processed'


--- select top 100 * from [dbo].[CRT_Data_1Minute] order by 1 desc
--- select * from [CRT_Tasks]

drop table #QuotesHist


GO
/****** Object:  StoredProcedure [dbo].[USP_CRT_Agg_1Minute_OLD]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE procedure [dbo].[USP_CRT_Agg_1Minute_OLD]

	@StartDate datetime = NULL,
	@1MinFromStartDate Bit = 0
	
AS


SET NOCOUNT ON

declare @EndDate datetime,
		@RowsAffected int,
		@RowsToProcess int

SET	@RowsAffected = 0

SET @EndDate = dateadd(millisecond, -datepart(millisecond, getdate()) -datepart(second, getdate())*1000 - 3, getdate())

IF @StartDate is NULL
Begin


    --set @StartDate = DateAdd(minute,-1,Cast(convert(char(16), getdate(),121) as datetime))
	
	--select @StartDate = isnull(CRTT_LastRun, DateAdd(minute,-1,Cast(convert(char(16), getdate(),121) as datetime))) from CRT_Tasks with (nolock) where CRTT_TableName = 'CRT_Data_1Minute'
	select @StartDate = Max([CRTD_Period]) from [dbo].[CRT_Data_1Minute]
	select @StartDate = isnull(@StartDate, DateAdd(minute,-1,Cast(convert(char(16), getdate(),121) as datetime))) 
	--- select  isnull(CRTT_LastRun, DateAdd(minute,-1,Cast(convert(char(16), getdate(),121) as datetime))) from CRT_Tasks with (nolock) where CRTT_TableName = 'CRT_Data_1Minute'
	
End

ELSE Begin

	set @StartDate = Cast(convert(char(16), @StartDate,121) as datetime)
	IF @1MinFromStartDate = 1 
	Begin
		Set @EndDate = DateAdd(minute, 1 , @StartDate)
		set @EndDate = dateadd(millisecond, -datepart(millisecond, @EndDate) -datepart(second, @EndDate)*1000 - 3, @EndDate)
	End

End

--select @StartDate StartDate , @EndDate EndDate

if @StartDate >= @EndDate 
Begin
		print 'Start Date is not greater than End Date'
		return

End
IF Exists (select 1 from CRT_Data_1Minute where [CRTD_Period] > @StartDate)
Begin
		select 'Period Already Exists' as [Reason]
		return
End

;with c2 as (
select
       [PairSymbol],
       convert(varchar(16),[BidReceivedDate],121) as [minute],
       min([Bid]) as  Bid_Low ,  --- Low
	   max([Bid]) as  Bid_High, --- High
	   min([Mid]) as  Mid_Low ,  --- Low
	   max([Mid]) as  Mid_High, --- High

	   Count([Id]) as Cnt
from YB_Quotes.dbo.[SpotRatesHistory] with (nolock)
where 1=1
and [BidReceivedDate] between @StartDate and  @EndDate
--and [PairSymbol] = 'EURUSD'
group by convert(varchar(16), [BidReceivedDate] ,121) ,[PairSymbol]
), c3 as (
select
       [PairSymbol],
	   convert(varchar(16),[BidReceivedDate] ,121) as [minute],
	   [BidReceivedDate] AS [DateQuote],
	    
       [Bid] AS Bid_Val,
	   [Mid] AS Mid_Val,
	   ROW_NUMBER() over (partition by [PairSymbol],convert(varchar(16),[BidReceivedDate] ,121) order by [BidReceivedDate] ) as Bid_start,
       ROW_NUMBER() over (partition by [PairSymbol],convert(varchar(16),[BidReceivedDate] ,121) order by [BidReceivedDate] desc) as Bid_end
from YB_Quotes.dbo.[SpotRatesHistory] with (nolock)
where 1=1
and [BidReceivedDate] between @StartDate and  @EndDate
--and [PairSymbol] = 'EURUSD'
)


INSERT INTO [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])

select  c2.[minute] [CRTD_Period], 
		c3.[DateQuote] [CRTD_FirstQuote],
		c3_Bid.[DateQuote] [CRTD_LastQuote],
		c2.PairSymbol,
		c3.Bid_Val    as Bid_OpenValue, 
		IsNull(c3_Bid.Bid_Val,0)   as Bid_CloseValue, 
		Bid_Low, 
		Bid_High,
		IsNull(c3.Mid_Val,0)     as Mid_OpenValue, 
		IsNull(c3_Bid.Mid_Val,0)  as Mid_CloseValue, 
		Mid_Low,
		Mid_High,
		GetDate() As Date_Inserted,
		c2.Cnt

from   c2
       Inner join c3  on c2.[PairSymbol] = c3.[PairSymbol] and c2.[minute] = c3.[minute] and Bid_start =1
       Inner join c3 as c3_Bid on c2.[PairSymbol] = c3_Bid.[PairSymbol] and c2.[minute] = c3_Bid.[minute] and c3_Bid.Bid_end =1
Where 1=1
and Not Exists (select 1 from [CRT_Data_1Minute] XX with (nolock) where XX.[CRTD_PairSymbol] = c2.PairSymbol collate SQL_Latin1_General_CP1_CI_AS 
	            and XX.[CRTD_Period] = c2.[minute])
order by 1,4

select @RowsAffected = @@RowCount
 
 			update CRT_Tasks
			set CRTT_LastRun = @EndDate,
				CRTT_LastRowCount = @RowsAffected,
				CRTT_LastModifiedDate = GetDate()
			where CRTT_TableName = 'CRT_Data_1Minute'
			
--select @RowsToProcess RowsToProcess, @RowsAffected RowsAffected
--select * from CRT_Tasks where CRTT_ID = 1
print Cast (@RowsAffected as varchar(10)) + ' Rows Processed'


--- select top 100 * from [dbo].[CRT_Data_1Minute] order by 1 desc
--- select * from [CRT_Tasks]


GO
/****** Object:  StoredProcedure [dbo].[USP_CRT_GetData]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[USP_CRT_GetData]
	@pair  varchar(50),
	@start DATETIME,
	@end DATETIME, 
	@resolution varchar(10)
AS

SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

/*
---- Example :
Exec [USP_CRT_GetData] 'EURUSD','2015-06-01', '2015-06-05','1'
*/


IF @resolution = '5' 
Begin
		SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_5Minutes]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]


	SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'

	FROM [dbo].[CRT_Data_LiveChart] 
	WHERE  [CRTD_PairSymbol] = @pair
	and [CRTD_TargetName] = '5Minutes'


    
End
ELSE IF @resolution = '15' 
Begin
		SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_15Minutes]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]

		SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'

	FROM [dbo].[CRT_Data_LiveChart] 
	WHERE  [CRTD_PairSymbol] = @pair
	and [CRTD_TargetName] = '15Minutes'



End
ELSE IF @resolution = '30' 
Begin

	SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_30Minutes]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]


	SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'

	FROM [dbo].[CRT_Data_LiveChart] 
	WHERE  [CRTD_PairSymbol] = @pair
	and [CRTD_TargetName] = '30Minutes'



End
ELSE IF @resolution = '60' 
Begin

	SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_1Hour]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]


	SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'

	FROM [dbo].[CRT_Data_LiveChart] 
	WHERE  [CRTD_PairSymbol] = @pair
	and [CRTD_TargetName] = '1Hour'




End
ELSE IF @resolution = '120' 
Begin
		SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_2Hours]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]


	SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'

	FROM [dbo].[CRT_Data_LiveChart] 
	WHERE  [CRTD_PairSymbol] = @pair
	and [CRTD_TargetName] = '2Hours'


End
ELSE IF @resolution = '240' 
Begin

	SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_4Hours]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]


	SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'

	FROM [dbo].[CRT_Data_LiveChart] 
	WHERE  [CRTD_PairSymbol] = @pair
	and [CRTD_TargetName] = '4Hours'


End
ELSE IF @resolution = '480' 
Begin
		SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_8Hours]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]


	SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'

	FROM [dbo].[CRT_Data_LiveChart] 
	WHERE  [CRTD_PairSymbol] = @pair
	and [CRTD_TargetName] = '8Hours'


End
ELSE IF @resolution = 'D' 
Begin

	SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_1Day]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]

	
	SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'

	FROM [dbo].[CRT_Data_LiveChart] 
	WHERE  [CRTD_PairSymbol] = @pair
	and [CRTD_TargetName] = '1Day'



End
ELSE IF @resolution = 'W' 
Begin
		SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_1Week]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]


	SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'

	FROM [dbo].[CRT_Data_LiveChart] 
	WHERE  [CRTD_PairSymbol] = @pair
	and [CRTD_TargetName] = '1Week'


End
ELSE IF @resolution = 'M' 
Begin

		SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_1Month]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period]

	SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'

	FROM [dbo].[CRT_Data_LiveChart] 
	WHERE  [CRTD_PairSymbol] = @pair
	and [CRTD_TargetName] = '1Month'


End
ELSE
Begin
		---- 1 Minute
	SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'


	FROM [CRT_Data_1Minute]
	WHERE [CRTD_Period] >= @start
		AND [CRTD_Period] <= @end
		AND [CRTD_PairSymbol] = @pair
   ORDER BY [CRTD_Period]


   	SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'

	FROM [dbo].[CRT_Data_LiveChart] 
	WHERE  [CRTD_PairSymbol] = @pair
	and [CRTD_TargetName] = '1Minute'



End

RETURN 0

GO
/****** Object:  StoredProcedure [dbo].[USP_CRT_GetData_LastBars]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[USP_CRT_GetData_LastBars]
      @pair  varchar(50),
      @toDate DATETIME = Null, 
      @numOfBars int,
      @resolution varchar(10)
AS

SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


IF @toDate Is Null
      SET @toDate = GetDate()


/*
---- Example :
Exec [USP_CRT_GetData_LastBars] 'EURUSD','2016-05-23 15:25', 25,'W'
*/




IF @resolution = '5' 
Begin

           SELECT Top (@numOfBars) 
                             [CRTD_Period] as 'Timestamp'
                            ,[CRTD_BidOpeningValue] as 'BidOpen'
                            ,[CRTD_BidClosingValue] as 'BidClose'
                            ,[CRTD_BidLowValue] as 'BidLow'
                            ,[CRTD_BidHighValue] as 'BidHigh'

                            ,[CRTD_MidOpeningValue] as 'MidOpen'
                            ,[CRTD_MidClosingValue] as 'MidClose'
                            ,[CRTD_MidLowValue] as 'MidLow'
                            ,[CRTD_MidHighValue] as 'MidHigh'

      into #Charts_5
      FROM [CRT_Data_5Minutes]
      WHERE 1 = 1
           AND [CRTD_Period] <= @toDate
           AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period] Desc

      SELECT * FROM #Charts_5
    ORDER BY [Timestamp]

      SELECT 
            [CRTD_Period] as 'Timestamp'
           ,[CRTD_BidOpeningValue] as 'BidOpen'
           ,[CRTD_BidClosingValue] as 'BidClose'
           ,[CRTD_BidLowValue] as 'BidLow'
           ,[CRTD_BidHighValue] as 'BidHigh'

           ,[CRTD_MidOpeningValue] as 'MidOpen'
           ,[CRTD_MidClosingValue] as 'MidClose'
           ,[CRTD_MidLowValue] as 'MidLow'
           ,[CRTD_MidHighValue] as 'MidHigh'

      FROM [dbo].[CRT_Data_LiveChart] 
      WHERE  [CRTD_PairSymbol] = @pair
      and [CRTD_TargetName] = '5Minutes'


    
End
ELSE IF @resolution = '15' 
Begin
           SELECT Top (@numOfBars) 
                             [CRTD_Period] as 'Timestamp'
                            ,[CRTD_BidOpeningValue] as 'BidOpen'
                            ,[CRTD_BidClosingValue] as 'BidClose'
                            ,[CRTD_BidLowValue] as 'BidLow'
                            ,[CRTD_BidHighValue] as 'BidHigh'

                            ,[CRTD_MidOpeningValue] as 'MidOpen'
                            ,[CRTD_MidClosingValue] as 'MidClose'
                            ,[CRTD_MidLowValue] as 'MidLow'
                            ,[CRTD_MidHighValue] as 'MidHigh'

           into #Charts_15
           FROM [CRT_Data_15Minutes]
           WHERE 1 = 1
                 AND [CRTD_Period] <= @toDate
                 AND [CRTD_PairSymbol] = @pair
           ORDER BY [CRTD_Period] Desc


           SELECT * FROM #Charts_15
           ORDER BY [Timestamp]

           SELECT 
                       [CRTD_Period] as 'Timestamp'
                      ,[CRTD_BidOpeningValue] as 'BidOpen'
                      ,[CRTD_BidClosingValue] as 'BidClose'
                      ,[CRTD_BidLowValue] as 'BidLow'
                      ,[CRTD_BidHighValue] as 'BidHigh'

                      ,[CRTD_MidOpeningValue] as 'MidOpen'
                      ,[CRTD_MidClosingValue] as 'MidClose'
                      ,[CRTD_MidLowValue] as 'MidLow'
                      ,[CRTD_MidHighValue] as 'MidHigh'

      FROM [dbo].[CRT_Data_LiveChart] 
      WHERE  [CRTD_PairSymbol] = @pair
      and [CRTD_TargetName] = '15Minutes'



End
ELSE IF @resolution = '30' 
Begin

      SELECT Top (@numOfBars) 
            [CRTD_Period] as 'Timestamp'
           ,[CRTD_BidOpeningValue] as 'BidOpen'
           ,[CRTD_BidClosingValue] as 'BidClose'
           ,[CRTD_BidLowValue] as 'BidLow'
           ,[CRTD_BidHighValue] as 'BidHigh'

           ,[CRTD_MidOpeningValue] as 'MidOpen'
           ,[CRTD_MidClosingValue] as 'MidClose'
           ,[CRTD_MidLowValue] as 'MidLow'
           ,[CRTD_MidHighValue] as 'MidHigh'

      into #Charts_30
      FROM [CRT_Data_30Minutes]
      WHERE 1 = 1
           AND [CRTD_Period] <= @toDate
           AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period] Desc


      SELECT * FROM #Charts_30
    ORDER BY [Timestamp]


      SELECT 
            [CRTD_Period] as 'Timestamp'
           ,[CRTD_BidOpeningValue] as 'BidOpen'
           ,[CRTD_BidClosingValue] as 'BidClose'
           ,[CRTD_BidLowValue] as 'BidLow'
           ,[CRTD_BidHighValue] as 'BidHigh'

           ,[CRTD_MidOpeningValue] as 'MidOpen'
           ,[CRTD_MidClosingValue] as 'MidClose'
           ,[CRTD_MidLowValue] as 'MidLow'
           ,[CRTD_MidHighValue] as 'MidHigh'

      FROM [dbo].[CRT_Data_LiveChart] 
      WHERE  [CRTD_PairSymbol] = @pair
      and [CRTD_TargetName] = '30Minutes'



End
ELSE IF @resolution = '60' 
Begin

      SELECT Top (@numOfBars) 
            [CRTD_Period] as 'Timestamp'
           ,[CRTD_BidOpeningValue] as 'BidOpen'
           ,[CRTD_BidClosingValue] as 'BidClose'
           ,[CRTD_BidLowValue] as 'BidLow'
           ,[CRTD_BidHighValue] as 'BidHigh'

           ,[CRTD_MidOpeningValue] as 'MidOpen'
           ,[CRTD_MidClosingValue] as 'MidClose'
           ,[CRTD_MidLowValue] as 'MidLow'
           ,[CRTD_MidHighValue] as 'MidHigh'

      into #Charts_60
      FROM [CRT_Data_1Hour]
      WHERE 1 = 1
           AND [CRTD_Period] <= @toDate
           AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period] Desc

      SELECT * FROM #Charts_60
      ORDER BY [Timestamp]


      SELECT 
            [CRTD_Period] as 'Timestamp'
           ,[CRTD_BidOpeningValue] as 'BidOpen'
           ,[CRTD_BidClosingValue] as 'BidClose'
           ,[CRTD_BidLowValue] as 'BidLow'
           ,[CRTD_BidHighValue] as 'BidHigh'

           ,[CRTD_MidOpeningValue] as 'MidOpen'
           ,[CRTD_MidClosingValue] as 'MidClose'
           ,[CRTD_MidLowValue] as 'MidLow'
           ,[CRTD_MidHighValue] as 'MidHigh'

      FROM [dbo].[CRT_Data_LiveChart] 
      WHERE  [CRTD_PairSymbol] = @pair
      and [CRTD_TargetName] = '1Hour'




End
ELSE IF @resolution = '120' 
Begin
           SELECT Top (@numOfBars) 
            [CRTD_Period] as 'Timestamp'
           ,[CRTD_BidOpeningValue] as 'BidOpen'
           ,[CRTD_BidClosingValue] as 'BidClose'
           ,[CRTD_BidLowValue] as 'BidLow'
           ,[CRTD_BidHighValue] as 'BidHigh'

           ,[CRTD_MidOpeningValue] as 'MidOpen'
           ,[CRTD_MidClosingValue] as 'MidClose'
           ,[CRTD_MidLowValue] as 'MidLow'
           ,[CRTD_MidHighValue] as 'MidHigh'

      into #Charts_120
      FROM [CRT_Data_2Hours]
      WHERE 1 = 1
           AND [CRTD_Period] <= @toDate
           AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period] Desc

      SELECT * FROM #Charts_120
    ORDER BY [Timestamp]


      SELECT 
            [CRTD_Period] as 'Timestamp'
           ,[CRTD_BidOpeningValue] as 'BidOpen'
           ,[CRTD_BidClosingValue] as 'BidClose'
           ,[CRTD_BidLowValue] as 'BidLow'
           ,[CRTD_BidHighValue] as 'BidHigh'

           ,[CRTD_MidOpeningValue] as 'MidOpen'
           ,[CRTD_MidClosingValue] as 'MidClose'
           ,[CRTD_MidLowValue] as 'MidLow'
           ,[CRTD_MidHighValue] as 'MidHigh'

      FROM [dbo].[CRT_Data_LiveChart] 
      WHERE  [CRTD_PairSymbol] = @pair
      and [CRTD_TargetName] = '2Hours'


End
ELSE IF @resolution = '240' 
Begin

      SELECT Top (@numOfBars) 
            [CRTD_Period] as 'Timestamp'
           ,[CRTD_BidOpeningValue] as 'BidOpen'
           ,[CRTD_BidClosingValue] as 'BidClose'
           ,[CRTD_BidLowValue] as 'BidLow'
           ,[CRTD_BidHighValue] as 'BidHigh'

           ,[CRTD_MidOpeningValue] as 'MidOpen'
           ,[CRTD_MidClosingValue] as 'MidClose'
           ,[CRTD_MidLowValue] as 'MidLow'
           ,[CRTD_MidHighValue] as 'MidHigh'

      into #Charts_240
      FROM [CRT_Data_4Hours]
      WHERE 1 = 1
           AND [CRTD_Period] <= @toDate
           AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period] Desc


      SELECT * FROM #Charts_240
      ORDER BY [Timestamp]


      SELECT 
            [CRTD_Period] as 'Timestamp'
           ,[CRTD_BidOpeningValue] as 'BidOpen'
           ,[CRTD_BidClosingValue] as 'BidClose'
           ,[CRTD_BidLowValue] as 'BidLow'
           ,[CRTD_BidHighValue] as 'BidHigh'

           ,[CRTD_MidOpeningValue] as 'MidOpen'
           ,[CRTD_MidClosingValue] as 'MidClose'
           ,[CRTD_MidLowValue] as 'MidLow'
           ,[CRTD_MidHighValue] as 'MidHigh'

      FROM [dbo].[CRT_Data_LiveChart] 
      WHERE  [CRTD_PairSymbol] = @pair
      and [CRTD_TargetName] = '4Hours'


End
ELSE IF @resolution = '480' 
Begin
           SELECT Top (@numOfBars) 
            [CRTD_Period] as 'Timestamp'
           ,[CRTD_BidOpeningValue] as 'BidOpen'
           ,[CRTD_BidClosingValue] as 'BidClose'
           ,[CRTD_BidLowValue] as 'BidLow'
           ,[CRTD_BidHighValue] as 'BidHigh'

           ,[CRTD_MidOpeningValue] as 'MidOpen'
           ,[CRTD_MidClosingValue] as 'MidClose'
           ,[CRTD_MidLowValue] as 'MidLow'
           ,[CRTD_MidHighValue] as 'MidHigh'

      into #Charts_480
      FROM [CRT_Data_8Hours]
      WHERE 1 = 1
           AND [CRTD_Period] <= @toDate
           AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period] Desc

      SELECT * FROM #Charts_480
    ORDER BY [Timestamp]


      SELECT 
            [CRTD_Period] as 'Timestamp'
           ,[CRTD_BidOpeningValue] as 'BidOpen'
           ,[CRTD_BidClosingValue] as 'BidClose'
           ,[CRTD_BidLowValue] as 'BidLow'
           ,[CRTD_BidHighValue] as 'BidHigh'

           ,[CRTD_MidOpeningValue] as 'MidOpen'
           ,[CRTD_MidClosingValue] as 'MidClose'
           ,[CRTD_MidLowValue] as 'MidLow'
           ,[CRTD_MidHighValue] as 'MidHigh'

      FROM [dbo].[CRT_Data_LiveChart] 
      WHERE  [CRTD_PairSymbol] = @pair
      and [CRTD_TargetName] = '8Hours'


End
ELSE IF @resolution = 'D' 
Begin

      SELECT Top (@numOfBars) 
            [CRTD_Period] as 'Timestamp'
           ,[CRTD_BidOpeningValue] as 'BidOpen'
           ,[CRTD_BidClosingValue] as 'BidClose'
           ,[CRTD_BidLowValue] as 'BidLow'
           ,[CRTD_BidHighValue] as 'BidHigh'

           ,[CRTD_MidOpeningValue] as 'MidOpen'
           ,[CRTD_MidClosingValue] as 'MidClose'
           ,[CRTD_MidLowValue] as 'MidLow'
           ,[CRTD_MidHighValue] as 'MidHigh'

      into #Charts_D
      FROM [CRT_Data_1Day]
      WHERE 1 = 1
           AND [CRTD_Period] <= @toDate
           AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period] Desc


      SELECT * FROM #Charts_D
    ORDER BY [Timestamp]

      
      SELECT 
            [CRTD_Period] as 'Timestamp'
           ,[CRTD_BidOpeningValue] as 'BidOpen'
           ,[CRTD_BidClosingValue] as 'BidClose'
           ,[CRTD_BidLowValue] as 'BidLow'
           ,[CRTD_BidHighValue] as 'BidHigh'

           ,[CRTD_MidOpeningValue] as 'MidOpen'
           ,[CRTD_MidClosingValue] as 'MidClose'
           ,[CRTD_MidLowValue] as 'MidLow'
           ,[CRTD_MidHighValue] as 'MidHigh'

      FROM [dbo].[CRT_Data_LiveChart] 
      WHERE  [CRTD_PairSymbol] = @pair
      and [CRTD_TargetName] = '1Day'



End
ELSE IF @resolution = 'W' 
Begin
           SELECT Top (@numOfBars) 
            [CRTD_Period] as 'Timestamp'
           ,[CRTD_BidOpeningValue] as 'BidOpen'
           ,[CRTD_BidClosingValue] as 'BidClose'
           ,[CRTD_BidLowValue] as 'BidLow'
           ,[CRTD_BidHighValue] as 'BidHigh'

           ,[CRTD_MidOpeningValue] as 'MidOpen'
           ,[CRTD_MidClosingValue] as 'MidClose'
           ,[CRTD_MidLowValue] as 'MidLow'
           ,[CRTD_MidHighValue] as 'MidHigh'

      into #Charts_W
      FROM [CRT_Data_1Week]
      WHERE 1 = 1
           AND [CRTD_Period] <= @toDate
           AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period] Desc

      SELECT * FROM #Charts_W
      ORDER BY [Timestamp]


      SELECT 
            [CRTD_Period] as 'Timestamp'
           ,[CRTD_BidOpeningValue] as 'BidOpen'
           ,[CRTD_BidClosingValue] as 'BidClose'
           ,[CRTD_BidLowValue] as 'BidLow'
           ,[CRTD_BidHighValue] as 'BidHigh'

           ,[CRTD_MidOpeningValue] as 'MidOpen'
           ,[CRTD_MidClosingValue] as 'MidClose'
           ,[CRTD_MidLowValue] as 'MidLow'
           ,[CRTD_MidHighValue] as 'MidHigh'

      FROM [dbo].[CRT_Data_LiveChart] 
      WHERE  [CRTD_PairSymbol] = @pair
      and [CRTD_TargetName] = '1Week'


End
ELSE IF @resolution = 'M' 
Begin

           SELECT Top (@numOfBars) 
            [CRTD_Period] as 'Timestamp'
           ,[CRTD_BidOpeningValue] as 'BidOpen'
           ,[CRTD_BidClosingValue] as 'BidClose'
           ,[CRTD_BidLowValue] as 'BidLow'
           ,[CRTD_BidHighValue] as 'BidHigh'

           ,[CRTD_MidOpeningValue] as 'MidOpen'
           ,[CRTD_MidClosingValue] as 'MidClose'
           ,[CRTD_MidLowValue] as 'MidLow'
           ,[CRTD_MidHighValue] as 'MidHigh'

      into #Charts_M
      FROM [CRT_Data_1Month]
      WHERE 1 = 1
           AND [CRTD_Period] <= @toDate
           AND [CRTD_PairSymbol] = @pair
    ORDER BY [CRTD_Period] Desc


      SELECT * FROM #Charts_M
    ORDER BY [Timestamp]

      SELECT 
            [CRTD_Period] as 'Timestamp'
           ,[CRTD_BidOpeningValue] as 'BidOpen'
           ,[CRTD_BidClosingValue] as 'BidClose'
           ,[CRTD_BidLowValue] as 'BidLow'
           ,[CRTD_BidHighValue] as 'BidHigh'

           ,[CRTD_MidOpeningValue] as 'MidOpen'
           ,[CRTD_MidClosingValue] as 'MidClose'
           ,[CRTD_MidLowValue] as 'MidLow'
           ,[CRTD_MidHighValue] as 'MidHigh'

      FROM [dbo].[CRT_Data_LiveChart] 
      WHERE  [CRTD_PairSymbol] = @pair
      and [CRTD_TargetName] = '1Month'


End
ELSE
Begin
           ---- 1 Minute
      SELECT Top (@numOfBars) 
            [CRTD_Period] as 'Timestamp'
           ,[CRTD_BidOpeningValue] as 'BidOpen'
           ,[CRTD_BidClosingValue] as 'BidClose'
           ,[CRTD_BidLowValue] as 'BidLow'
           ,[CRTD_BidHighValue] as 'BidHigh'

           ,[CRTD_MidOpeningValue] as 'MidOpen'
           ,[CRTD_MidClosingValue] as 'MidClose'
           ,[CRTD_MidLowValue] as 'MidLow'
           ,[CRTD_MidHighValue] as 'MidHigh'

      into #Charts
      FROM [CRT_Data_1Minute]
      WHERE 1 = 1
           AND [CRTD_Period] <= @toDate
           AND [CRTD_PairSymbol] = @pair
   ORDER BY [CRTD_Period] Desc

   SELECT * FROM #Charts
   ORDER BY [Timestamp]


     SELECT 
            [CRTD_Period] as 'Timestamp'
           ,[CRTD_BidOpeningValue] as 'BidOpen'
           ,[CRTD_BidClosingValue] as 'BidClose'
           ,[CRTD_BidLowValue] as 'BidLow'
           ,[CRTD_BidHighValue] as 'BidHigh'

           ,[CRTD_MidOpeningValue] as 'MidOpen'
           ,[CRTD_MidClosingValue] as 'MidClose'
           ,[CRTD_MidLowValue] as 'MidLow'
           ,[CRTD_MidHighValue] as 'MidHigh'

      FROM [dbo].[CRT_Data_LiveChart] 
      WHERE  [CRTD_PairSymbol] = @pair
      and [CRTD_TargetName] = '1Minute'



End

RETURN 0


GO
/****** Object:  StoredProcedure [dbo].[USP_CRT_GetLiveData]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[USP_CRT_GetLiveData]

AS
		SELECT 
		 [CRTD_Period] as 'Timestamp'
		,[CRTD_BidOpeningValue] as 'BidOpen'
		,[CRTD_BidClosingValue] as 'BidClose'
		,[CRTD_BidLowValue] as 'BidLow'
		,[CRTD_BidHighValue] as 'BidHigh'

		,[CRTD_MidOpeningValue] as 'MidOpen'
		,[CRTD_MidClosingValue] as 'MidClose'
		,[CRTD_MidLowValue] as 'MidLow'
		,[CRTD_MidHighValue] as 'MidHigh'

		,[CRTD_PairSymbol] as 'PairSymbol'
		,CASE [CRTD_TargetName] 
			WHEN '5Minutes' THEN '5'
			WHEN '15Minutes' THEN '15'
			WHEN '30Minutes' THEN '30'
			WHEN '1Hour' THEN '60'
			WHEN '2Hours' THEN '120'
			WHEN '4Hours' THEN '240'
			WHEN '8Hours' THEN '480'
			WHEN '1Day' THEN 'D'
			WHEN '1Week' THEN 'W'
			WHEN '1Month' THEN 'M'
			ELSE '1'
		 END as 'Interval'

	FROM [dbo].[CRT_Data_LiveChart] 
RETURN 0

GO
/****** Object:  StoredProcedure [dbo].[USP_CRT_LiveChartDataInit]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*




*/

CREATE Procedure [dbo].[USP_CRT_LiveChartDataInit]




	 @PairSymbol varchar(50)

AS 



--- EXEC USP_CRT_LiveChartDataInit @PairSymbol = 'SYBGBP'

---- truncate table [CRT_Data_LiveChart]
--delete from CRT_Data_LiveChart where [CRTD_PairSymbol] = @PairSymbol


IF EXISTS ( select 1 from [CRT_Data_LiveChart] where [CRTD_PairSymbol] = @PairSymbol)
Begin
	print 'Data Already Exists'
	Return 1
End


INSERT INTO [dbo].[CRT_Data_LiveChart]
           ([CRTD_TargetName]
           ,[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_DateModified]
           )
 select top 1 '15Minutes' AS [CRTD_TargetName],
		Max([CRTD_Period]) AS [CRTD_Period] ,
		Max([CRTD_LastQuote]) AS [CRTD_FirstQuote],
		Max([CRTD_LastQuote]) AS [CRTD_LastQuote],
		@PairSymbol [CRTD_PairSymbol],
		0 AS 	[CRTD_BidOpeningValue],
        0 AS    [CRTD_BidClosingValue],
        Max([CRTD_BidLowValue])   AS  [CRTD_BidLowValue],
        Min([CRTD_BidHighValue])  AS  [CRTD_BidHighValue],
        0 AS    [CRTD_MidOpeningValue],
        0 AS   [CRTD_MidClosingValue],
        Max([CRTD_MidLowValue]) AS  [CRTD_MidLowValue],
        Min([CRTD_MidHighValue]) AS [CRTD_MidHighValue],
        GetDate() AS [CRTD_DateModified]

from [dbo].[CRT_Data_15Minutes] with (nolock)
WHERE  [CRTD_PairSymbol] = @PairSymbol
Group By [CRTD_PairSymbol]


UNION

 select '1Day' AS [CRTD_TargetName],
		Max([CRTD_Period]) AS [CRTD_Period] ,
		Max([CRTD_LastQuote]) AS [CRTD_FirstQuote],
		Max([CRTD_LastQuote]) AS [CRTD_LastQuote],
		[CRTD_PairSymbol],
		0 AS 	[CRTD_BidOpeningValue],
        0 AS    [CRTD_BidClosingValue],
        Max([CRTD_BidLowValue])   AS  [CRTD_BidLowValue],
        Min([CRTD_BidHighValue])  AS  [CRTD_BidHighValue],
        0 AS    [CRTD_MidOpeningValue],
        0 AS   [CRTD_MidClosingValue],
        Max([CRTD_MidLowValue]) AS  [CRTD_MidLowValue],
        Min([CRTD_MidHighValue]) AS [CRTD_MidHighValue],
        GetDate() AS [CRTD_DateModified]

from [dbo].[CRT_Data_1Day] with (nolock)
	WHERE  [CRTD_PairSymbol] = @PairSymbol
Group By [CRTD_PairSymbol]

UNION


 select '1Hour' AS [CRTD_TargetName],
		Max([CRTD_Period]) AS [CRTD_Period] ,
		Max([CRTD_LastQuote]) AS [CRTD_FirstQuote],
		Max([CRTD_LastQuote]) AS [CRTD_LastQuote],
		[CRTD_PairSymbol],
		0 AS 	[CRTD_BidOpeningValue],
        0 AS    [CRTD_BidClosingValue],
        Max([CRTD_BidLowValue])   AS  [CRTD_BidLowValue],
        Min([CRTD_BidHighValue])  AS  [CRTD_BidHighValue],
        0 AS    [CRTD_MidOpeningValue],
        0 AS   [CRTD_MidClosingValue],
        Max([CRTD_MidLowValue]) AS  [CRTD_MidLowValue],
        Min([CRTD_MidHighValue]) AS [CRTD_MidHighValue],
        GetDate() AS [CRTD_DateModified]

from [dbo].[CRT_Data_1Hour] with (nolock)
	WHERE  [CRTD_PairSymbol] = @PairSymbol
Group By [CRTD_PairSymbol]


UNION

 select '1Minute' AS [CRTD_TargetName],
		Max([CRTD_Period]) AS [CRTD_Period] ,
		Max([CRTD_LastQuote]) AS [CRTD_FirstQuote],
		Max([CRTD_LastQuote]) AS [CRTD_LastQuote],
		[CRTD_PairSymbol],
		0 AS 	[CRTD_BidOpeningValue],
        0 AS    [CRTD_BidClosingValue],
        Max([CRTD_BidLowValue])   AS  [CRTD_BidLowValue],
        Min([CRTD_BidHighValue])  AS  [CRTD_BidHighValue],
        0 AS    [CRTD_MidOpeningValue],
        0 AS   [CRTD_MidClosingValue],
        Max([CRTD_MidLowValue]) AS  [CRTD_MidLowValue],
        Min([CRTD_MidHighValue]) AS [CRTD_MidHighValue],
        GetDate() AS [CRTD_DateModified]

from [dbo].[CRT_Data_1Minute] with (nolock)
	WHERE  [CRTD_PairSymbol] = @PairSymbol
Group By [CRTD_PairSymbol]


UNION

 select '1Month' AS [CRTD_TargetName],
		Max([CRTD_Period]) AS [CRTD_Period] ,
		Max([CRTD_LastQuote]) AS [CRTD_FirstQuote],
		Max([CRTD_LastQuote]) AS [CRTD_LastQuote],
		[CRTD_PairSymbol],
		0 AS 	[CRTD_BidOpeningValue],
        0 AS    [CRTD_BidClosingValue],
        Max([CRTD_BidLowValue])   AS  [CRTD_BidLowValue],
        Min([CRTD_BidHighValue])  AS  [CRTD_BidHighValue],
        0 AS    [CRTD_MidOpeningValue],
        0 AS   [CRTD_MidClosingValue],
        Max([CRTD_MidLowValue]) AS  [CRTD_MidLowValue],
        Min([CRTD_MidHighValue]) AS [CRTD_MidHighValue],
        GetDate() AS [CRTD_DateModified]

from [dbo].[CRT_Data_1Month] with (nolock)
	WHERE  [CRTD_PairSymbol] = @PairSymbol
Group By [CRTD_PairSymbol]



UNION

 select '1Week' AS [CRTD_TargetName],
		Max([CRTD_Period]) AS [CRTD_Period] ,
		Max([CRTD_LastQuote]) AS [CRTD_FirstQuote],
		Max([CRTD_LastQuote]) AS [CRTD_LastQuote],
		[CRTD_PairSymbol],
		0 AS 	[CRTD_BidOpeningValue],
        0 AS    [CRTD_BidClosingValue],
        Max([CRTD_BidLowValue])   AS  [CRTD_BidLowValue],
        Min([CRTD_BidHighValue])  AS  [CRTD_BidHighValue],
        0 AS    [CRTD_MidOpeningValue],
        0 AS   [CRTD_MidClosingValue],
        Max([CRTD_MidLowValue]) AS  [CRTD_MidLowValue],
        Min([CRTD_MidHighValue]) AS [CRTD_MidHighValue],
        GetDate() AS [CRTD_DateModified]

from [dbo].[CRT_Data_1Week] with (nolock)
	WHERE  [CRTD_PairSymbol] = @PairSymbol
Group By [CRTD_PairSymbol]


UNION

 select '2Hours' AS [CRTD_TargetName],
		Max([CRTD_Period]) AS [CRTD_Period] ,
		Max([CRTD_LastQuote]) AS [CRTD_FirstQuote],
		Max([CRTD_LastQuote]) AS [CRTD_LastQuote],
		[CRTD_PairSymbol],
		0 AS 	[CRTD_BidOpeningValue],
        0 AS    [CRTD_BidClosingValue],
        Max([CRTD_BidLowValue])   AS  [CRTD_BidLowValue],
        Min([CRTD_BidHighValue])  AS  [CRTD_BidHighValue],
        0 AS    [CRTD_MidOpeningValue],
        0 AS   [CRTD_MidClosingValue],
        Max([CRTD_MidLowValue]) AS  [CRTD_MidLowValue],
        Min([CRTD_MidHighValue]) AS [CRTD_MidHighValue],
        GetDate() AS [CRTD_DateModified]

from [dbo].[CRT_Data_2Hours] with (nolock)
	WHERE  [CRTD_PairSymbol] = @PairSymbol
Group By [CRTD_PairSymbol]


UNION

 select '30Minutes' AS [CRTD_TargetName],
		Max([CRTD_Period]) AS [CRTD_Period] ,
		Max([CRTD_LastQuote]) AS [CRTD_FirstQuote],
		Max([CRTD_LastQuote]) AS [CRTD_LastQuote],
		[CRTD_PairSymbol],
		0 AS 	[CRTD_BidOpeningValue],
        0 AS    [CRTD_BidClosingValue],
        Max([CRTD_BidLowValue])   AS  [CRTD_BidLowValue],
        Min([CRTD_BidHighValue])  AS  [CRTD_BidHighValue],
        0 AS    [CRTD_MidOpeningValue],
        0 AS   [CRTD_MidClosingValue],
        Max([CRTD_MidLowValue]) AS  [CRTD_MidLowValue],
        Min([CRTD_MidHighValue]) AS [CRTD_MidHighValue],
        GetDate() AS [CRTD_DateModified]

from [dbo].[CRT_Data_30Minutes] with (nolock)
	WHERE  [CRTD_PairSymbol] = @PairSymbol
Group By [CRTD_PairSymbol]

UNION

 select '4Hours' AS [CRTD_TargetName],
		Max([CRTD_Period]) AS [CRTD_Period] ,
		Max([CRTD_LastQuote]) AS [CRTD_FirstQuote],
		Max([CRTD_LastQuote]) AS [CRTD_LastQuote],
		[CRTD_PairSymbol],
		0 AS 	[CRTD_BidOpeningValue],
        0 AS    [CRTD_BidClosingValue],
        Max([CRTD_BidLowValue])   AS  [CRTD_BidLowValue],
        Min([CRTD_BidHighValue])  AS  [CRTD_BidHighValue],
        0 AS    [CRTD_MidOpeningValue],
        0 AS   [CRTD_MidClosingValue],
        Max([CRTD_MidLowValue]) AS  [CRTD_MidLowValue],
        Min([CRTD_MidHighValue]) AS [CRTD_MidHighValue],
        GetDate() AS [CRTD_DateModified]

from [dbo].[CRT_Data_4Hours] with (nolock)
	WHERE  [CRTD_PairSymbol] = @PairSymbol
Group By [CRTD_PairSymbol]


UNION

 select '5Minutes' AS [CRTD_TargetName],
		Max([CRTD_Period]) AS [CRTD_Period] ,
		Max([CRTD_LastQuote]) AS [CRTD_FirstQuote],
		Max([CRTD_LastQuote]) AS [CRTD_LastQuote],
		[CRTD_PairSymbol],
		0 AS 	[CRTD_BidOpeningValue],
        0 AS    [CRTD_BidClosingValue],
        Max([CRTD_BidLowValue])   AS  [CRTD_BidLowValue],
        Min([CRTD_BidHighValue])  AS  [CRTD_BidHighValue],
        0 AS    [CRTD_MidOpeningValue],
        0 AS   [CRTD_MidClosingValue],
        Max([CRTD_MidLowValue]) AS  [CRTD_MidLowValue],
        Min([CRTD_MidHighValue]) AS [CRTD_MidHighValue],
        GetDate() AS [CRTD_DateModified]

from [dbo].[CRT_Data_5Minutes] with (nolock)
	WHERE  [CRTD_PairSymbol] = @PairSymbol
Group By [CRTD_PairSymbol]

UNION

 select '8Hours' AS [CRTD_TargetName],
		Max([CRTD_Period]) AS [CRTD_Period] ,
		Max([CRTD_LastQuote]) AS [CRTD_FirstQuote],
		Max([CRTD_LastQuote]) AS [CRTD_LastQuote],
		[CRTD_PairSymbol],
		0 AS 	[CRTD_BidOpeningValue],
        0 AS    [CRTD_BidClosingValue],
        Max([CRTD_BidLowValue])   AS  [CRTD_BidLowValue],
        Min([CRTD_BidHighValue])  AS  [CRTD_BidHighValue],
        0 AS    [CRTD_MidOpeningValue],
        0 AS   [CRTD_MidClosingValue],
        Max([CRTD_MidLowValue]) AS  [CRTD_MidLowValue],
        Min([CRTD_MidHighValue]) AS [CRTD_MidHighValue],
        GetDate() AS [CRTD_DateModified]

from [dbo].[CRT_Data_8Hours] with (nolock)
	WHERE  [CRTD_PairSymbol] = @PairSymbol
Group By [CRTD_PairSymbol]



ORDER BY 1,2,5


	

select * from [dbo].[CRT_Data_LiveChart] 
WHERE  [CRTD_PairSymbol] = @PairSymbol


/*

-- Checks : 
select * from [YB_Quotes].[dbo].[PairSymbols] with (nolock)
where  [PairSymbol] NOT in (select [CRTD_PairSymbol] collate SQL_Latin1_General_CP1_CI_AS from YB_Charts..[CRT_Data_LiveChart]) 



select [CRTD_PairSymbol],Count(*) 
from  [dbo].[CRT_Data_LiveChart] with (nolock)
Group By [CRTD_PairSymbol]
Having count(*) <> 11
*/



GO
/****** Object:  StoredProcedure [dbo].[USP_CRT_LiveChartProcess]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[USP_CRT_LiveChartProcess]
AS
SET NOCOUNT ON

 declare  @DT_Sec bigint,   @StartDate datetime, @interval int, @RefDate datetime
set @StartDate = getdate()

SET @RefDate = '2015-01-01'
--select getdate()

declare @MaxId bigint

Declare   @Queue table 
(	[Id]				BIGINT Primary Key Clustered ,
	[PairSymbol]		[varchar](50) NOT NULL,
	[Bid]				[float]		NOT NULL,
	[Ask]				[float]		NOT NULL,
	[Mid]				[float]		NOT NULL,
	[BidProviderId]		[tinyint] NOT NULL,
	[AskProviderId]		[tinyint] NOT NULL,
	[BidCreationDate]	[datetime] NOT NULL,
	[AskCreationDate]	[datetime] NOT NULL,
	[BidReceivedDate]	[datetime] NOT NULL,
	[AskReceivedDate]	[datetime] NOT NULL,
	[SavedDate]			[datetime] NOT NULL
)


select @MaxId = Max([Id])
from [YB_Quotes].[dbo].[SpotRatesQueue] with (nolock)

--select @MaxId MaxId

IF @MaxId IS NOT NULL
Begin

	DELETE  [YB_Quotes].[dbo].[SpotRatesQueue]
	OUTPUT	DELETED.[Id], 
			DELETED.[PairSymbol],	
			DELETED.[Bid],				
			DELETED.[Ask],				
			DELETED.[Mid],				
			DELETED.[BidProviderId],	
			DELETED.[AskProviderId],		
			DELETED.[BidCreationDate],	
			DELETED.[AskCreationDate],	
			DELETED.[BidReceivedDate],
			DELETED.[AskReceivedDate],	
			DELETED.[SavedDate]			
		
	INTO @Queue
	WHERE [Id] <= @MaxId

	select
		   [PairSymbol],
		   convert(varchar(16),[BidReceivedDate],121) as [minute],
		   min([Bid]) as  Bid_Low ,  --- Low
		   max([Bid]) as  Bid_High, --- High
		   min([Mid]) as  Mid_Low ,  --- Low
		   max([Mid]) as  Mid_High, --- High
		   Count([Id]) as Cnt
	INTO #c2 
	from @Queue
	where 1=1
	group by convert(varchar(16), [BidReceivedDate] ,121) ,[PairSymbol]


	select
		   [PairSymbol],
		   convert(varchar(16),[BidReceivedDate] ,121) as [minute],
		   [BidReceivedDate] AS [DateQuote],
	    
		   [Bid] AS Bid_Val,
		   [Mid] AS Mid_Val,
		   ROW_NUMBER() over (partition by [PairSymbol],convert(varchar(16),[BidReceivedDate] ,121) order by [BidReceivedDate] ) as Bid_start,
		   ROW_NUMBER() over (partition by [PairSymbol],convert(varchar(16),[BidReceivedDate] ,121) order by [BidReceivedDate] desc) as Bid_end
	INTO #c3 
	from @Queue 
	where 1=1
create index ix_PairSymbol on #c2(PairSymbol)
create index ix_minute on #c2([minute])

create index ix_PairSymbol on #c3(PairSymbol)
create index ix_minute on #c3([minute])
create index ix_Bid_start on #c3(Bid_start)
create index ix_Bid_end on #c3(Bid_end)

	UPDATE [dbo].[CRT_Data_LiveChart]
	   SET [CRTD_Period] =      Case when  A.[CRTD_Period] > [CRT_Data_LiveChart].[CRTD_Period] then A.[CRTD_Period] 
									 else  [CRT_Data_LiveChart].[CRTD_Period] end 
		  ,[CRTD_FirstQuote] =  Case when  A.[CRTD_Period] > [CRT_Data_LiveChart].[CRTD_Period] then A.[CRTD_FirstQuote] 
									 else  [CRT_Data_LiveChart].[CRTD_FirstQuote] end
		  ,[CRTD_LastQuote] =   A.[CRTD_LastQuote]
		  ,[CRTD_BidOpeningValue] = Case when  A.[CRTD_Period] > [CRT_Data_LiveChart].[CRTD_Period] then IsNull([CRTD_BidClosingValue],A.Bid_OpenValue) 
		                                 else [CRTD_BidOpeningValue] end
		  ,[CRTD_BidClosingValue] = A.Bid_CloseValue
		  ,[CRTD_BidLowValue] = Case	when  A.[CRTD_Period] > [CRT_Data_LiveChart].[CRTD_Period] then	 A.Bid_Low
										when  A.Bid_Low < [CRTD_BidLowValue] then A.Bid_Low 
										else [CRTD_BidLowValue] end
		  ,[CRTD_BidHighValue] = Case	when  A.[CRTD_Period] > [CRT_Data_LiveChart].[CRTD_Period] then	 A.Bid_High
										when  A.Bid_High > [CRTD_BidHighValue] then A.Bid_High 
										else [CRTD_BidHighValue] end
		  ,[CRTD_MidOpeningValue] = Case when  A.[CRTD_Period] > [CRT_Data_LiveChart].[CRTD_Period] then  IsNull([CRTD_MidClosingValue],A.Mid_OpenValue) else [CRTD_MidOpeningValue] end
		  ,[CRTD_MidClosingValue] = A.Mid_CloseValue
		  ,[CRTD_MidLowValue] = Case	when  A.[CRTD_Period] > [CRT_Data_LiveChart].[CRTD_Period] then	 A.Mid_Low
										when  A.Mid_Low < [CRTD_MidLowValue] then A.Mid_Low 
										else [CRTD_MidLowValue] end
		  ,[CRTD_MidHighValue] = Case	when  A.[CRTD_Period] > [CRT_Data_LiveChart].[CRTD_Period] then	 A.Mid_High 
										when  A.Mid_High > [CRTD_MidHighValue] then  A.Mid_High      
										else [CRTD_MidHighValue] end
		  ,[CRTD_DateModified] = GetDate()
		  ,[CRTD_Rows] = Case when  A.[CRTD_Period] > [CRT_Data_LiveChart].[CRTD_Period] then IsNull([CRTD_Rows],0) + Cnt 
						 else Cnt end


	From 
	(
	select  '1Minute' AS [Target],
	/* Case when (datediff(second,@RefDate,Cast(convert(char(16), GetDate(),121) as datetime)) /(60*1))*(60*1) =datediff(second,@RefDate,Cast(convert(char(16), GetDate(),121) as datetime)) 
	 then '1Minute'  Else Null End As [Ind], */
	 c2.[minute] [CRTD_Period], 
			c3.[DateQuote] [CRTD_FirstQuote],
			c3_Bid.[DateQuote] [CRTD_LastQuote],
			c2.PairSymbol,
			c3.Bid_Val    as Bid_OpenValue, 
			IsNull(c3_Bid.Bid_Val,0)   as Bid_CloseValue, 
			Bid_Low, 
			Bid_High,
			IsNull(c3.Mid_Val,0)     as Mid_OpenValue, 
			IsNull(c3_Bid.Mid_Val,0)  as Mid_CloseValue, 
			Mid_Low,
			Mid_High,
			GetDate() As Date_Inserted,
			c2.Cnt

	from   #c2 C2
		   Inner join #c3 C3 on c2.[PairSymbol] = c3.[PairSymbol] and c2.[minute] = c3.[minute] and Bid_start =1
		   Inner join #c3 as c3_Bid on c2.[PairSymbol] = c3_Bid.[PairSymbol] and c2.[minute] = c3_Bid.[minute] and c3_Bid.Bid_end =1
	Where 1=1
	UNION
	select  '5Minutes' AS [Target],
	/* Case when (datediff(second,@RefDate,Cast(convert(char(16), GetDate(),121) as datetime)) /(60*5))*(60*5) =datediff(second,@RefDate,Cast(convert(char(16), GetDate(),121) as datetime)) 
	 then '5Minutes'  Else Null End As [Ind], */
	 dateadd(minute, datepart(minute, C2.[minute]) / 5 * 5 - datepart(minute, C2.[minute]), C2.[minute]) [CRTD_Period], 
			c3.[DateQuote] [CRTD_FirstQuote],
			c3_Bid.[DateQuote] [CRTD_LastQuote],
			c2.PairSymbol,
			c3.Bid_Val    as Bid_OpenValue, 
			IsNull(c3_Bid.Bid_Val,0)   as Bid_CloseValue, 
			Bid_Low, 
			Bid_High,
			IsNull(c3.Mid_Val,0)     as Mid_OpenValue, 
			IsNull(c3_Bid.Mid_Val,0)  as Mid_CloseValue, 
			Mid_Low,
			Mid_High,
			GetDate() As Date_Inserted,
			c2.Cnt
	from   #c2 AS c2
		   Inner join #c3  as c3 on c2.[PairSymbol] = c3.[PairSymbol] and c2.[minute] = c3.[minute] and Bid_start =1
		   Inner join #c3 as c3_Bid on c2.[PairSymbol] = c3_Bid.[PairSymbol] and c2.[minute] = c3_Bid.[minute] and c3_Bid.Bid_end =1
	Where 1=1
	UNION
	select  '15Minutes' AS [Target],
	/* Case when (datediff(second,@RefDate,Cast(convert(char(16), GetDate(),121) as datetime)) /(60*15))*(60*15) =datediff(second,@RefDate,Cast(convert(char(16), GetDate(),121) as datetime)) 
	 then '15Minutes'  Else Null End As [Ind], */
	 dateadd(minute, datepart(minute, C2.[minute]) / 15 * 15 - datepart(minute, C2.[minute]), C2.[minute]) [CRTD_Period],  
			c3.[DateQuote] [CRTD_FirstQuote],
			c3_Bid.[DateQuote] [CRTD_LastQuote],
			c2.PairSymbol,
			c3.Bid_Val    as Bid_OpenValue, 
			IsNull(c3_Bid.Bid_Val,0)   as Bid_CloseValue, 
			Bid_Low, 
			Bid_High,
			IsNull(c3.Mid_Val,0)     as Mid_OpenValue, 
			IsNull(c3_Bid.Mid_Val,0)  as Mid_CloseValue, 
			Mid_Low,
			Mid_High,
			GetDate() As Date_Inserted,
			c2.Cnt

	from   #c2 as c2
		   Inner join #c3 as c3 on c2.[PairSymbol] = c3.[PairSymbol] and c2.[minute] = c3.[minute] and Bid_start =1
		   Inner join #c3 as c3_Bid on c2.[PairSymbol] = c3_Bid.[PairSymbol] and c2.[minute] = c3_Bid.[minute] and c3_Bid.Bid_end =1
	Where 1=1
	UNION
	select  '30Minutes' AS [Target],
	/* Case when (datediff(second,@RefDate,Cast(convert(char(16), GetDate(),121) as datetime)) /(60*30))*(60*30) =datediff(second,@RefDate,Cast(convert(char(16), GetDate(),121) as datetime)) 
	 then '30Minutes'  Else Null End As [Ind], */
	 dateadd(minute, datepart(minute, C2.[minute]) / 30 * 30 - datepart(minute, C2.[minute]), C2.[minute]) [CRTD_Period],  
			c3.[DateQuote] [CRTD_FirstQuote],
			c3_Bid.[DateQuote] [CRTD_LastQuote],
			c2.PairSymbol,
			c3.Bid_Val    as Bid_OpenValue, 
			IsNull(c3_Bid.Bid_Val,0)   as Bid_CloseValue, 
			Bid_Low, 
			Bid_High,
			IsNull(c3.Mid_Val,0)     as Mid_OpenValue, 
			IsNull(c3_Bid.Mid_Val,0)  as Mid_CloseValue, 
			Mid_Low,
			Mid_High,
			GetDate() As Date_Inserted,
			c2.Cnt

	from   #c2 as c2
		   Inner join #c3 as c3 on c2.[PairSymbol] = c3.[PairSymbol] and c2.[minute] = c3.[minute] and Bid_start =1
		   Inner join #c3 as c3_Bid on c2.[PairSymbol] = c3_Bid.[PairSymbol] and c2.[minute] = c3_Bid.[minute] and c3_Bid.Bid_end =1
	Where 1=1
	UNION
	select  '1Hour' AS [Target],
	/* Case when (datediff(second,@RefDate,Cast(convert(char(16), GetDate(),121) as datetime)) /(60*60))*(60*60) =datediff(second,@RefDate,Cast(convert(char(16), GetDate(),121) as datetime)) 
	 then '1Hour'  Else Null End As [Ind], */
	 dateadd(minute, datepart(minute, C2.[minute]) / 60 * 60 - datepart(minute, C2.[minute]), C2.[minute]) 
	 [CRTD_Period],  
			c3.[DateQuote] [CRTD_FirstQuote],
			c3_Bid.[DateQuote] [CRTD_LastQuote],
			c2.PairSymbol,
			c3.Bid_Val    as Bid_OpenValue, 
			IsNull(c3_Bid.Bid_Val,0)   as Bid_CloseValue, 
			Bid_Low, 
			Bid_High,
			IsNull(c3.Mid_Val,0)     as Mid_OpenValue, 
			IsNull(c3_Bid.Mid_Val,0)  as Mid_CloseValue, 
			Mid_Low,
			Mid_High,
			GetDate() As Date_Inserted,
			c2.Cnt

	from   #c2 as c2
		   Inner join #c3 as c3 on c2.[PairSymbol] = c3.[PairSymbol] and c2.[minute] = c3.[minute] and Bid_start =1
		   Inner join #c3 as c3_Bid on c2.[PairSymbol] = c3_Bid.[PairSymbol] and c2.[minute] = c3_Bid.[minute] and c3_Bid.Bid_end =1
	Where 1=1
	UNION
	select  '2Hours' AS [Target],
	/* Case when (datediff(second,@RefDate,Cast(convert(char(16), GetDate(),121) as datetime)) /(60*60*2))*(60*60*2) =datediff(second,@RefDate,Cast(convert(char(16), GetDate(),121) as datetime)) 
	 then '2Hours'  Else Null End As [Ind], */
	 --dateadd(minute, datepart(minute, C2.[minute]) / 120 * 120 - datepart(minute, C2.[minute]), C2.[minute]) 
	   dateadd(hour, datepart(hour, dateadd(minute, datepart(minute, C2.[minute]) / 120 * 120 - datepart(minute, C2.[minute]), C2.[minute]) ) / 2 * 2 - datepart(hour, dateadd(minute, datepart(minute, C2.[minute]) / 120 * 120 - datepart(minute, C2.[minute]), C2.[minute]) ), dateadd(minute, datepart(minute, C2.[minute]) / 120 * 120 - datepart(minute, C2.[minute]), C2.[minute]) )
	   [CRTD_Period],  
			c3.[DateQuote] [CRTD_FirstQuote],
			c3_Bid.[DateQuote] [CRTD_LastQuote],
			c2.PairSymbol,
			c3.Bid_Val    as Bid_OpenValue, 
			IsNull(c3_Bid.Bid_Val,0)   as Bid_CloseValue, 
			Bid_Low, 
			Bid_High,
			IsNull(c3.Mid_Val,0)     as Mid_OpenValue, 
			IsNull(c3_Bid.Mid_Val,0)  as Mid_CloseValue, 
			Mid_Low,
			Mid_High,
			GetDate() As Date_Inserted,
			c2.Cnt

	from   #c2 as c2
		   Inner join #c3 as c3 on c2.[PairSymbol] = c3.[PairSymbol] and c2.[minute] = c3.[minute] and Bid_start =1
		   Inner join #c3 as c3_Bid on c2.[PairSymbol] = c3_Bid.[PairSymbol] and c2.[minute] = c3_Bid.[minute] and c3_Bid.Bid_end =1
	Where 1=1
	UNION
	select  '4Hours' AS [Target],
	/* Case when (datediff(second,@RefDate,Cast(convert(char(16), GetDate(),121) as datetime)) /(60*60*4))*(60*60*4) =datediff(second,@RefDate,Cast(convert(char(16), GetDate(),121) as datetime)) 
	 then '4Hours'  Else Null End As [Ind], */
	 --dateadd(minute, datepart(minute, C2.[minute]) / 120 * 120 - datepart(minute, C2.[minute]), C2.[minute]) 
	  dateadd(hour, datepart(hour, dateadd(minute, datepart(minute, C2.[minute]) / 240 * 240 - datepart(minute, C2.[minute]), C2.[minute]) ) / 4 * 4 - datepart(hour, dateadd(minute, datepart(minute, C2.[minute]) / 240 * 240 - datepart(minute, C2.[minute]), C2.[minute]) ), dateadd(minute, datepart(minute, C2.[minute]) / 240 * 240 - datepart(minute, C2.[minute]), C2.[minute]) )
	  [CRTD_Period],  
			c3.[DateQuote] [CRTD_FirstQuote],
			c3_Bid.[DateQuote] [CRTD_LastQuote],
			c2.PairSymbol,
			c3.Bid_Val    as Bid_OpenValue, 
			IsNull(c3_Bid.Bid_Val,0)   as Bid_CloseValue, 
			Bid_Low, 
			Bid_High,
			IsNull(c3.Mid_Val,0)     as Mid_OpenValue, 
			IsNull(c3_Bid.Mid_Val,0)  as Mid_CloseValue, 
			Mid_Low,
			Mid_High,
			GetDate() As Date_Inserted,
			c2.Cnt

	from   #c2 as c2
		   Inner join #c3 as c3 on c2.[PairSymbol] = c3.[PairSymbol] and c2.[minute] = c3.[minute] and Bid_start =1
		   Inner join #c3 as c3_Bid on c2.[PairSymbol] = c3_Bid.[PairSymbol] and c2.[minute] = c3_Bid.[minute] and c3_Bid.Bid_end =1
	Where 1=1
	UNION
	select  '8Hours' AS [Target],
	/* Case when (datediff(second,@RefDate,Cast(convert(char(16), GetDate(),121) as datetime)) /(60*60*8))*(60*60*8) =datediff(second,@RefDate,Cast(convert(char(16), GetDate(),121) as datetime)) 
	 then '8Hours'  Else Null End As [Ind], */
	 --dateadd(minute, datepart(minute, C2.[minute]) / 120 * 120 - datepart(minute, C2.[minute]), C2.[minute]) 
	  dateadd(hour, datepart(hour, dateadd(minute, datepart(minute, C2.[minute]) / 480 * 480 - datepart(minute, C2.[minute]), C2.[minute]) ) / 8 * 8 - datepart(hour, dateadd(minute, datepart(minute, C2.[minute]) / 480 * 480 - datepart(minute, C2.[minute]), C2.[minute]) ), dateadd(minute, datepart(minute, C2.[minute]) / 480 * 480 - datepart(minute, C2.[minute]), C2.[minute]) )
	  [CRTD_Period],  
			c3.[DateQuote] [CRTD_FirstQuote],
			c3_Bid.[DateQuote] [CRTD_LastQuote],
			c2.PairSymbol,
			c3.Bid_Val    as Bid_OpenValue, 
			IsNull(c3_Bid.Bid_Val,0)   as Bid_CloseValue, 
			Bid_Low, 
			Bid_High,
			IsNull(c3.Mid_Val,0)     as Mid_OpenValue, 
			IsNull(c3_Bid.Mid_Val,0)  as Mid_CloseValue, 
			Mid_Low,
			Mid_High,
			GetDate() As Date_Inserted,
			c2.Cnt
	from   #c2 as c2
		   Inner join #c3 as c3 on c2.[PairSymbol] = c3.[PairSymbol] and c2.[minute] = c3.[minute] and Bid_start =1
		   Inner join #c3 as c3_Bid on c2.[PairSymbol] = c3_Bid.[PairSymbol] and c2.[minute] = c3_Bid.[minute] and c3_Bid.Bid_end =1
	Where 1=1
	UNION
	select  '1Week' AS [Target],
	/* Case when dateadd(day, -datepart(weekday, Cast(Convert(char(10),c2.[minute],121) as datetime))+1 , Cast(Convert(char(10),c2.[minute],121) as datetime)) 
			= dateadd(day, -datepart(weekday, Cast(Convert(char(10),GetDate(),121) as datetime))+1 , Cast(Convert(char(10),GetDate(),121) as datetime))
	 then '1Week'  Else Null End As [Ind], */
	 dateadd(day, -datepart(weekday, Cast(Convert(char(10),c2.[minute],121) as datetime))+1 , Cast(Convert(char(10),c2.[minute],121) as datetime))
	 [CRTD_Period], 
			c3.[DateQuote] [CRTD_FirstQuote],
			c3_Bid.[DateQuote] [CRTD_LastQuote],
			c2.PairSymbol,
			c3.Bid_Val    as Bid_OpenValue, 
			IsNull(c3_Bid.Bid_Val,0)   as Bid_CloseValue, 
			Bid_Low, 
			Bid_High,
			IsNull(c3.Mid_Val,0)     as Mid_OpenValue, 
			IsNull(c3_Bid.Mid_Val,0)  as Mid_CloseValue, 
			Mid_Low,
			Mid_High,
			GetDate() As Date_Inserted,
			c2.Cnt
	from   #c2 as c2
		   Inner join #c3 as c3 on c2.[PairSymbol] = c3.[PairSymbol] and c2.[minute] = c3.[minute] and Bid_start =1
		   Inner join #c3 as c3_Bid on c2.[PairSymbol] = c3_Bid.[PairSymbol] and c2.[minute] = c3_Bid.[minute] and c3_Bid.Bid_end =1
	Where 1=1
	UNION
	select  '1Day' AS [Target],
	/* Case when Cast(Convert(char(10),c2.[minute],121) as datetime)  = Cast(Convert(char(10),GetDate(),121) as datetime) 
	 then '1Day'  Else Null End As [Ind], */
	 Cast(Convert(char(10),c2.[minute],121) as datetime)  [CRTD_Period], 
			c3.[DateQuote] [CRTD_FirstQuote],
			c3_Bid.[DateQuote] [CRTD_LastQuote],
			c2.PairSymbol,
			c3.Bid_Val    as Bid_OpenValue, 
			IsNull(c3_Bid.Bid_Val,0)   as Bid_CloseValue, 
			Bid_Low, 
			Bid_High,
			IsNull(c3.Mid_Val,0)     as Mid_OpenValue, 
			IsNull(c3_Bid.Mid_Val,0)  as Mid_CloseValue, 
			Mid_Low,
			Mid_High,
			GetDate() As Date_Inserted,
			c2.Cnt
	from   #c2 as c2
		   Inner join #c3 as c3  on c2.[PairSymbol] = c3.[PairSymbol] and c2.[minute] = c3.[minute] and Bid_start =1
		   Inner join #c3 as c3_Bid on c2.[PairSymbol] = c3_Bid.[PairSymbol] and c2.[minute] = c3_Bid.[minute] and c3_Bid.Bid_end =1
	Where 1=1
	UNION
	---select dateadd(day,-datepart(day,getdate())+1,Cast(Convert(char(10),GetDate(),121) as datetime) )
	---select dateadd(day,-datepart(day,c2.[minute])+1,Cast(Convert(char(10),c2.[minute],121) as datetime) )
	select  '1Month' AS [Target],
	/* Case when dateadd(day,-datepart(day,c2.[minute])+1,Cast(Convert(char(10),c2.[minute],121) as datetime) ) = Cast(Convert(char(10),GetDate(),121) as datetime) 
	 then '1Month'  Else Null End As [Ind], */
		dateadd(day,-datepart(day,c2.[minute])+1,Cast(Convert(char(10),c2.[minute],121) as datetime) ) [CRTD_Period], 
			c3.[DateQuote] [CRTD_FirstQuote],
			c3_Bid.[DateQuote] [CRTD_LastQuote],
			c2.PairSymbol,
			c3.Bid_Val    as Bid_OpenValue, 
			IsNull(c3_Bid.Bid_Val,0)   as Bid_CloseValue, 
			Bid_Low, 
			Bid_High,
			IsNull(c3.Mid_Val,0)     as Mid_OpenValue, 
			IsNull(c3_Bid.Mid_Val,0)  as Mid_CloseValue, 
			Mid_Low,
			Mid_High,
			GetDate() As Date_Inserted,
			c2.Cnt
	from   #c2 as c2
		   Inner join #c3  as c3 on c2.[PairSymbol] = c3.[PairSymbol] and c2.[minute] = c3.[minute] and Bid_start =1
		   Inner join #c3 as c3_Bid on c2.[PairSymbol] = c3_Bid.[PairSymbol] and c2.[minute] = c3_Bid.[minute] and c3_Bid.Bid_end =1
	Where 1=1
	) AS A
	Where [CRTD_TargetName] = A.[Target] collate SQL_Latin1_General_CP1_CI_AS
	And [CRTD_PairSymbol] = A.PairSymbol collate SQL_Latin1_General_CP1_CI_AS
	--and  PairSymbol = 'AUDUSD'
	--and Target = '1Minute'
	drop table #c2
	drop table #c3
End


--	select datediff(ms,@StartDate,getdate()) TimeToProcess

	---- select * from [dbo].[CRT_Data_LiveChart] where [CRTD_PairSymbol] = 'AUDUSD' AND [CRTD_TargetName] = '1Minute'




GO
/****** Object:  StoredProcedure [dbo].[USP_StudyTemplate_AddOrUpdate]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[USP_StudyTemplate_AddOrUpdate]
	@client VARCHAR(100),
	@user VARCHAR(300),
	@templateName VARCHAR(300),
	@content TEXT
AS
	
	MERGE [StudyTemplate] as st
	USING (VALUES(@client,@user,@templateName,@content)) as s ([Client], [User], [TemplateName], [Content])
	ON st.[Client]=s.[Client] AND st.[User] = s.[User] AND st.[TemplateName] = s.[TemplateName]
	WHEN MATCHED
		THEN UPDATE SET [Content] = s.[Content]
	WHEN NOT MATCHED THEN 
		INSERT ([Client], [User], [TemplateName], [Content])
		VALUES(@client, @user, @templateName, @content) 
	;


RETURN 0

GO
/****** Object:  StoredProcedure [dbo].[USP_StudyTemplate_Delete]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[USP_StudyTemplate_Delete]
	@client VARCHAR(100),
	@user VARCHAR(300),
	@templateName VARCHAR(300)
AS
	DELETE FROM [StudyTemplate]
	WHERE [Client]=@client AND [User] = @user AND [TemplateName] = @templateName
RETURN 0

GO
/****** Object:  StoredProcedure [dbo].[USP_StudyTemplate_GetNames]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[USP_StudyTemplate_GetNames]
	@client VARCHAR(100),
	@user VARCHAR(300)
AS
	SELECT [TemplateName]
	FROM [StudyTemplate]
	WHERE [Client]=@client AND [User]=@user

RETURN 0

GO
/****** Object:  StoredProcedure [dbo].[USP_StudyTemplate_GetStudy]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[USP_StudyTemplate_GetStudy]
	@client VARCHAR(100),
	@user VARCHAR(300),
	@templateName VARCHAR(300)
AS
	SELECT [TemplateName], [Content]
	FROM [StudyTemplate]
	WHERE [Client]=@client AND [User]=@user AND [TemplateName]=@templateName
RETURN 0

GO
/****** Object:  StoredProcedure [dbo].[USP_UTIL_CRT_ReAggDay]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec USP_UTIL_CRT_Validation '2016-06-03'
CREATE procedure [dbo].[USP_UTIL_CRT_ReAggDay]
(@checkDay datetime)
as
declare @TableName	sysname,@UnitDefinition varchar(15),@TimeUnit varchar(10),@TimeInterval varchar(10),@sql nvarchar(max),@minLastRun datetime,@Source_TableName sysname

create table #temp (CRTD_ID int,
					CRTD_Period datetime,
					CRTD_FirstQuote datetime,
					CRTD_LastQuote  datetime,
					CRTD_PairSymbol varchar(15),
					CRTD_BidOpeningValue float ,
					CRTD_BidClosingValue float ,
					CRTD_BidLowValue float ,
					CRTD_BidHighValue float ,
					CRTD_MidOpeningValue float ,
					CRTD_MidClosingValue float ,
					CRTD_MidLowValue float ,
					CRTD_MidHighValue float,
					StartIntervalDate datetime,
					EndIntervalDate datetime)

create index ix_StartIntervalDate on #temp(StartIntervalDate) 

create table #temp1 (StartPeriod datetime,
					EndPeriod datetime,
					First_Quote datetime,
					Last_Quote datetime,
					CRTD_PairSymbol varchar(15),
					BidMin_Value float,
					BidMax_Value float,
					MidMin_Value float,
					MidMax_Value float,
					Min_RowId int,
					Max_RowId int,
					BidOpen_Value float,
					BidClose_Value float,
					MidOpen_Value float,
					MidClose_Value float   )	


declare cTasks cursor local static for
	select CRTT_TableName, CRTT_UnitDefinition
	from CRT_tasks with (nolock)
	where CRTT_Name <> '1Minute'
	and CRTT_IsActive = 1 and CRTT_Source_TableName <> '' 
	order by CRTT_ID
open cTasks
fetch next from cTasks into @TableName, @UnitDefinition
while @@fetch_status = 0
	begin	
			truncate table #temp
			truncate table #temp1
			set @TimeUnit=substring(@UnitDefinition,1,1)
			set @TimeInterval=substring(@UnitDefinition,2,4)
			SELECT @TimeUnit=CASE @TimeUnit when 'N' then 'minute'
											when 'H' then 'hour'
											when 'D' then 'day'
											when 'W' then 'Week'
											when 'M' then 'Month'		
							  end											
		set @SQL = 
		'insert into #temp(CRTD_Period,CRTD_FirstQuote,CRTD_LastQuote,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_BidClosingValue,CRTD_BidLowValue,CRTD_BidHighValue,CRTD_MidOpeningValue,
						   CRTD_MidClosingValue,CRTD_MidLowValue,CRTD_MidHighValue,StartIntervalDate,EndIntervalDate)
		SELECT CRTD_Period ,CRTD_FirstQuote ,CRTD_LastQuote ,CRTD_PairSymbol ,CRTD_BidOpeningValue ,CRTD_BidClosingValue  
	          ,CRTD_BidLowValue ,CRTD_BidHighValue ,CRTD_MidOpeningValue ,CRTD_MidClosingValue ,CRTD_MidLowValue ,CRTD_MidHighValue,
			  	  dateadd('+@TimeUnit+', datediff('+@TimeUnit+',0,CRTD_Period) /'+ @TimeInterval+' * '+@TimeInterval+', 0) as StartIntervalDate,
			  dateadd(millisecond,-3,dateadd('+@TimeUnit+','+@TimeInterval+', (dateadd('+@TimeUnit+', datediff('+@TimeUnit+',0,CRTD_Period) / '+@TimeInterval+' * '+@TimeInterval+', 0)))) as EndIntervalDate
		from  YB_Charts.dbo.CRT_Data_1Minute (nolock)
		where CRTD_Period BETWEEN CAST(@checkDay AS DATE) AND CAST(dateadd(millisecond,-3,@checkDay+1) AS DATEtIME)'
		exec sp_executesql @SQL,N'@checkDay datetime ',@checkDay 				
		if @TimeUnit='Week'--change so the week will be from sunday to saturday
			begin
				UPDATE #temp
				SET StartIntervalDate=StartIntervalDate-1,
					EndIntervalDate=EndIntervalDate-1
			end				
		insert into #temp1
				(StartPeriod, EndPeriod, First_Quote, Last_Quote, CRTD_PairSymbol, BidMin_Value, BidMax_Value, MidMin_Value, MidMax_Value)			
		select  StartIntervalDate,
				EndIntervalDate,
				min(CRTD_FirstQuote) First_Quote, max(CRTD_LastQuote) Last_Quote, 
				A.CRTD_PairSymbol,
				min(CRTD_BidLowValue) BidMin_Value, max(CRTD_BidHighValue) BidMax_Value, 
				min(CRTD_MidLowValue) MidMin_Value, max(CRTD_MidHighValue) MidMax_Value			 
		from #temp A
		group by StartIntervalDate,EndIntervalDate,A.CRTD_PairSymbol
				
		update A
		set BidOpen_Value = B.CRTD_BidOpeningValue,
			MidOpen_Value = B.CRTD_MidOpeningValue
		FROM #temp1 A
			INNER JOIN (select StartIntervalDate,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_MidOpeningValue,ROW_NUMBER() over (partition by CRTD_PairSymbol,StartIntervalDate order by crtd_period) as rownum
						from #temp) B ON A.CRTD_PairSymbol = B.CRTD_PairSymbol and A.StartPeriod=B.StartIntervalDate
		where B.rownum=1

		update A
		set BidClose_Value = B.CRTD_BidClosingValue,
			MidClose_Value = B.CRTD_MidClosingValue
		FROM #temp1 A
			INNER JOIN (select StartIntervalDate,CRTD_PairSymbol,CRTD_BidClosingValue,CRTD_MidClosingValue,ROW_NUMBER() over (partition by CRTD_PairSymbol,StartIntervalDate order by crtd_period desc) as rownum
						from #temp) B ON A.CRTD_PairSymbol = B.CRTD_PairSymbol and A.StartPeriod=B.StartIntervalDate
		where B.rownum=1

		set @SQL = 
				'delete from ' + quotename(@TableName) + 
				' where CRTD_Period BETWEEN CAST(@checkDay AS DATE) AND CAST(dateadd(millisecond,-3,@checkDay+1) AS DATEtIME)'
		exec sp_executesql @SQL,N'@checkDay datetime ',@checkDay 				
		
		set @SQL = 
				'insert into ' + quotename(@TableName) + 
				'(CRTD_Period, CRTD_FirstQuote, CRTD_LastQuote, CRTD_PairSymbol,
					CRTD_BidOpeningValue, CRTD_BidClosingValue, CRTD_BidLowValue,CRTD_BidHighValue,
					CRTD_MidOpeningValue, CRTD_MidClosingValue, CRTD_MidLowValue,CRTD_MidHighValue)
				select StartPeriod, First_Quote, Last_Quote, A.CRTD_PairSymbol, BidOpen_Value, BidClose_Value, BidMin_Value, BidMax_Value,
						MidOpen_Value, MidClose_Value, MidMin_Value, MidMax_Value
				from #temp1 A'					
		exec(@SQL)			
	fetch next from cTasks into @TableName, @UnitDefinition

	end
close cTasks
deallocate cTasks

drop table #temp
drop table #temp1

GO
/****** Object:  StoredProcedure [dbo].[USP_UTIL_CRT_Validation]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec USP_UTIL_CRT_Validation '2016-12-12'
CREATE procedure [dbo].[USP_UTIL_CRT_Validation]
(@checkDay datetime,@fixMismatch bit=0)
as
declare @TableName	sysname,@UnitDefinition varchar(15),@TimeUnit varchar(10),@TimeInterval varchar(10),@sql nvarchar(max),@minLastRun datetime,@mismatchfound bit

create table #temp (CRTD_ID int,
					CRTD_Period datetime,
					CRTD_FirstQuote datetime,
					CRTD_LastQuote  datetime,
					CRTD_PairSymbol varchar(15),
					CRTD_BidOpeningValue float ,
					CRTD_BidClosingValue float ,
					CRTD_BidLowValue float ,
					CRTD_BidHighValue float ,
					CRTD_MidOpeningValue float ,
					CRTD_MidClosingValue float ,
					CRTD_MidLowValue float ,
					CRTD_MidHighValue float,
					StartIntervalDate datetime,
					EndIntervalDate datetime)

create index ix_StartIntervalDate on #temp(StartIntervalDate) 

create table #temp1 (StartPeriod datetime,
					EndPeriod datetime,
					First_Quote datetime,
					Last_Quote datetime,
					CRTD_PairSymbol varchar(15),
					BidMin_Value float,
					BidMax_Value float,
					MidMin_Value float,
					MidMax_Value float,
					Min_RowId int,
					Max_RowId int,
					BidOpen_Value float,
					BidClose_Value float,
					MidOpen_Value float,
					MidClose_Value float   )	

create table #MismatchRecords 
(CRTD_Period datetime,
CRTD_FirstQuote datetime,
CRTD_LastQuote datetime ,
CRTD_PairSymbol varchar(15),
CRTD_BidOpeningValue float,
CRTD_BidClosingValue float,
CRTD_BidLowValue float,
CRTD_BidHighValue float,
CRTD_MidOpeningValue float,
CRTD_MidClosingValue float,
CRTD_MidLowValue float,
CRTD_MidHighValue float)

SELECT CRTD_PairSymbol ,max([CRTD_LastQuote]) as max_LastQuote
into   #LastQuote
from  [YB_Charts].[dbo].[CRT_Data_1Minute](nolock)
where CRTD_Period>getdate()-7
group by CRTD_PairSymbol 


select  CRTT_TableName, CRTT_UnitDefinition
into #TablesToCheck
from CRT_tasks with (nolock)
where CRTT_Name <> '1Minute'
and CRTT_IsActive = 1 and CRTT_Source_TableName <> ''
order by crtt_id


if datepart(weekday,@checkDay)<>1
	delete from #TablesToCheck where CRTT_TableName='CRT_Data_1Week'

if datepart(day,@checkDay)<>1
	delete from #TablesToCheck where CRTT_TableName='CRT_Data_1Month'

declare cTasks cursor local static for
	select  CRTT_TableName, CRTT_UnitDefinition
	from #TablesToCheck
--where CRTT_TableName = 'CRT_Data_1Month'
open cTasks
fetch next from cTasks into @TableName, @UnitDefinition
while @@fetch_status = 0
	begin	
			set @mismatchfound=0
			truncate table #temp
			truncate table #temp1
			truncate table #MismatchRecords 
			set @TimeUnit=substring(@UnitDefinition,1,1)
			set @TimeInterval=substring(@UnitDefinition,2,4)
			SELECT @TimeUnit=CASE @TimeUnit when 'N' then 'minute'
											when 'H' then 'hour'
											when 'D' then 'day'
											when 'W' then 'Week'
											when 'M' then 'Month'		
							  end											
		set @SQL = 
		'insert into #temp(CRTD_Period,CRTD_FirstQuote,CRTD_LastQuote,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_BidClosingValue,CRTD_BidLowValue,CRTD_BidHighValue,CRTD_MidOpeningValue,
							CRTD_MidClosingValue,CRTD_MidLowValue,CRTD_MidHighValue,StartIntervalDate,EndIntervalDate)
		SELECT CRTD_Period ,CRTD_FirstQuote ,CRTD_LastQuote ,CRTD_PairSymbol ,CRTD_BidOpeningValue ,CRTD_BidClosingValue  
				,CRTD_BidLowValue ,CRTD_BidHighValue ,CRTD_MidOpeningValue ,CRTD_MidClosingValue ,CRTD_MidLowValue ,CRTD_MidHighValue,
			  		dateadd('+@TimeUnit+', datediff('+@TimeUnit+',0,CRTD_Period) /'+ @TimeInterval+' * '+@TimeInterval+', 0) as StartIntervalDate,
				dateadd(millisecond,-3,dateadd('+@TimeUnit+','+@TimeInterval+', (dateadd('+@TimeUnit+', datediff('+@TimeUnit+',0,CRTD_Period) / '+@TimeInterval+' * '+@TimeInterval+', 0)))) as EndIntervalDate
		from  YB_Charts.dbo.CRT_Data_1Minute (nolock)'
		
		if @TimeUnit in ('minute','hour')
			set @SQL = @SQL +' where CRTD_Period BETWEEN CAST(@checkDay AS DATE) AND dateadd(ms,-3,@checkDay+1)'
		else if @TimeUnit ='Week'
			begin
				set @SQL = @SQL +' where dateadd('+@TimeUnit+', datediff('+@TimeUnit+',0,CRTD_Period) /'+ @TimeInterval+' * '+@TimeInterval+', 0)-1 =CAST(@checkDay AS DATE)
				and CRTD_Period BETWEEN CAST(@checkDay AS DATE) and CAST(@checkDay+6 AS DATE)'
				set @SQL=replace(@SQL,'as StartIntervalDate','-1 as StartIntervalDate')
				set @SQL=replace(@SQL,'as EndIntervalDate','-1 as EndIntervalDate')
			end
		else		
			set @SQL = @SQL +' where dateadd('+@TimeUnit+', datediff('+@TimeUnit+',0,CRTD_Period) /'+ @TimeInterval+' * '+@TimeInterval+', 0) =CAST(@checkDay AS DATE)'
--print @sql
		exec sp_executesql @SQL,N'@checkDay datetime ',@checkDay 				
		
		insert into #temp1
				(StartPeriod, EndPeriod, First_Quote, Last_Quote, CRTD_PairSymbol, BidMin_Value, BidMax_Value, MidMin_Value, MidMax_Value)			
		select  StartIntervalDate,
				EndIntervalDate,
				min(CRTD_FirstQuote) First_Quote, max(CRTD_LastQuote) Last_Quote, 
				A.CRTD_PairSymbol,
				min(CRTD_BidLowValue) BidMin_Value, max(CRTD_BidHighValue) BidMax_Value, 
				min(CRTD_MidLowValue) MidMin_Value, max(CRTD_MidHighValue) MidMax_Value			 
		from #temp A
			inner join #LastQuote B on A.CRTD_PairSymbol=B.CRTD_PairSymbol 
		where A.EndIntervalDate<=B.max_LastQuote
		group by StartIntervalDate,EndIntervalDate,A.CRTD_PairSymbol
				
		update A
		set BidOpen_Value = B.CRTD_BidOpeningValue,
			MidOpen_Value = B.CRTD_MidOpeningValue
		FROM #temp1 A
			INNER JOIN (select StartIntervalDate,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_MidOpeningValue,ROW_NUMBER() over (partition by CRTD_PairSymbol,StartIntervalDate order by crtd_period) as rownum
						from #temp) B ON A.CRTD_PairSymbol = B.CRTD_PairSymbol and A.StartPeriod=B.StartIntervalDate
		where B.rownum=1

		update A
		set BidClose_Value = B.CRTD_BidClosingValue,
			MidClose_Value = B.CRTD_MidClosingValue
		FROM #temp1 A
			INNER JOIN (select StartIntervalDate,CRTD_PairSymbol,CRTD_BidClosingValue,CRTD_MidClosingValue,ROW_NUMBER() over (partition by CRTD_PairSymbol,StartIntervalDate order by crtd_period desc) as rownum
						from #temp) B ON A.CRTD_PairSymbol = B.CRTD_PairSymbol and A.StartPeriod=B.StartIntervalDate
		where B.rownum=1

		set @sql='insert into #MismatchRecords 
			(CRTD_Period,CRTD_FirstQuote,CRTD_LastQuote,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_BidClosingValue,CRTD_BidLowValue,CRTD_BidHighValue,
			 CRTD_MidOpeningValue,CRTD_MidClosingValue,CRTD_MidLowValue,CRTD_MidHighValue)
		select StartPeriod, First_Quote, Last_Quote, CRTD_PairSymbol, BidOpen_Value, BidClose_Value, BidMin_Value, BidMax_Value,
		  	   MidOpen_Value, MidClose_Value, MidMin_Value, MidMax_Value
		from #temp1 
		except
		select CRTD_Period,CRTD_FirstQuote,CRTD_LastQuote,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_BidClosingValue,CRTD_BidLowValue,CRTD_BidHighValue,
			 CRTD_MidOpeningValue,CRTD_MidClosingValue,CRTD_MidLowValue,CRTD_MidHighValue
		from '+@TableName+' where CRTD_Period BETWEEN CAST(@checkDay AS DATE) AND CAST(dateadd(millisecond,-3,@checkDay+1) AS DATEtIME)'		
		exec sp_executesql @SQL,N'@checkDay datetime ',@checkDay 

		if @@rowcount>0
			begin
				select 'There is mismatch in table '+@TableName+' at '+Convert(varchar(10),@checkDay,120)+'. Here are the mismatched records:'
				set @sql='select * from
						  (select ''Calculated'' as Source,CRTD_Period,CRTD_FirstQuote,CRTD_LastQuote,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_BidClosingValue,CRTD_BidLowValue,CRTD_BidHighValue,
								   CRTD_MidOpeningValue,CRTD_MidClosingValue,CRTD_MidLowValue,CRTD_MidHighValue
						  from #MismatchRecords 
						  union all
						  select ''Saved'' as Source,CRTD_Period,CRTD_FirstQuote,CRTD_LastQuote,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_BidClosingValue,CRTD_BidLowValue,CRTD_BidHighValue,
								   CRTD_MidOpeningValue,CRTD_MidClosingValue,CRTD_MidLowValue,CRTD_MidHighValue
						  from '+@TableName+' A
						  where CRTD_Period BETWEEN CAST(@checkDay AS DATE) AND CAST(dateadd(millisecond,-3,@checkDay+1) AS DATEtIME)
						  and exists(select 1 from #MismatchRecords B where A.CRTD_Period=B.CRTD_Period and A.CRTD_PairSymbol=B.CRTD_PairSymbol))s
						  order by CRTD_Period,CRTD_PairSymbol,Source'
				exec sp_executesql @SQL,N'@checkDay datetime ',@checkDay 
				set @mismatchfound=1
			end
		else
			begin
				set @sql='insert into #MismatchRecords 
					(CRTD_Period,CRTD_FirstQuote,CRTD_LastQuote,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_BidClosingValue,CRTD_BidLowValue,CRTD_BidHighValue,
					 CRTD_MidOpeningValue,CRTD_MidClosingValue,CRTD_MidLowValue,CRTD_MidHighValue)
				select CRTD_Period,CRTD_FirstQuote,CRTD_LastQuote,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_BidClosingValue,CRTD_BidLowValue,CRTD_BidHighValue,
					 CRTD_MidOpeningValue,CRTD_MidClosingValue,CRTD_MidLowValue,CRTD_MidHighValue
				from '+@TableName+' 
				where CRTD_Period BETWEEN CAST(@checkDay AS DATE) AND CAST(dateadd(millisecond,-3,@checkDay+1) AS DATEtIME)
				except
				select StartPeriod, First_Quote, Last_Quote, CRTD_PairSymbol, BidOpen_Value, BidClose_Value, BidMin_Value, BidMax_Value,
		  			   MidOpen_Value, MidClose_Value, MidMin_Value, MidMax_Value
				from #temp1'
				exec sp_executesql @SQL,N'@checkDay datetime ',@checkDay 
				if @@rowcount>0
					begin
						select 'There is mismatch in table '+@TableName+' at '+Convert(varchar(10),@checkDay,120)+'. Here are the mismatched records:'
						select * from
							  (select 'Saved' as Source,CRTD_Period,CRTD_FirstQuote,CRTD_LastQuote,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_BidClosingValue,CRTD_BidLowValue,CRTD_BidHighValue,
										CRTD_MidOpeningValue,CRTD_MidClosingValue,CRTD_MidLowValue,CRTD_MidHighValue
							  from #MismatchRecords 
							  union all
							  select 'Calculated' as Source,StartPeriod, First_Quote, Last_Quote, CRTD_PairSymbol, BidMin_Value, BidMax_Value, MidMin_Value, MidMax_Value,
									  MidOpen_Value, MidClose_Value,BidOpen_Value, BidClose_Value
							  from #temp1 A
							  where exists(select 1 from #MismatchRecords B where A.StartPeriod=B.CRTD_Period and A.CRTD_PairSymbol=B.CRTD_PairSymbol))s
							  order by CRTD_Period,CRTD_PairSymbol,Source				
							  set @mismatchfound=1
					end 		
				else 
					select 'There are no mismatches in '+@TableName
			end
			if @mismatchfound=1 and @fixMismatch=1
				begin
					set @sql='delete from A
								from '+@TableName+' A
									inner join #MismatchRecords B on A.CRTD_Period=b.CRTD_Period and A.CRTD_PairSymbol=B.CRTD_PairSymbol'
					exec(@sql)
					set @sql='insert into '+@TableName+' 
										(CRTD_Period,CRTD_FirstQuote,CRTD_LastQuote,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_BidClosingValue,CRTD_BidLowValue,CRTD_BidHighValue,
										 CRTD_MidOpeningValue,CRTD_MidClosingValue,CRTD_MidLowValue,CRTD_MidHighValue)
							  select StartPeriod, First_Quote, Last_Quote, A.CRTD_PairSymbol, BidOpen_Value, BidClose_Value, BidMin_Value, BidMax_Value,
		  							 MidOpen_Value, MidClose_Value, MidMin_Value, MidMax_Value
							from #temp1 A								
									inner join #MismatchRecords B on A.StartPeriod=b.CRTD_Period and A.CRTD_PairSymbol=B.CRTD_PairSymbol'
					exec(@sql)
				end
		fetch next from cTasks into @TableName, @UnitDefinition

	end
close cTasks
deallocate cTasks

drop table #temp
drop table #temp1
drop table #MismatchRecords
drop table #LastQuote
drop table #TablesToCheck
GO
/****** Object:  StoredProcedure [dbo].[USP_UTIL_CRT_Validation_5min]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec USP_UTIL_CRT_Validation_5min '2016-12-13'
CREATE procedure [dbo].[USP_UTIL_CRT_Validation_5min]
(@checkDay datetime)
as
set nocount on
declare @TableName	sysname,@UnitDefinition varchar(15),@TimeUnit varchar(10),@TimeInterval varchar(10),@sql nvarchar(max),@minLastRun datetime
create table #temp (CRTD_ID int,
					CRTD_Period datetime,
					CRTD_FirstQuote datetime,
					CRTD_LastQuote  datetime,
					CRTD_PairSymbol varchar(15),
					CRTD_BidOpeningValue float ,
					CRTD_BidClosingValue float ,
					CRTD_BidLowValue float ,
					CRTD_BidHighValue float ,
					CRTD_MidOpeningValue float ,
					CRTD_MidClosingValue float ,
					CRTD_MidLowValue float ,
					CRTD_MidHighValue float,
					StartIntervalDate datetime,
					EndIntervalDate datetime)

create index ix_StartIntervalDate on #temp(StartIntervalDate) 

create table #temp1 (StartPeriod datetime,
					EndPeriod datetime,
					First_Quote datetime,
					Last_Quote datetime,
					CRTD_PairSymbol varchar(15),
					BidMin_Value float,
					BidMax_Value float,
					MidMin_Value float,
					MidMax_Value float,
					Min_RowId int,
					Max_RowId int,
					BidOpen_Value float,
					BidClose_Value float,
					MidOpen_Value float,
					MidClose_Value float   )	

create table #MismatchRecords 
(CRTD_Period datetime,
CRTD_FirstQuote datetime,
CRTD_LastQuote datetime ,
CRTD_PairSymbol varchar(15),
CRTD_BidOpeningValue float,
CRTD_BidClosingValue float,
CRTD_BidLowValue float,
CRTD_BidHighValue float,
CRTD_MidOpeningValue float,
CRTD_MidClosingValue float,
CRTD_MidLowValue float,
CRTD_MidHighValue float)

SELECT CRTD_PairSymbol ,max([CRTD_LastQuote]) as max_LastQuote
into   #LastQuote
from  [YB_Charts].[dbo].[CRT_Data_1Minute](nolock)
group by CRTD_PairSymbol 
	
insert into #temp(CRTD_Period,CRTD_FirstQuote,CRTD_LastQuote,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_BidClosingValue,CRTD_BidLowValue,CRTD_BidHighValue,CRTD_MidOpeningValue,
					CRTD_MidClosingValue,CRTD_MidLowValue,CRTD_MidHighValue,StartIntervalDate,EndIntervalDate)
SELECT CRTD_Period ,CRTD_FirstQuote ,CRTD_LastQuote ,CRTD_PairSymbol ,CRTD_BidOpeningValue ,CRTD_BidClosingValue  
	    ,CRTD_BidLowValue ,CRTD_BidHighValue ,CRTD_MidOpeningValue ,CRTD_MidClosingValue ,CRTD_MidLowValue ,CRTD_MidHighValue,
			dateadd(minute, datediff(minute,0,CRTD_Period) /5 * 5, 0) as StartIntervalDate,
		dateadd(millisecond,-3,dateadd(minute,5, (dateadd(minute, datediff(minute,0,CRTD_Period) / 5* 5, 0)))) as EndIntervalDate
from  YB_Charts.dbo.CRT_Data_1Minute (nolock)
where CRTD_Period BETWEEN CAST(@checkDay AS DATE) AND CAST(dateadd(millisecond,-3,@checkDay+1) AS DATEtIME)

insert into #temp1
		(StartPeriod, EndPeriod, First_Quote, Last_Quote, CRTD_PairSymbol, BidMin_Value, BidMax_Value, MidMin_Value, MidMax_Value)			
select  StartIntervalDate,
		EndIntervalDate,
		min(CRTD_FirstQuote) First_Quote, max(CRTD_LastQuote) Last_Quote, 
		A.CRTD_PairSymbol,
		min(CRTD_BidLowValue) BidMin_Value, max(CRTD_BidHighValue) BidMax_Value, 
		min(CRTD_MidLowValue) MidMin_Value, max(CRTD_MidHighValue) MidMax_Value			 
from #temp A
	inner join #LastQuote B on A.CRTD_PairSymbol=B.CRTD_PairSymbol 
where A.EndIntervalDate<=B.max_LastQuote
group by StartIntervalDate,EndIntervalDate,A.CRTD_PairSymbol
				
update A
set BidOpen_Value = B.CRTD_BidOpeningValue,
	MidOpen_Value = B.CRTD_MidOpeningValue
FROM #temp1 A
	INNER JOIN (select StartIntervalDate,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_MidOpeningValue,ROW_NUMBER() over (partition by CRTD_PairSymbol,StartIntervalDate order by crtd_period) as rownum
				from #temp) B ON A.CRTD_PairSymbol = B.CRTD_PairSymbol and A.StartPeriod=B.StartIntervalDate
where B.rownum=1

update A
set BidClose_Value = B.CRTD_BidClosingValue,
	MidClose_Value = B.CRTD_MidClosingValue
FROM #temp1 A
	INNER JOIN (select StartIntervalDate,CRTD_PairSymbol,CRTD_BidClosingValue,CRTD_MidClosingValue,ROW_NUMBER() over (partition by CRTD_PairSymbol,StartIntervalDate order by crtd_period desc) as rownum
				from #temp) B ON A.CRTD_PairSymbol = B.CRTD_PairSymbol and A.StartPeriod=B.StartIntervalDate
where B.rownum=1

insert into #MismatchRecords 
	(CRTD_Period,CRTD_FirstQuote,CRTD_LastQuote,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_BidClosingValue,CRTD_BidLowValue,CRTD_BidHighValue,
		CRTD_MidOpeningValue,CRTD_MidClosingValue,CRTD_MidLowValue,CRTD_MidHighValue)
select StartPeriod, First_Quote, Last_Quote, CRTD_PairSymbol, BidOpen_Value, BidClose_Value, BidMin_Value, BidMax_Value,
		MidOpen_Value, MidClose_Value, MidMin_Value, MidMax_Value
from #temp1 
except
select CRTD_Period,CRTD_FirstQuote,CRTD_LastQuote,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_BidClosingValue,CRTD_BidLowValue,CRTD_BidHighValue,
		CRTD_MidOpeningValue,CRTD_MidClosingValue,CRTD_MidLowValue,CRTD_MidHighValue
from CRT_Data_5Minutes 
where CRTD_Period BETWEEN CAST(@checkDay AS DATE) AND CAST(dateadd(millisecond,-3,@checkDay+1) AS DATEtIME)

if @@rowcount>0
	begin
		select 'There are mismatches in CRT_Data_5Minutes. Here are the mismatched records:'
		select * from
					(select 'Calculated' as Source,CRTD_Period,CRTD_FirstQuote,CRTD_LastQuote,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_BidClosingValue,CRTD_BidLowValue,CRTD_BidHighValue,
							CRTD_MidOpeningValue,CRTD_MidClosingValue,CRTD_MidLowValue,CRTD_MidHighValue
					from #MismatchRecords 
					union all
					select 'Saved' as Source,CRTD_Period,CRTD_FirstQuote,CRTD_LastQuote,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_BidClosingValue,CRTD_BidLowValue,CRTD_BidHighValue,
							CRTD_MidOpeningValue,CRTD_MidClosingValue,CRTD_MidLowValue,CRTD_MidHighValue
					from CRT_Data_5Minutes A
					where CRTD_Period BETWEEN CAST(@checkDay AS DATE) AND CAST(dateadd(millisecond,-3,@checkDay+1) AS DATEtIME)
					and exists(select 1 from #MismatchRecords B where A.CRTD_Period=B.CRTD_Period and A.CRTD_PairSymbol=B.CRTD_PairSymbol))s
		order by CRTD_Period,CRTD_PairSymbol,Source
	end
else
	begin
		insert into #MismatchRecords 
			(CRTD_Period,CRTD_FirstQuote,CRTD_LastQuote,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_BidClosingValue,CRTD_BidLowValue,CRTD_BidHighValue,
				CRTD_MidOpeningValue,CRTD_MidClosingValue,CRTD_MidLowValue,CRTD_MidHighValue)
		select CRTD_Period,CRTD_FirstQuote,CRTD_LastQuote,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_BidClosingValue,CRTD_BidLowValue,CRTD_BidHighValue,
				CRTD_MidOpeningValue,CRTD_MidClosingValue,CRTD_MidLowValue,CRTD_MidHighValue
		from CRT_Data_5Minutes 
		where CRTD_Period BETWEEN CAST(@checkDay AS DATE) AND CAST(dateadd(millisecond,-3,@checkDay+1) AS DATEtIME)
		except
		select StartPeriod, First_Quote, Last_Quote, CRTD_PairSymbol, BidOpen_Value, BidClose_Value, BidMin_Value, BidMax_Value,
		  		MidOpen_Value, MidClose_Value, MidMin_Value, MidMax_Value
		from #temp1				
		if @@rowcount>0
			begin
				select 'There are mismatches in CRT_Data_5Minutes. Here are the mismatched records:'
				select * from
						(select 'Saved' as Source,CRTD_Period,CRTD_FirstQuote,CRTD_LastQuote,CRTD_PairSymbol,CRTD_BidOpeningValue,CRTD_BidClosingValue,CRTD_BidLowValue,CRTD_BidHighValue,
								CRTD_MidOpeningValue,CRTD_MidClosingValue,CRTD_MidLowValue,CRTD_MidHighValue
						from #MismatchRecords 
						union all
						select 'Calculated' as Source,StartPeriod, First_Quote, Last_Quote, CRTD_PairSymbol, BidMin_Value, BidMax_Value, MidMin_Value, MidMax_Value,
								MidOpen_Value, MidClose_Value,BidOpen_Value, BidClose_Value
						from #temp1 A
						where exists(select 1 from #MismatchRecords B where A.StartPeriod=B.CRTD_Period and A.CRTD_PairSymbol=B.CRTD_PairSymbol))s
						order by CRTD_Period,CRTD_PairSymbol,Source				
			end 		
		else
			select 'There are no mismatches in CRT_Data_5Minutes at '+convert(varchar(30),@checkDay,120)
	end
		
drop table #temp
drop table #temp1
drop table #MismatchRecords
drop table #LastQuote
GO
/****** Object:  StoredProcedure [dbo].[USP_UTIL_INIT_CRT_LastQuote]    Script Date: 15/06/2017 15:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[USP_UTIL_INIT_CRT_LastQuote]
AS
/*create table CRT_LastQuote
	(TableName varchar(20),
	 CRTD_PairSymbol varchar(50),
	 LAST_CRTD_Period datetime,
	 NEXT_CRTD_Period datetime,
	 Next_End_period datetime,
	 LastQuote datetime)
create index ix_TableName on CRT_LastQuote(TableName)
create index ix_CRTD_PairSymbol on CRT_LastQuote(CRTD_PairSymbol)
*/

truncate table CRT_LastQuote
declare @TableName varchar(100),@sql varchar(max),@UnitDefinition varchar(15),@TimeUnit varchar(10),@TimeInterval varchar(10),
	    @Source_TableName varchar(100)

create table #LastQuote
(CRTD_PairSymbol varchar(20),
max_LastQuote datetime)

insert into #LastQuote
select B.CRTD_PairSymbol,max([CRTD_LastQuote]) as max_LastQuote
from CRT_Data_1Minute B (nolock)							
group by B.CRTD_PairSymbol

declare cTasks cursor local static for
	select CRTT_TableName,CRTT_UnitDefinition,CRTT_Source_TableName
	from CRT_tasks with (nolock)
	where 1=1 
	and CRTT_Name <> '1Minute'
	and CRTT_IsActive = 1 and CRTT_Source_TableName <> '' 
	order by 1
open cTasks
fetch next from cTasks into @TableName, @UnitDefinition,@Source_TableName
while @@fetch_status = 0
	begin	
			set @TimeUnit=substring(@UnitDefinition,1,1)
			set @TimeInterval=substring(@UnitDefinition,2,4)
			SELECT @TimeUnit=CASE @TimeUnit when 'N' then 'minute'
											when 'H' then 'hour'
											when 'D' then 'day'
											when 'W' then 'Week'
											when 'M' then 'Month'		
							  end											

		 Set @SQL =
		'insert into CRT_LastQuote(TableName,CRTD_PairSymbol,LAST_CRTD_Period)
		SELECT '''+@TableName+''',CRTD_PairSymbol ,max(CRTD_Period)
		from  ' + quotename(@TableName) + '(nolock)
		group by CRTD_PairSymbol '
		exec(@SQL)

		update A
			set LastQuote=B.max_LastQuote
			from CRT_LastQuote A
			inner join #LastQuote B on A.CRTD_PairSymbol=B.CRTD_PairSymbol
		where A.tableName=@TableName		

		Set @SQL =
		'update CRT_LastQuote
		 set NEXT_CRTD_Period=dateadd('+@TimeUnit+','+@TimeInterval+', (dateadd('+@TimeUnit+', datediff('+@TimeUnit+',0,LAST_CRTD_Period) / '+@TimeInterval+' * '+@TimeInterval+', 0)))
		 where TableName='''+@TableName+''''
		 exec(@SQL)

		 Set @SQL =
		'update CRT_LastQuote
		 set Next_End_period=dateadd('+@TimeUnit+','+@TimeInterval+', (dateadd('+@TimeUnit+', datediff('+@TimeUnit+',0,NEXT_CRTD_Period) / '+@TimeInterval+' * '+@TimeInterval+', 0)))
		 where TableName='''+@TableName+''''
		 exec(@SQL)

		 fetch next from cTasks into @TableName, @UnitDefinition,@Source_TableName
	end
close cTasks
deallocate cTasks
drop table #LastQuote
GO
USE [master]
GO
ALTER DATABASE [YB_Charts] SET  READ_WRITE 
GO
