USE SharePrices
GO

/*
DROP VIEW vHoldingValueHistory
DROP VIEW vErroneousPrices_Intraday
DROP VIEW vErroneousPrices_Daily
DROP VIEW vHolding
DROP VIEW vCashBalances
DROP FUNCTION dbo.fn_GetExchangeRate
DROP FUNCTION dbo.fn_GetPriceAtDate
DROP PROCEDURE usp_SwapDisplayOrder
DROP PROCEDURE usp_GetHoldingsHistory
--DROP PROCEDURE usp_DeleteHolding
DROP PROCEDURE usp_SoldHolding
DROP PROCEDURE usp_GetAccounts
DROP PROCEDURE usp_GetHoldings
DROP PROCEDURE usp_InsertHolding
DROP PROCEDURE usp_InsertIntradayData
DROP PROCEDURE usp_InsertDailyData
DROP PROCEDURE usp_GetDailyData
DROP PROCEDURE usp_GetIntradayData
DROP PROCEDURE usp_UpdateInstrument
DROP PROCEDURE usp_InsertInstrument
DROP PROCEDURE usp_GetInstruments
DROP TYPE PriceDataType
DROP TABLE Holding
DROP TABLE Account
DROP TABLE AccountHolder
DROP TABLE InstrumentHistory_Daily
DROP TABLE InstrumentHistory_Intraday
DROP TABLE Instrument
DROP TABLE TotalHoldingsHistory_Daily
DROP TABLE AllDays
--DROP TABLE Exchange
*/
GO

/*
CREATE LOGIN [OZDOMAIN\SharePrices_WebApp] FROM WINDOWS
CREATE USER [OZDOMAIN\SharePrices_WebApp] FOR LOGIN [OZDOMAIN\SharePrices_WebApp]
CREATE ROLE WebApp_Role
EXEC sp_addrolemember 'WebApp_Role', 'OZDOMAIN\SharePrices_WebApp'
*/

/*
CREATE TABLE Exchange (
  ExchangeID tinyint IDENTITY NOT NULL,
  ShortName varchar(10) NOT NULL,
  FullName varchar(50) NULL,
  CONSTRAINT PK_Exchange PRIMARY KEY CLUSTERED (ExchangeID)
)
GO
INSERT Exchange (ShortName, FullName)
  VALUES ('N/A', 'N/A'),
         ('ASX', 'Australian Stock Exchange'),
         ('LSE', 'London Stock Exchange'),
         ('NYSE', 'New York Stock Exchange'),
         ('NASDAQ', 'NASDAQ')
GO
*/

CREATE TABLE AllDays (
	DT date NOT NULL,
	CONSTRAINT PK_AllDays PRIMARY KEY CLUSTERED (DT)
)
GO

CREATE TABLE PriceSource (
  PriceSourceID tinyint IDENTITY NOT NULL,
  PriceSourceName varchar(30) NOT NULL,
  CONSTRAINT PK_PriceSource PRIMARY KEY CLUSTERED (PriceSourceID),
  CONSTRAINT UC_PriceSource UNIQUE NONCLUSTERED (PriceSourceName)
)
GO
INSERT PriceSource (PriceSourceName) VALUES
  ('Yahoo Finance UK'),
  ('London Stock Exchange')
GO

CREATE TABLE Instrument (
  InstrumentID smallint IDENTITY NOT NULL,
  --ExchangeID tinyint NOT NULL,
  Symbol VARCHAR(8) NOT NULL,
  FullName VARCHAR(100) NULL,
  DisplayName VARCHAR(30) NULL,
  DisplayOrder TINYINT NULL,
  PostPandemicDilution money NOT NULL,
  GMTOffset INT NULL,
  Currency VARCHAR(3) NULL,
  TrackPriceHistory BIT NOT NULL,
  PriceSourceID tinyint NOT NULL,
  --CurrentPrice money NULL,
  CurrentPrice real NULL,
  InstrumentType VARCHAR(15) NULL,
  ShowInMarquee CHAR(1) NULL, -- A = Always, O = Only when open, NULL = Never
  WatchlistID tinyint NULL, --Not a real ID yet
  TradeDayStart datetime NULL,
  TradeDayEnd datetime NULL,
  LastUpdated datetime NULL,
  CONSTRAINT PK_Instrument PRIMARY KEY CLUSTERED (InstrumentID),
  CONSTRAINT UC_Instrument_Symbol UNIQUE NONCLUSTERED (Symbol),
  CONSTRAINT FK_Instrument_PriceSource FOREIGN KEY (PriceSourceID) REFERENCES PriceSource (PriceSourceID),
  --CONSTRAINT FK_Instrument_Exchange FOREIGN KEY (ExchangeID) REFERENCES Exchange (ExchangeID)
)
GO  

--CREATE NONCLUSTERED INDEX IDX_Instrument_ExchangeID_Symbol ON Instrument (ExchangeID, Symbol)
--CREATE NONCLUSTERED INDEX IDX_Instrument_Symbol ON Instrument (Symbol)
CREATE NONCLUSTERED INDEX IDX_Instrument_DisplayOrder ON Instrument (DisplayOrder)
GO

CREATE TABLE InstrumentHistory_Daily (
  InstrumentID smallint NOT NULL,
  HistoryDT date NOT NULL,
  --OpenPrice money NULL,
  --HighPrice money NULL,
  --LowPrice money NULL,
  --ClosePrice money NULL,
  OpenPrice real NULL,
  HighPrice real NULL,
  LowPrice real NULL,
  ClosePrice real NULL,
  Volume bigint NULL,
  CONSTRAINT PK_InstrumentHistory_Daily PRIMARY KEY CLUSTERED (InstrumentID, HistoryDT),
  CONSTRAINT FK_InstrumentHistory_Daily_Instrument FOREIGN KEY (InstrumentID) REFERENCES Instrument (InstrumentID)
)
GO

CREATE TABLE InstrumentHistory_Intraday (
  InstrumentID smallint NOT NULL,
  HistoryDT smalldatetime NOT NULL,
  --OpenPrice money NULL,
  --HighPrice money NULL,
  --LowPrice money NULL,
  --ClosePrice money NULL,
  OpenPrice real NULL,
  HighPrice real NULL,
  LowPrice real NULL,
  ClosePrice real NULL,
  Volume bigint NULL,
  CONSTRAINT PK_InstrumentHistory_Intraday PRIMARY KEY CLUSTERED (InstrumentID, HistoryDT),
  CONSTRAINT FK_InstrumentHistory_Intraday_Instrument FOREIGN KEY (InstrumentID) REFERENCES Instrument (InstrumentID)
)
GO

CREATE TABLE AccountHolder (
	AccountHolderID tinyint IDENTITY NOT NULL,
	Name varchar(10) NOT NULL,
	CONSTRAINT PK_AccountHolder PRIMARY KEY CLUSTERED (AccountHolderID),
	CONSTRAINT UC_AccountHolder UNIQUE NONCLUSTERED (Name)
)
GO
INSERT AccountHolder (Name) VALUES ('Steve'), ('Steph')
GO

CREATE TABLE Account (
  AccountID tinyint IDENTITY NOT NULL,
  AccountHolderID tinyint NOT NULL,
  ShortName varchar(20) NOT NULL,
  IsTaxable bit NOT NULL,
  CONSTRAINT PK_Account PRIMARY KEY CLUSTERED (AccountID),
  CONSTRAINT UC_Account_ShortName UNIQUE NONCLUSTERED (ShortName),
  CONSTRAINT FK_Account_AccountHolder FOREIGN KEY (AccountHolderID) REFERENCES AccountHolder (AccountHolderID)
)
GO
INSERT Account (ShortName) VALUES
  ('Steve HL ISA'),
  ('Steve HL Trd'),
  ('Steph HL Trd'),
  ('Steph ii ISA'),
  ('Steph ii Trd'),
  ('Steve ii Trd'),
  ('Steve ii ISA'),
  ('Steve AJB'),
  ('Steph AJB'),
  ('Steve Crypto')
GO

CREATE TABLE Holding (
  HoldingID int IDENTITY NOT NULL,
  AccountID tinyint NOT NULL,
  InstrumentID smallint NOT NULL,
  --NoUnits int NOT NULL,
  --NoUnits real NOT NULL,
  NoUnits numeric(36, 12) NOT NULL,
  --PurchasePricePerUnit money NOT NULL,
  --PurchasePricePerUnit real NOT NULL,
  PurchasePricePerUnit numeric(36, 12) NOT NULL,
  --ActualExchangeRate real NULL,
  ActualExchangeRate numeric(36, 12) NULL,
  PurchaseDate datetime NOT NULL,
  PurchaseCurrencyID smallint NULL,
  BookCostInPurchaseCurrency numeric(36, 12) NULL,
  SoldDate datetime NULL,
  SoldCurrencyID smallint NULL,
  SoldProceeds numeric(36, 12) NULL,
  CONSTRAINT PK_Holding PRIMARY KEY CLUSTERED (HoldingID),
  CONSTRAINT FK_Holding_Account FOREIGN KEY (AccountID) REFERENCES Account (AccountID),
  CONSTRAINT FK_Holding_Instrument FOREIGN KEY (InstrumentID) REFERENCES Instrument (InstrumentID),
  CONSTRAINT FK_Holding_SoldCurrencyInstrument FOREIGN KEY (SoldCurrencyID) REFERENCES Instrument (InstrumentID)
)
GO

CREATE TABLE TradeActionType (
	ActionType VARCHAR(10) NOT NULL,
	CONSTRAINT PK_TradeActionType PRIMARY KEY CLUSTERED (ActionType)
)
GO
INSERT TradeActionType VALUES ('Buy'), ('Sell'), ('Transfer'), ('Split')
GO

CREATE TABLE TradeLedger (
	TradeLedgerID INT IDENTITY NOT NULL,
	InstrumentID SMALLINT NOT NULL,
	AccountID TINYINT NOT NULL,
	TradeDT datetime NOT NULL,
	ActionType VARCHAR(10) NOT NULL,
	NoUnits NUMERIC(36, 12) NOT NULL,
	TradeCurrencyID SMALLINT NOT NULL,
	ActualExchangeRate NUMERIC(36, 12) NULL,
	EstimatedExchangeRate NUMERIC(36, 12) NULL,
	TradeValue MONEY NOT NULL,
	TradeValueGBP MONEY NOT NULL,
	--NewPoolNoUnits NUMERIC(36, 12) NOT NULL,
	--NewPoolCostBaseGBP MONEY NOT NULL,
	Notes VARCHAR(1000) NULL,
	CONSTRAINT PK_TradeLedger PRIMARY KEY CLUSTERED (TradeLedgerID),
	CONSTRAINT FK_TradeLedger_Instrument FOREIGN KEY (InstrumentID) REFERENCES Instrument (InstrumentID),
	CONSTRAINT FK_TradeLedger_TradeActionType FOREIGN KEY (ActionType) REFERENCES TradeActionType (ActionType),
	CONSTRAINT FK_TradeLedger_TradeCurrency FOREIGN KEY (TradeCurrencyID) REFERENCES Instrument (InstrumentID),
	CONSTRAINT UC_TradeLedger UNIQUE NONCLUSTERED (InstrumentID, AccountID, TradeDT)
)
GO

/*
UPDATE ShareTrades_Steph_XLS SET Account = CASE Account WHEN 'AJ Bell' THEN 'Steph AJB'
WHEN 'AJ Bell - ISA' THEN 'Steph AJB ISA'
WHEN 'Hargreaves Lansdown' THEN 'Steph HL Trd'
WHEN 'Interactive Investor - ISA' THEN 'Steph ii ISA'
WHEN 'Interactive Investor - Trading Account' THEN 'Steph ii Trd'
ELSE Account END

UPDATE ShareTrades_Steve_XLS SET Account = CASE Account WHEN 'AJ Bell' THEN 'Steve AJB'
WHEN 'AJ Bell - ISA' THEN 'Steve AJB ISA'
WHEN 'Hargreaves Lansdown - Trading Account' THEN 'Steve HL Trd'
WHEN 'Hargreaves Lansdown - ISA' THEN 'Steve HL ISA'
WHEN 'Interactive Investor - ISA' THEN 'Steve ii ISA'
WHEN 'Interactive Investor - Trading Account' THEN 'Steve ii Trd'
ELSE Account END

INSERT TradeLedger (
	[InstrumentID],
	[AccountID],
	[TradeDT],
	[ActionType],
	[NoUnits],
	[TradeCurrencyID],
	[ActualExchangeRate],
	[EstimatedExchangeRate],
	[TradeValue],
	[TradeValueGBP],
	[Notes]
)
SELECT
	InstrumentID,
	a.AccountID,
	[Transaction Date (UK time)],
	[Buy or Sell],
	[No Units],
	(SELECT InstrumentID FROM Instrument WHERE Currency = [Settlement Currency] AND InstrumentType = 'CURRENCY'),
	CASE WHEN [Settlement Currency] = 'GBP' THEN 1 ELSE NULL END,
	CASE WHEN [Settlement Currency] = 'GBP' THEN NULL ELSE dbo.fn_GetExchangeRate([Settlement Currency], [Transaction Date (UK time)]) END,
	[Transaction Total],
	ROUND([Transaction Total] / CASE WHEN [Settlement Currency] = 'GBP' THEN 1 ELSE dbo.fn_GetExchangeRate([Settlement Currency], [Transaction Date (UK time)]) END, 2),
	Notes + ISNULL(' - [' + F9 + ']', '')
FROM
	ShareTrades_Steph_XLS x
	LEFT OUTER JOIN Account a
		ON a.ShortName = x.Account
WHERE
	[Buy or Sell] IN ('Buy', 'Sell')
ORDER BY [Transaction Date (UK time)]

INSERT TradeLedger (
	[InstrumentID],
	[AccountID],
	[TradeDT],
	[ActionType],
	[NoUnits],
	[TradeCurrencyID],
	[ActualExchangeRate],
	[EstimatedExchangeRate],
	[TradeValue],
	[TradeValueGBP],
	[Notes]
)
SELECT
	InstrumentID,
	a.AccountID,
	[Transaction Date (UK time)],
	[Buy or Sell],
	[No Units],
	(SELECT InstrumentID FROM Instrument WHERE Currency = [Settlement Currency] AND InstrumentType = 'CURRENCY'),
	CASE WHEN [Settlement Currency] = 'GBP' THEN 1 ELSE NULL END,
	CASE WHEN [Settlement Currency] = 'GBP' THEN NULL ELSE dbo.fn_GetExchangeRate([Settlement Currency], [Transaction Date (UK time)]) END,
	[Transaction Total],
	ROUND([Transaction Total] / CASE WHEN [Settlement Currency] = 'GBP' THEN 1 ELSE dbo.fn_GetExchangeRate([Settlement Currency], [Transaction Date (UK time)]) END, 2),
	Notes + ISNULL(' - [' + F9 + ']', '')
FROM
	ShareTrades_Steve_XLS x
	LEFT OUTER JOIN Account a
		ON a.ShortName = x.Account
WHERE
	[Buy or Sell] IN ('Buy', 'Sell')
ORDER BY [Transaction Date (UK time)]
GO
*/

/*
SELECT * FROM Account
SELECT * FROM Instrument WHERE symbol IN ('LMI3.L', '2BRK.L')
87	LMI3.L
93	2BRK.L
*/

CREATE TABLE TotalHoldingsHistory_Daily (
	HistoryDate date NOT NULL,
	[Open] int NOT NULL,
	Low int NOT NULL,
	High int NOT NULL,
	[Close] int NOT NULL,
	CONSTRAINT PK_TotalHoldingsHistory_Daily PRIMARY KEY CLUSTERED (HistoryDate)
)
GO

CREATE TYPE PriceDataType
AS TABLE (
  PriceDT datetime NOT NULL,
  --OpenPrice money NULL,
  --HighPrice money NULL,
  --LowPrice money NULL,
  --ClosePrice money NULL,
  OpenPrice real NULL,
  HighPrice real NULL,
  LowPrice real NULL,
  ClosePrice real NULL,
  Volume bigint NULL
)
GO
GRANT EXECUTE ON TYPE::PriceDataType TO WebApp_Role
GO

CREATE OR ALTER FUNCTION dbo.fn_GetExchangeRate(@Currency VARCHAR(3), @DT DATETIME)
RETURNS REAL
AS
BEGIN
  DECLARE @Rate REAL
  IF @Currency COLLATE Latin1_General_CS_AS = 'GBp' COLLATE Latin1_General_CS_AS
  BEGIN
    SET @Rate = 100
  END
  ELSE
  BEGIN
    IF @Currency COLLATE Latin1_General_CS_AS = 'GBP' COLLATE Latin1_General_CS_AS
    BEGIN
      SET @Rate = 1
    END
    ELSE
    BEGIN
      DECLARE @InstrumentID INT
      SELECT @InstrumentID = InstrumentID FROM Instrument WHERE FullName = 'GBP/' + @Currency
      IF @InstrumentID IS NULL
      BEGIN
        --Currency pair Instrument not found - return zero to indicate error
        SET @Rate = 0
      END
      ELSE
      BEGIN
        --Is there a rate for this exact datetime?
        SELECT @Rate = ClosePrice FROM InstrumentHistory_Intraday WHERE InstrumentID = @InstrumentID AND HistoryDT = @DT
        IF @Rate IS NULL
        BEGIN
          --No exect match
          DECLARE @StartDT DATETIME, @EndDT DATETIME, @StartRate REAL, @EndRate REAL
          --@StartID INT, @EndID INT, 
          SELECT TOP 1 @StartDT = HistoryDT, @StartRate = ClosePrice FROM InstrumentHistory_Intraday WHERE InstrumentID = @InstrumentID AND HistoryDT < @DT ORDER BY HistoryDT DESC
          SELECT TOP 1 @EndDT = HistoryDT, @EndRate = OpenPrice FROM InstrumentHistory_Intraday WHERE InstrumentID = @InstrumentID AND HistoryDT > @DT ORDER BY HistoryDT
          IF @StartDT IS NOT NULL AND @EndDT IS NOT NULL
          BEGIN
            --Work out how far between the 2 dates our DT is, and calculate rate accordingly
            DECLARE @TotalSeconds BIGINT
            DECLARE @Percent REAL
            SELECT @TotalSeconds = DATEDIFF(second, @StartDT, @EndDT)
            SET @Percent = CONVERT(REAL, DATEDIFF(second, @StartDT, @DT)) / @TotalSeconds * 100
            SET @Rate = @StartRate + ((@EndRate - @StartRate) / 100 * @Percent)
          END
          ELSE
          BEGIN
            --We don't have BOTH a start AND end price
            --Return the non-NULL rate if we have one, zero otherwise
            SET @Rate = COALESCE(@StartRate, @EndRate, 0)
          END
        END
      END
    END
  END

  RETURN @Rate
END
GO

CREATE OR ALTER FUNCTION dbo.fn_GetPriceAtDate(@InstrumentID INT, @DT DATETIME)
RETURNS REAL
AS
BEGIN
  DECLARE @Rate REAL
  
  IF @InstrumentID IS NULL OR @DT IS NULL
  BEGIN
    RETURN 0.0
  END
  
  --Is there a rate for this exact datetime?
  SELECT @Rate = ClosePrice FROM InstrumentHistory_Intraday WHERE InstrumentID = @InstrumentID AND HistoryDT = @DT
  IF @Rate IS NULL
  BEGIN
    --No exect match
    DECLARE @StartDT DATETIME, @EndDT DATETIME, @StartRate REAL, @EndRate REAL
    --@StartID INT, @EndID INT, 
    SELECT TOP 1 @StartDT = HistoryDT, @StartRate = ClosePrice FROM InstrumentHistory_Intraday WHERE InstrumentID = @InstrumentID AND HistoryDT < @DT ORDER BY HistoryDT DESC
    SELECT TOP 1 @EndDT = HistoryDT, @EndRate = OpenPrice FROM InstrumentHistory_Intraday WHERE InstrumentID = @InstrumentID AND HistoryDT > @DT ORDER BY HistoryDT
    IF @StartDT IS NOT NULL AND @EndDT IS NOT NULL
    BEGIN
      --Work out how far between the 2 dates our DT is, and calculate rate accordingly
      DECLARE @TotalSeconds BIGINT
      DECLARE @Percent REAL
      SELECT @TotalSeconds = DATEDIFF(second, @StartDT, @EndDT)
      SET @Percent = CONVERT(REAL, DATEDIFF(second, @StartDT, @DT)) / @TotalSeconds * 100
      SET @Rate = @StartRate + ((@EndRate - @StartRate) / 100 * @Percent)
    END
    ELSE
    BEGIN
      --We don't have BOTH a start AND end price
      --Return the non-NULL rate if we have one, zero otherwise
      SET @Rate = COALESCE(@StartRate, @EndRate, 0)
    END
  END
  
  RETURN @Rate
END
GO

--CREATE PROCEDURE usp_InsertInstrument (@ExchangeShortName varchar(10), @Symbol varchar(7), @FullName varchar(100))
CREATE OR ALTER PROCEDURE usp_InsertInstrument (@Symbol varchar(8), @FullName varchar(100))
AS
BEGIN
  SET NOCOUNT ON
  DECLARE @DisplayOrder tinyint
  
  IF NOT EXISTS (SELECT NULL FROM Instrument WHERE Symbol = @Symbol)
  BEGIN
    SELECT @DisplayOrder = MAX(DisplayOrder)+1 FROM Instrument
    SELECT @DisplayOrder = ISNULL(@DisplayOrder, 1)

    --INSERT Instrument (ExchangeID, Symbol, FullName, DisplayOrder) SELECT @ExchangeID, @Symbol, @FullName, @DisplayOrder WHERE NOT EXISTS (SELECT NULL FROM Instrument WHERE ExchangeID = @ExchangeID AND Symbol = @Symbol)
    INSERT Instrument (Symbol, FullName, DisplayOrder, PostPandemicDilution, PriceSourceID, TrackPriceHistory) SELECT @Symbol, @FullName, @DisplayOrder, 1, 1, 1
    
	SELECT
      i.DisplayOrder,
      i.FullName as [InstrumentName],
      i.Symbol as [Symbol],
      CONVERT(DATETIME, '2030-12-31') as [MinDailyDate],
      CONVERT(DATETIME, '1970-01-01') as [MaxDailyDate],
      CONVERT(DATETIME, '2030-12-31') as [MinIntradayDate],
      CONVERT(DATETIME, '1970-01-01') as [MaxIntradayDate]
    FROM
      Instrument i
    WHERE
      Symbol = @Symbol
  END
END
GO
GRANT EXECUTE ON usp_InsertInstrument TO WebApp_Role
GO
/*
EXEC usp_InsertInstrument '^AXJO', 'S&P ASX 200'
EXEC usp_InsertInstrument 'QAN.AX', 'Qantas'
EXEC usp_InsertInstrument 'WEB.AX', 'Webjet'
EXEC usp_InsertInstrument 'WBC.AX', 'Westpac'
EXEC usp_InsertInstrument 'CBA.AX', 'Commonwealth Bank'
EXEC usp_InsertInstrument 'FLT.AX', 'Flight Centre'
EXEC usp_InsertInstrument '^FTSE', 'FTSE 100'
EXEC usp_InsertInstrument '^FTAS', 'FTSE All-Share'
EXEC usp_InsertInstrument 'TMPL.L', 'Temple Bar Investment Trust'
EXEC usp_InsertInstrument 'SDV.L', 'Cherverton Investment Trust'
EXEC usp_InsertInstrument 'MKS.L', 'Marks & Spencer'
EXEC usp_InsertInstrument 'BP.L', 'BP'
EXEC usp_InsertInstrument 'RDSB.L', 'Royal Dutch Shell'
EXEC usp_InsertInstrument 'LLOY.L', 'Lloyds Bank'
EXEC usp_InsertInstrument 'BARC.L', 'Barclays Bank'
EXEC usp_InsertInstrument 'AML.L', 'Aston Martin Lagonda'
EXEC usp_InsertInstrument 'TUI.L', 'TUI'
EXEC usp_InsertInstrument 'RR.L', 'Rolls Royce'
EXEC usp_InsertInstrument 'IAG.L', 'International Consolidated Airlines'
EXEC usp_InsertInstrument 'CCL.L', 'Carnival Cruises (LSE)'
EXEC usp_InsertInstrument '^GSPC', 'S&P 500'
EXEC usp_InsertInstrument '^DJI', 'Dow Jones Industrial Average'
EXEC usp_InsertInstrument '^IXIC', 'NASDAQ Composite'
EXEC usp_InsertInstrument 'CCL', 'Carnival Cruises (NYSE)'
EXEC usp_InsertInstrument 'RCL', 'Royal Caribbean Cruises'
EXEC usp_InsertInstrument 'NCLH', 'Norwegian Cruise Line Holdings'
EXEC usp_InsertInstrument 'AAL', 'American Airlines'
EXEC usp_InsertInstrument 'EBAY', 'E-bay'
--EXEC usp_InsertInstrument 'AMZN', 'Amazon'
EXEC usp_InsertInstrument 'GBPUSD=X', 'GBP/USD'
EXEC usp_InsertInstrument 'GBPAUD=X', 'GBP/AUD'
GO
*/

/*

delete InstrumentHistory_Intraday where InstrumentID>31
delete InstrumentHistory_Daily where InstrumentID>31
delete Instrument where InstrumentID>31

*/

--CREATE PROCEDURE usp_UpdateInstrument (@Symbol varchar(8), @GMTOffset int, @Currency varchar(3), @CurrentPrice money, @InstrumentType varchar(15), @TradeDayStart datetime, @TradeDayEnd datetime)
CREATE OR ALTER PROCEDURE usp_UpdateInstrument (@Symbol varchar(8), @GMTOffset int, @Currency varchar(3), @CurrentPrice real, @InstrumentType varchar(15), @TradeDayStart datetime, @TradeDayEnd datetime)
AS
BEGIN
  SET NOCOUNT ON
  DECLARE @DisplayOrder tinyint
  
  UPDATE
    Instrument
  SET
    --DisplayName VARCHAR(30) NULL,
    --PostPandemicDilution money NOT NULL,
    --ShowInMarquee CHAR(1) NULL, -- A = Always, O = Only when open, NULL = Never
    GMTOffset = @GMTOffset,
    Currency = @Currency,
    CurrentPrice = @CurrentPrice,
    InstrumentType = @InstrumentType,
    TradeDayStart = @TradeDayStart,
    TradeDayEnd = @TradeDayEnd,
    LastUpdated = CURRENT_TIMESTAMP
  WHERE
    Symbol = @Symbol
END
GO
GRANT EXECUTE ON usp_UpdateInstrument TO WebApp_Role
GO

CREATE OR ALTER PROCEDURE usp_GetAccounts
AS
BEGIN
  SET NOCOUNT ON
  
  SELECT
    ShortName as [AccountName]
  FROM
    Account
  ORDER BY
    ShortName
END
GO
GRANT EXECUTE ON usp_GetAccounts TO WebApp_Role
GO

CREATE OR ALTER PROCEDURE usp_GetInstruments
AS
BEGIN
  SET NOCOUNT ON
  
  SELECT
    DisplayOrder,
    [InstrumentName],
    [DisplayName],
    [Symbol],
    [PostPandemicDilution],
    [GMTOffset],
    [Currency],
	CASE [TrackPriceHistory] WHEN 1 THEN 1 ELSE 0 END as [TrackPriceHistory], --Javascript doesn't like True/False
	[PriceSourceName] as [PriceSource],
    [CurrentPrice],
    [InstrumentType],
    [ShowInMarquee],
    [WatchlistID],
    [SingleDayStartDate],
    [SingleDayEndDate],
    [MinDailyDate],
    [MaxDailyDate],
    [MinIntradayDate],
    [MaxIntradayDate],
    [LastSoldDate],
    dbo.fn_GetPriceAtDate(dt.InstrumentID, LastSoldDate) as [LastSoldPrice]
  FROM
    (SELECT
      i.InstrumentID,
      i.DisplayOrder,
      i.FullName as [InstrumentName],
      ISNULL(i.DisplayName, LEFT(i.FullName, 30)) as [DisplayName],
      i.Symbol as [Symbol],
      i.PostPandemicDilution as [PostPandemicDilution],
      i.GMTOffset as [GMTOffset],
      i.Currency as [Currency],
	  i.TrackPriceHistory as [TrackPriceHistory],
	  ps.PriceSourceName as [PriceSourceName],
      i.CurrentPrice as [CurrentPrice],
      i.InstrumentType as [InstrumentType],
      i.ShowInMarquee as [ShowInMarquee],
      i.WatchlistID as [WatchlistID],
      i.TradeDayStart as [SingleDayStartDate],
      i.TradeDayEnd as [SingleDayEndDate],
      ISNULL((SELECT MIN(dd.HistoryDT) FROM InstrumentHistory_Daily dd WHERE dd.InstrumentID = i.InstrumentID), CONVERT(DATETIME, '2030-12-31')) as [MinDailyDate],
      ISNULL((SELECT MAX(dd.HistoryDT) FROM InstrumentHistory_Daily dd WHERE dd.InstrumentID = i.InstrumentID), CONVERT(DATETIME, '1970-01-01')) as [MaxDailyDate],
      ISNULL((SELECT MIN(id.HistoryDT) FROM InstrumentHistory_Intraday id WHERE id.InstrumentID = i.InstrumentID), CONVERT(DATETIME, '2030-12-31')) as [MinIntradayDate],
      ISNULL((SELECT MAX(id.HistoryDT) FROM InstrumentHistory_Intraday id WHERE id.InstrumentID = i.InstrumentID), CONVERT(DATETIME, '1970-01-01')) as [MaxIntradayDate],
      (SELECT MAX(h.SoldDate) FROM Holding h WHERE h.InstrumentID = i.InstrumentID AND h.SoldDate IS NOT NULL) as [LastSoldDate]
    FROM
      Instrument i
	  INNER JOIN PriceSource ps
	    ON ps.PriceSourceID = i.PriceSourceID) as dt
  ORDER BY
    DisplayOrder
END
GO
GRANT EXECUTE ON usp_GetInstruments TO WebApp_Role
GO

CREATE OR ALTER PROCEDURE usp_GetDailyData (@Symbol varchar(8), @StartDate datetime, @EndDate datetime)
AS
BEGIN
  SELECT
    h.HistoryDT as [DT],
    h.OpenPrice as [open],
    h.HighPrice as [high],
    h.LowPrice as [low],
    h.ClosePrice as [close],
    h.Volume as [volume]
  FROM
    Instrument i
    INNER JOIN InstrumentHistory_Daily h
      ON h.InstrumentID = i.InstrumentID
  WHERE
    i.Symbol = @Symbol
    AND h.HistoryDT >= @StartDate
    AND h.HistoryDT <= @EndDate
  ORDER BY
    h.HistoryDT
END
GO
GRANT EXECUTE ON usp_GetDailyData TO WebApp_Role
GO

CREATE OR ALTER PROCEDURE usp_GetIntradayData (@Symbol varchar(8), @StartDate datetime, @EndDate datetime)
AS
BEGIN
  DECLARE @MAX_DAYS INT = 30
  
  IF DATEDIFF(dd, @StartDate, @EndDate) > @MAX_DAYS
  BEGIN
    SET @StartDate = DATEADD(dd, 0-@MAX_DAYS, @EndDate)
  END

  SELECT
    h.HistoryDT as [DT],
    h.OpenPrice as [open],
    h.HighPrice as [high],
    h.LowPrice as [low],
    h.ClosePrice as [close],
    h.Volume as [volume]
  FROM
    Instrument i
    INNER LOOP JOIN InstrumentHistory_Intraday h
      ON h.InstrumentID = i.InstrumentID
  WHERE
    i.Symbol = @Symbol
    AND h.HistoryDT >= @StartDate
    AND h.HistoryDT <= @EndDate
  ORDER BY
    h.HistoryDT
END
GO
GRANT EXECUTE ON usp_GetIntradayData TO WebApp_Role
GO

CREATE OR ALTER PROCEDURE usp_InsertDailyData (@Symbol varchar(8), @PriceData PriceDataType READONLY)
AS
BEGIN
  SET NOCOUNT ON
  DECLARE @InstrumentID int
  --DECLARE @NoUpdated int
  DECLARE @NoInserted int
  
  SELECT @InstrumentID = InstrumentID FROM Instrument WHERE Symbol = @Symbol
  
  IF @InstrumentID IS NOT NULL
  BEGIN
  /*
    UPDATE
      h
    SET
      OpenPrice = d.OpenPrice,
      HighPrice = d.HighPrice,
      LowPrice = d.LowPrice,
      ClosePrice = d.ClosePrice,
      Volume = d.Volume
    FROM
      @PriceData d
      INNER JOIN InstrumentHistory_Daily h
        ON h.InstrumentID = @InstrumentID
       AND h.HistoryDT = CONVERT(date, d.PriceDT)
       
    SET @NoUpdated = @@ROWCOUNT
    */
    
    INSERT InstrumentHistory_Daily (
      InstrumentID,
      HistoryDT,
      OpenPrice,
      HighPrice,
      LowPrice,
      ClosePrice,
      Volume)
    SELECT
      @InstrumentID,
      CONVERT(date, DATEADD(hour, 1, PriceDT)), --Add an hour to the input datetime before converting to date to allow for changes in daylight savings
      OpenPrice,
      HighPrice,
      LowPrice,
      ClosePrice,
      Volume
    FROM
      @PriceData d
    WHERE
      NOT EXISTS (SELECT NULL FROM InstrumentHistory_Daily h WHERE h.InstrumentID = @InstrumentID AND h.HistoryDT = CONVERT(date, DATEADD(hour, 1, PriceDT)))
      
    SET @NoInserted = @@ROWCOUNT
    
    SELECT @NoInserted as [NoInserted] /*, @NoUpdated as [NoUpdated]*/
  END
  ELSE
  BEGIN
    SELECT CONVERT(int, 0) as [NoInserted], CONVERT(int, 0) as [NoUpdated]
  END
END
GO
GRANT EXECUTE ON usp_InsertDailyData TO WebApp_Role
GO

CREATE OR ALTER PROCEDURE usp_InsertIntradayData (@Symbol varchar(8), @PriceData PriceDataType READONLY)
AS
BEGIN
  SET NOCOUNT ON
  DECLARE @InstrumentID int
  DECLARE @NoUpdated int
  DECLARE @NoInserted int
  
  SELECT @InstrumentID = InstrumentID FROM Instrument WHERE Symbol = @Symbol
  
  IF @InstrumentID IS NOT NULL
  BEGIN
    UPDATE
      h
    SET
      OpenPrice = d.OpenPrice,
      HighPrice = d.HighPrice,
      LowPrice = d.LowPrice,
      ClosePrice = d.ClosePrice,
      Volume = d.Volume
    FROM
      @PriceData d
      INNER JOIN InstrumentHistory_Intraday h
        ON h.InstrumentID = @InstrumentID
       AND h.HistoryDT = d.PriceDT
       
    SET @NoUpdated = @@ROWCOUNT
    
    INSERT InstrumentHistory_Intraday (
      InstrumentID,
      HistoryDT,
      OpenPrice,
      HighPrice,
      LowPrice,
      ClosePrice,
      Volume)
    SELECT
      @InstrumentID,
      PriceDT,
      OpenPrice,
      HighPrice,
      LowPrice,
      ClosePrice,
      Volume
    FROM
      @PriceData d
    WHERE
      NOT EXISTS (SELECT NULL FROM InstrumentHistory_Intraday h WHERE h.InstrumentID = @InstrumentID AND h.HistoryDT = d.PriceDT)
      
    SET @NoInserted = @@ROWCOUNT
    
    SELECT @NoInserted as [NoInserted], @NoUpdated as [NoUpdated]
  END
  ELSE
  BEGIN
    SELECT CONVERT(int, 0) as [NoInserted], CONVERT(int, 0) as [NoUpdated]
  END
END
GO
GRANT EXECUTE ON usp_InsertIntradayData TO WebApp_Role
GO

--CREATE PROCEDURE usp_InsertHolding (@Account varchar(20), @Symbol varchar(8), @NoUnits int, @PurchasePricePerUnit money, @PurchaseDate datetime, @Solddate datetime = NULL)
CREATE OR ALTER PROCEDURE usp_InsertHolding (@Account varchar(20), @Symbol varchar(8), @NoUnits real, @PurchasePricePerUnit real, @PurchaseDate datetime, @PurchaseCurrency varchar(8), @BookCostInPurchaseCurrency numeric(36, 12), @Solddate datetime = NULL)
AS
BEGIN
  DECLARE @AccountID tinyint
  DECLARE @InstrumentID smallint
  
  SELECT @AccountID = AccountID FROM Account WHERE ShortName = @Account
  
  SELECT @InstrumentID = InstrumentID FROM Instrument WHERE Symbol = @Symbol
  
  INSERT Holding (
    AccountID,
    InstrumentID,
    NoUnits,
    PurchasePricePerUnit,
    PurchaseDate,
	PurchaseCurrencyID,
    BookCostInPurchaseCurrency,
    SoldDate)
  SELECT
    @AccountID,
    @InstrumentID,
    @NoUnits,
    @PurchasePricePerUnit,
    @PurchaseDate,
	(SELECT InstrumentID FROM Instrument WHERE Symbol = @PurchaseCurrency),
	@BookCostInPurchaseCurrency,
    @SoldDate

  SELECT
    h.HoldingID,
    a.ShortName as [AccountName],
    i.Symbol,
    h.PurchaseDate,
    h.NoUnits,
    h.PurchasePricePerUnit,
    h.SoldDate
  FROM
    Holding h
    INNER JOIN Instrument i
      ON i.InstrumentID = h.InstrumentID
    INNER JOIN Account a
      ON a.AccountID = h.AccountID
  WHERE
    h.HoldingID = @@IDENTITY
END
GO
GRANT EXECUTE ON usp_InsertHolding TO WebApp_Role
GO

-- EXEC usp_InsertHolding 'Steph AJB', 'TMPL.L', 2372,  708, '2020-05-13'
-- EXEC usp_InsertHolding 'Steph AJB', 'SDV.L', 2000,  127, '2020-05-17', '2020-06-12'
-- EXEC usp_InsertHolding 'Steph AJB', 'BP.L', 5787,  311, '2020-05-13'
-- EXEC usp_InsertHolding 'Steph AJB', 'RDSB.L', 1897,  1264.88, '2020-05-11'
-- EXEC usp_InsertHolding 'Steph AJB', 'LLOY.L', 59170,  30.42, '2020-05-11'
-- EXEC usp_InsertHolding 'Steph AJB', 'BARC.L', 17261,  104.28, '2020-05-11'

-- EXEC usp_InsertHolding 'Steph HL Trd', 'EBAY', 949, 39.35, '2020-04-29', '2020-06-11'
-- EXEC usp_InsertHolding 'Steph HL Trd', 'NCLH', 1696, 21.72, '2020-06-10', '2020-06-11'
-- EXEC usp_InsertHolding 'Steph HL Trd', 'AMZN', 15, 2375.18, '2020-04-29', '2020-06-05'
-- EXEC usp_InsertHolding 'Steph HL Trd', 'IAG.L', 6644, 325.1, '2020-06-05'
-- EXEC usp_InsertHolding 'Steph HL Trd', 'RR.L', 5783, 335.08, '2020-06-05'
-- EXEC usp_InsertHolding 'Steph HL Trd', 'RR.L', 19276, 32.00, '2020-11-09'

-- EXEC usp_InsertHolding 'Steph ii ISA', 'AAL', 2170, 11.5245, '2020-07-21 12:13', NULL
-- EXEC usp_InsertHolding 'Steph ii ISA', 'FLT.AX', 2705, 11.63, '2020-08-20 01:10', NULL
-- EXEC usp_InsertHolding 'Steph ii ISA', 'RCL', 1050,  54.15 , '2020-05-27', '2020-06-11'
-- EXEC usp_InsertHolding 'Steph ii ISA', 'GME', 125, 125.033296, '2021-02-25 15:01', NULL
-- EXEC usp_InsertHolding 'Steph ii ISA', 'AAL', 1840, 20.845949, '2021-02-26 14:13', NULL

-- EXEC usp_InsertHolding 'Steph ii Trd', 'NCLH', 2650, 17.8, '2020-05-27', '2020-06-11'
-- EXEC usp_InsertHolding 'Steph ii Trd', 'AML.L', 9985, 67.1, '2020-06-04', '2020-06-12'
-- EXEC usp_InsertHolding 'Steph ii Trd', 'CBA.AX', 580,  59.00, '2020-05-13', '2020-06-12'
-- EXEC usp_InsertHolding 'Steph ii Trd', 'NCLH', 2580, 19.037, '2020-07-21 11:55', NULL
-- EXEC usp_InsertHolding 'Steph ii Trd', 'NCLH', 2580, 15.1690, '2020-07-21 11:55', NULL
-- EXEC usp_InsertHolding 'Steph ii Trd', 'RCL', 1071, 53.7053, '2020-07-21 12:01', NULL
-- EXEC usp_InsertHolding 'Steph ii Trd', 'RCL', 1078, 53.192, '2020-07-21 12:18', NULL
-- EXEC usp_InsertHolding 'Steph ii Trd', 'MKS.L', 33546, 138.59, '2021-02-22 14:58', NULL
-- EXEC usp_InsertHolding 'Steph ii Trd', 'CUK', 3250, 21.54336, '2021-02-22 15:04', NULL
-- EXEC usp_InsertHolding 'Steph ii Trd', 'AAL', 1700, 20.42657, '2021-02-22 15:11', NULL
-- EXEC usp_InsertHolding 'Steph ii Trd', 'RR.L', 28762, 100.8243, '2021-02-22 15:15', NULL
-- EXEC usp_InsertHolding 'Steph ii Trd', 'TUI.L', 5119, 376.9953, '2021-02-22 15:17', NULL
-- EXEC usp_InsertHolding 'Steph ii Trd', 'RCL', 2149, 80.8007, '2021-02-22 14:44', NULL
-- EXEC usp_InsertHolding 'Steph ii Trd', 'NCLH', 2100, 27.5428, '2021-02-22 14:51', NULL
-- EXEC usp_InsertHolding 'Steph ii Trd', 'WEB.AX', 14500, 5.42542, '2021-02-23 00:17', NULL
-- EXEC usp_InsertHolding 'Steph ii Trd', 'NCLH', 960, 21.1690, '2020-11-18 15:55', NULL
-- EXEC usp_InsertHolding 'Steph ii Trd', 'NCLH', 40, 21.08, '2020-11-18 15:58', NULL



-- EXEC usp_InsertHolding 'Steve AJB', 'TMPL.L', 5623,  708, '2020-05-13'
-- EXEC usp_InsertHolding 'Steve AJB', 'MKS.L', 33546,  89, '2020-05-11'
-- EXEC usp_InsertHolding 'Steve AJB', 'CCL', 2334,  17.44, '2020-06-03', '2020-06-11'
-- EXEC usp_InsertHolding 'Steve AJB', 'NCLH', 2322, 27.9475, '2021-02-22 14:55', NULL

-- EXEC usp_InsertHolding 'Steve HL ISA', 'NCLH', 3053, 17.27, '2020-05-27', '2020-06-11'
-- EXEC usp_InsertHolding 'Steve HL ISA', 'NCLH', 3053, 17.27, '2020-05-17', '2020-06-24 18:24'
-- EXEC usp_InsertHolding 'Steve HL ISA', 'CCL', 2667, 15.451, '2020-07-21 17:10', NULL
-- EXEC usp_InsertHolding 'Steve HL ISA', 'GME', 617, 119.986797, '2021-02-25 14:55', NULL
-- EXEC usp_InsertHolding 'Steve HL ISA', 'GME', 527, 124.422968, '2021-02-25 15:01', NULL

-- EXEC usp_InsertHolding 'Steve HL Trd', 'AAL', 2994, 12.35, '2020-05-27', '2020-06-11'
-- EXEC usp_InsertHolding 'Steve HL Trd', 'TUI.L', 4010, 490.93, '2020-06-05'
-- EXEC usp_InsertHolding 'Steve HL Trd', 'TUI.L', 3456, 95.745, '2021-01-21', NULL

-- EXEC usp_InsertHolding 'Steve ii Trd', 'QAN.AX', 15700,  3.63, '2020-04-28', '2020-06-12'
-- EXEC usp_InsertHolding 'Steve ii Trd', 'WEB.AX', 17000,  2.55, '2020-04-28', '2020-06-12'
-- EXEC usp_InsertHolding 'Steve ii Trd', 'WBC.AX', 2240,  15.07, '2020-05-13', '2020-06-12'
-- EXEC usp_InsertHolding 'Steve ii Trd', 'FLT.AX', 3500,  13.813, '2020-06-03', '2020-06-12'
-- EXEC usp_InsertHolding 'Steve ii Trd', 'WEB.AX', 20618, 3.0359, '2020-07-22 05:37', NULL
-- EXEC usp_InsertHolding 'Steve ii Trd', 'GME', 512, 54.17987, '2021-02-24 20:05', NULL
-- EXEC usp_InsertHolding 'Steve ii Trd', 'MAB.L', 9044, 227.2204, '2020-06-22 10:38', '2020-11-16 09:42'
-- EXEC usp_InsertHolding 'Steve ii Trd', 'JDW.L', 824, 11.3962, '2020-06-22 10:40', '2020-11-25 12:47'
-- EXEC usp_InsertHolding 'Steve ii Trd', 'RTN.L', 39894, 0.70936, '2020-06-22 10:34', '2020-12-02 10:50'
-- EXEC usp_InsertHolding 'Steve ii Trd', 'AML.L', 1078, 1854.724, '2020-12-24 09:22', NULL
-- EXEC usp_InsertHolding 'Steve ii Trd', 'IAG.L', 10911, 166.3459, '2020-12-24 09:28', NULL
-- EXEC usp_InsertHolding 'Steve ii Trd', 'CCL.L', 2576, 1203.112, '2020-11-16 12:56', NULL
-- EXEC usp_InsertHolding 'Steve ii Trd', 'ARB.L', 11459, 261.7805, '2021-03-01 11:25', NULL
GO

CREATE OR ALTER PROCEDURE usp_GetHoldings
AS
BEGIN
  SELECT
    h.HoldingID,
    a.ShortName as [AccountName],
    i.Symbol as [Symbol],
    h.PurchaseDate,
    h.NoUnits,
    h.PurchasePricePerUnit,
    ISNULL(h.ActualExchangeRate, dbo.fn_GetExchangeRate(i.Currency, h.PurchaseDate)) as [PurchaseExchangeRate],
    h.NoUnits * h.PurchasePricePerUnit / ISNULL(h.ActualExchangeRate, dbo.fn_GetExchangeRate(i.Currency, h.PurchaseDate)) as [BookCostGBP],
    h.SoldDate
  FROM
    Holding h
    INNER JOIN Instrument i
      ON h.InstrumentID = i.InstrumentID
    INNER JOIN Account a
      ON a.AccountID = h.AccountID
  ORDER BY
    i.Symbol,
    h.PurchaseDate,
    a.ShortName,
    h.NoUnits,
    h.PurchasePricePerUnit,
    h.SoldDate
END
GO
GRANT EXECUTE ON usp_GetHoldings TO WebApp_Role
GO

CREATE OR ALTER PROCEDURE usp_GetHoldingsHistory
AS
BEGIN
  DECLARE @Dates TABLE (InstrumentID int, DT datetime)

  INSERT @Dates
  SELECT
    InstrumentID,
    PurchaseDate as [DT]
  FROM
    Holding
  UNION
  SELECT
    InstrumentID,
    SoldDate as [DT]
  FROM
    Holding
  WHERE
    SoldDate IS NOT NULL
  ORDER BY
    DT

  SELECT
    i.Symbol,
    d.DT,
    ISNULL((SELECT SUM(NoUnits) FROM Holding p WHERE p.InstrumentID = d.InstrumentID AND p.PurchaseDate <= d.DT), 0) -
    ISNULL((SELECT SUM(NoUnits) FROM Holding s WHERE s.InstrumentID = d.InstrumentID AND s.SoldDate <= d.DT), 0) as [TotalUnits],
    ISNULL((SELECT SUM(NoUnits*PurchasePricePerUnit) FROM Holding p WHERE p.InstrumentID = d.InstrumentID AND p.PurchaseDate <= d.DT), 0) -
    ISNULL((SELECT SUM(NoUnits*PurchasePricePerUnit) FROM Holding s WHERE s.InstrumentID = d.InstrumentID AND s.SoldDate <= d.DT), 0) as [TotalCost]
  FROM
    @Dates d
    INNER JOIN Instrument i
      ON i.InstrumentID = d.InstrumentID
  ORDER BY
    d.InstrumentID,
    d.DT
END
GO
GRANT EXECUTE ON usp_GetHoldingsHistory TO WebApp_Role
GO

/*
CREATE PROCEDURE usp_DeleteHolding (@HoldingID int)
AS
BEGIN
  DELETE Holding WHERE HoldingID = @HoldingID
  SELECT @@ROWCOUNT AS [RecordsDeleted]
END
GO
GRANT EXECUTE ON usp_DeleteHolding TO WebApp_Role
GO
*/
CREATE OR ALTER PROCEDURE usp_SoldHolding (@HoldingID int, @SoldDate datetime, @SoldCurrency varchar(8), @SoldProceeds numeric(36, 12))
AS
BEGIN
  UPDATE
	Holding
  SET
	SoldDate = @SoldDate,
	SoldCurrencyID = (SELECT InstrumentID FROM Instrument WHERE Symbol = @SoldCurrency),
	SoldProceeds = @SoldProceeds
  WHERE
    HoldingID = @HoldingID

  SELECT @@ROWCOUNT AS [RecordsUpdated]
END
GO
GRANT EXECUTE ON usp_SoldHolding TO WebApp_Role
GO

CREATE OR ALTER PROCEDURE usp_SetAccountCashValue (@AccountName varchar(20), @Currency varchar(8), @Value numeric(36, 12))
AS
BEGIN
  DECLARE @AccountID int
  DECLARE @CurrencyID int

  SELECT @AccountID = AccountID FROM Account WHERE ShortName = @AccountName
  SELECT @CurrencyID = InstrumentID FROM Instrument WHERE Symbol = @Currency


  IF EXISTS (SELECT NULL FROM Holding WHERE AccountID = @AccountID AND InstrumentID = @CurrencyID)
  BEGIN
    UPDATE
	  Holding
	SET
	  NoUnits = @Value
	WHERE
	  AccountID = @AccountID
	  AND InstrumentID = @CurrencyID
  END
  ELSE
  BEGIN
    INSERT Holding (
	  AccountID,
      InstrumentID,
      NoUnits,
      PurchasePricePerUnit,
      PurchaseDate)
    VALUES (
      @AccountID,
	  @CurrencyID,
	  @Value,
	  1.0,
	  '2020-01-01')
  END

  SELECT
    h.HoldingID,
    a.ShortName as [AccountName],
    i.Symbol as [Symbol],
    h.PurchaseDate,
    h.NoUnits,
    h.PurchasePricePerUnit,
    ISNULL(h.ActualExchangeRate, dbo.fn_GetExchangeRate(i.Currency, h.PurchaseDate)) as [PurchaseExchangeRate],
    h.NoUnits * h.PurchasePricePerUnit / ISNULL(h.ActualExchangeRate, dbo.fn_GetExchangeRate(i.Currency, h.PurchaseDate)) as [BookCostGBP],
    h.SoldDate
  FROM
    Holding h
    INNER JOIN Instrument i
      ON h.InstrumentID = i.InstrumentID
    INNER JOIN Account a
      ON a.AccountID = h.AccountID
  WHERE
	a.AccountID = @AccountID
	AND h.InstrumentID = @CurrencyID
END
GO
GRANT EXECUTE ON usp_SetAccountCashValue TO WebApp_Role
GO

CREATE OR ALTER PROCEDURE usp_SwapDisplayOrder (@Symbol1 varchar(8), @Symbol2 varchar(8))
AS
BEGIN
  DECLARE @OldDisplayOrder1 TINYINT
  DECLARE @OldDisplayOrder2 TINYINT
  
  SELECT @OldDisplayOrder1 = DisplayOrder FROM Instrument WHERE Symbol = @Symbol1
  SELECT @OldDisplayOrder2 = DisplayOrder FROM Instrument WHERE Symbol = @Symbol2
  
  UPDATE
    Instrument
  SET
    DisplayOrder = CASE
                     WHEN Symbol = @Symbol1 THEN @OldDisplayOrder2
                     WHEN Symbol = @Symbol2 THEN @OldDisplayOrder1
                   END
  WHERE
    Symbol IN (@Symbol1, @Symbol2)

  SELECT
    @Symbol1 as [Symbol1],
    @OldDisplayOrder2 as [Symbol1NewDisplayOrder],
    @Symbol2 as [Symbol2],
    @OldDisplayOrder1 as [Symbol2NewDisplayOrder]
END
GO
GRANT EXECUTE ON usp_SwapDisplayOrder TO WebApp_Role
GO

CREATE OR ALTER PROCEDURE usp_SetTotalHoldingsValue (@TotalValueGBP money)
AS
BEGIN
	DECLARE @Rounded INT = CONVERT(int, FLOOR(@TotalValueGBP))
	DECLARE @EndOfPreviousWeek DATE = DATEADD(day, 1 - DATEPART(weekday, CURRENT_TIMESTAMP), convert(date, CURRENT_TIMESTAMP))
	DECLARE @PreviousDay DATE = DATEADD(day, -1, CONVERT(DATE, CURRENT_TIMESTAMP))

	--Maintain the AllDays table
	;WITH cteAllDays AS
     (SELECT CONVERT(datetime, CONVERT(date, MIN(PurchaseDate))) as DT FROM Holding
      UNION ALL
      SELECT DATEADD(day, 1, DT)
        FROM cteAllDays
       WHERE DATEADD(day, 1, DT) <= CONVERT(date, CURRENT_TIMESTAMP)
     )
	INSERT AllDays (DT) SELECT DT FROM cteAllDays c WHERE c.DT > (SELECT MAX(DT) FROM AllDays) AND c.DT <= CURRENT_TIMESTAMP OPTION (MAXRECURSION 20000)


	IF DATENAME(WEEKDAY, CURRENT_TIMESTAMP) NOT IN ('Saturday', 'Sunday')
	BEGIN
		IF EXISTS (SELECT NULL FROM TotalHoldingsHistory_Daily WHERE HistoryDate = CONVERT(date, CURRENT_TIMESTAMP))
		BEGIN
			UPDATE
				TotalHoldingsHistory_Daily
			SET
				Low = CASE WHEN @Rounded < Low THEN @Rounded ELSE Low END,
				High = CASE WHEN @Rounded > High THEN @Rounded ELSE High END,
				[Close] = @Rounded
			WHERE
				HistoryDate = CONVERT(date, CURRENT_TIMESTAMP)
		END
		ELSE
		BEGIN
			INSERT TotalHoldingsHistory_Daily (HistoryDate, [Open], Low, High, [Close]) VALUES (CONVERT(date, CURRENT_TIMESTAMP), @Rounded, @Rounded, @Rounded, @Rounded)
		END
	END

	SELECT
		pw.HistoryDate as [PreviousWeekDate],
		pw.[Close] as [PreviousWeekClose],
		pd.HistoryDate as [PreviousDay],
		pd.[Close] as [PreviousClose]
	FROM
		(SELECT TOP 1
			*
		FROM
			TotalHoldingsHistory_Daily
		WHERE
			HistoryDate <= @EndOfPreviousWeek
		ORDER BY
			HistoryDate DESC) as [pw],
		(SELECT TOP 1
			*
		FROM
			TotalHoldingsHistory_Daily
		WHERE
			HistoryDate <= @PreviousDay
		ORDER BY
			HistoryDate DESC) as [pd]
END
GO
GRANT EXECUTE ON usp_SetTotalHoldingsValue TO WebApp_Role
GO

CREATE OR ALTER PROCEDURE usp_GetTotalHoldingsHistory
AS
BEGIN
	SELECT
		h.HistoryDate,
		h.[Open],
		h.[High],
		h.[Low],
		h.[Close]
	FROM
		TotalHoldingsHistory_Daily h
	ORDER BY
		HistoryDate
END
GO
GRANT EXECUTE ON usp_GetTotalHoldingsHistory TO WebApp_Role
GO

CREATE OR ALTER VIEW vHolding
AS
  SELECT
    h.HoldingID,
	i.InstrumentID,
    a.ShortName as [AccountName],
    i.Symbol,
    i.FullName as [InstrumentName],
    h.PurchaseDate,
    h.NoUnits,
    h.PurchasePricePerUnit,
    h.ActualExchangeRate,
    h.SoldDate
  FROM
    Holding h
    INNER JOIN Instrument i
      ON i.InstrumentId = h.InstrumentId
    INNER JOIN Account a
      ON a.AccountID = h.AccountID
GO

CREATE OR ALTER VIEW vCashBalances
AS
SELECT
	a.AccountID,
	h.HoldingID,
	a.ShortName as [AccoutName],
	i.Symbol,
	h.NoUnits,
	--i.DisplayName as [InstrumentName],
	--i.CurrentPrice,
	--h.NoUnits,
	h.NoUnits * i.CurrentPrice as [Balance]
FROM
	Holding h
	INNER JOIN Instrument i
		ON i.InstrumentID = h.InstrumentID
	INNER JOIN Account a
		ON a.AccountID = h.AccountID
WHERE
	i.InstrumentType = 'CURRENCY'
	AND h.SoldDate IS NULL
GO

CREATE OR ALTER VIEW vErroneousPrices_Daily
AS
SELECT
  i.InstrumentID,
  i.Symbol,
  i.FullName,
  p.HistoryDT as [PreviousHistoryDT],
  d1.HistoryDT as [HistoryDT],
  n.HistoryDT as [NextHistoryDT],
  p.OpenPrice as [PreviousOpen],
  d1.OpenPrice as [Open],
  n.OpenPrice as [NextOpen],
  p.HighPrice as [PreviousHigh],
  d1.HighPrice as [High],
  n.HighPrice as [NextHigh],
  p.LowPrice as [PreviousLow],
  d1.LowPrice as [Low],
  n.LowPrice as [NextLow],
  p.ClosePrice as [PreviousClose],
  d1.ClosePrice as [Close],
  n.ClosePrice as [NextClose]
FROM
  Instrument i
  INNER JOIN InstrumentHistory_Daily d1
    ON d1.InstrumentID = i.InstrumentID
  INNER JOIN InstrumentHistory_Daily p
    ON p.InstrumentID = d1.InstrumentID
   AND p.HistoryDT = (SELECT MAX(HistoryDT) FROM InstrumentHistory_Daily WHERE InstrumentID = d1.InstrumentID AND HistoryDT < d1.HistoryDT)
  INNER JOIN InstrumentHistory_Daily n
    ON n.InstrumentID = d1.InstrumentID
   AND n.HistoryDT = (SELECT MIN(HistoryDT) FROM InstrumentHistory_Daily WHERE InstrumentID = d1.InstrumentID AND HistoryDT > d1.HistoryDT) 
WHERE
  (p.OpenPrice/CASE WHEN d1.OpenPrice = 0 THEN 0.0000001 ELSE d1.OpenPrice END > 90 AND n.OpenPrice/CASE WHEN d1.OpenPrice = 0 THEN 0.0000001 ELSE d1.OpenPrice END > 90)
  OR (p.HighPrice/CASE WHEN d1.HighPrice = 0 THEN 0.0000001 ELSE d1.HighPrice END > 90 AND n.HighPrice/CASE WHEN d1.HighPrice = 0 THEN 0.0000001 ELSE d1.HighPrice END > 90)
  OR (p.LowPrice/CASE WHEN d1.LowPrice = 0 THEN 0.0000001 ELSE d1.LowPrice END > 90 AND n.LowPrice/CASE WHEN d1.LowPrice = 0 THEN 0.0000001 ELSE d1.LowPrice END > 90)
  OR (p.ClosePrice/CASE WHEN d1.ClosePrice = 0 THEN 0.0000001 ELSE d1.ClosePrice END > 90 AND n.ClosePrice/CASE WHEN d1.ClosePrice = 0 THEN 0.0000001 ELSE d1.ClosePrice END > 90)
GO

CREATE OR ALTER VIEW vErroneousPrices_Intraday
AS
SELECT
  i.InstrumentID,
  i.Symbol,
  i.FullName,
  p.HistoryDT as [PreviousHistoryDT],
  d1.HistoryDT as [HistoryDT],
  n.HistoryDT as [NextHistoryDT],
  p.OpenPrice as [PreviousOpen],
  d1.OpenPrice as [Open],
  n.OpenPrice as [NextOpen],
  p.HighPrice as [PreviousHigh],
  d1.HighPrice as [High],
  n.HighPrice as [NextHigh],
  p.LowPrice as [PreviousLow],
  d1.LowPrice as [Low],
  n.LowPrice as [NextLow],
  p.ClosePrice as [PreviousClose],
  d1.ClosePrice as [Close],
  n.ClosePrice as [NextClose]
FROM
  Instrument i
  INNER JOIN InstrumentHistory_Intraday d1
    ON d1.InstrumentID = i.InstrumentID
  INNER JOIN InstrumentHistory_Intraday p
    ON p.InstrumentID = d1.InstrumentID
   AND p.HistoryDT = (SELECT MAX(HistoryDT) FROM InstrumentHistory_Daily WHERE InstrumentID = d1.InstrumentID AND HistoryDT < d1.HistoryDT)
  INNER JOIN InstrumentHistory_Intraday n
    ON n.InstrumentID = d1.InstrumentID
   AND n.HistoryDT = (SELECT MIN(HistoryDT) FROM InstrumentHistory_Daily WHERE InstrumentID = d1.InstrumentID AND HistoryDT > d1.HistoryDT) 
WHERE
  (p.OpenPrice/CASE WHEN d1.OpenPrice = 0 THEN 0.0000001 ELSE d1.OpenPrice END > 90 AND n.OpenPrice/CASE WHEN d1.OpenPrice = 0 THEN 0.0000001 ELSE d1.OpenPrice END > 90)
  OR (p.HighPrice/CASE WHEN d1.HighPrice = 0 THEN 0.0000001 ELSE d1.HighPrice END > 90 AND n.HighPrice/CASE WHEN d1.HighPrice = 0 THEN 0.0000001 ELSE d1.HighPrice END > 90)
  OR (p.LowPrice/CASE WHEN d1.LowPrice = 0 THEN 0.0000001 ELSE d1.LowPrice END > 90 AND n.LowPrice/CASE WHEN d1.LowPrice = 0 THEN 0.0000001 ELSE d1.LowPrice END > 90)
  OR (p.ClosePrice/CASE WHEN d1.ClosePrice = 0 THEN 0.0000001 ELSE d1.ClosePrice END > 90 AND n.ClosePrice/CASE WHEN d1.ClosePrice = 0 THEN 0.0000001 ELSE d1.ClosePrice END > 90)
GO

CREATE OR ALTER VIEW vDataQuality_Prices
AS
SELECT
  i.InstrumentID,
  i.Symbol,
  i.FullName,
  p.HistoryDT as [PreviousHistoryDT],
  d1.HistoryDT as [HistoryDT],
  n.HistoryDT as [NextHistoryDT],
  p.OpenPrice as [PreviousOpen],
  d1.OpenPrice as [Open],
  n.OpenPrice as [NextOpen],
  p.HighPrice as [PreviousHigh],
  d1.HighPrice as [High],
  n.HighPrice as [NextHigh],
  p.LowPrice as [PreviousLow],
  d1.LowPrice as [Low],
  n.LowPrice as [NextLow],
  p.ClosePrice as [PreviousClose],
  d1.ClosePrice as [Close],
  n.ClosePrice as [NextClose]
FROM
  Instrument i
  INNER JOIN InstrumentHistory_Daily d1
    ON d1.InstrumentID = i.InstrumentID
  INNER JOIN InstrumentHistory_Daily p
    ON p.InstrumentID = d1.InstrumentID
   AND p.HistoryDT = (SELECT MAX(HistoryDT) FROM InstrumentHistory_Daily WHERE InstrumentID = d1.InstrumentID AND HistoryDT < d1.HistoryDT)
  INNER JOIN InstrumentHistory_Daily n
    ON n.InstrumentID = d1.InstrumentID
   AND n.HistoryDT = (SELECT MIN(HistoryDT) FROM InstrumentHistory_Daily WHERE InstrumentID = d1.InstrumentID AND HistoryDT > d1.HistoryDT) 
GO

CREATE OR ALTER VIEW vHoldingValueHistory
AS
SELECT
	hist.HoldingID,
	a.ShortName as [AccountName],
	i.Symbol,
	i.Currency,
	i.FullName as [InstrumentName],
	h.PurchaseDate,
	h.PurchasePricePerUnit * h.NoUnits as [CostBase],
	(h.PurchasePricePerUnit * h.NoUnits) / dbo.fn_GetExchangeRate(Currency, DT) as [CostBaseGBP],
	h.SoldDate,
	DT as [ValuationDate],
	h.NoUnits * dbo.fn_GetPriceAtDate(h.InstrumentID, DT) as [Value],
	(h.NoUnits * dbo.fn_GetPriceAtDate(h.InstrumentID, DT) / dbo.fn_GetExchangeRate(Currency, DT)) as [ValueGBP],
	h.NoUnits * dbo.fn_GetPriceAtDate(h.InstrumentID, DT) - (h.PurchasePricePerUnit * h.NoUnits) as [Gain],
	(h.NoUnits * dbo.fn_GetPriceAtDate(h.InstrumentID, DT) - (h.PurchasePricePerUnit * h.NoUnits)) / dbo.fn_GetExchangeRate(Currency, DT) as [GainGBP]
FROM (
	SELECT
		HoldingID,
		PurchaseDate as DT
	FROM
		Holding
	UNION
	SELECT
		HoldingID,
		ISNULL(SoldDate, CURRENT_TIMESTAMP) as DT
	FROM
		Holding
	UNION
	SELECT
		HoldingID,
		DT
	FROM
		Holding h
		INNER JOIN allDays d
			ON d.DT >= h.PurchaseDate
			AND d.DT <= ISNULL(h.SoldDate, CURRENT_TIMESTAMP)) as hist
	INNER JOIN Holding h
		ON h.HoldingID = hist.HoldingID
	INNER JOIN Account a
		ON a.AccountID = h.AccountID
	INNER JOIN Instrument i
		ON i.InstrumentID = h.InstrumentID
GO

CREATE OR ALTER VIEW vTradeLedger
AS
SELECT
	ah.Name + ' - ' + CASE WHEN a.IsTaxable = 0 THEN 'Non-' ELSE '' END + 'Taxable' as [TaxBucket],
	a.ShortName as [AccountName],
	a.IsTaxable,
	i.Symbol,
	--ah.Name + ' - ' + CASE WHEN a.IsTaxable = 0 THEN 'Non-' ELSE '' END + 'Taxable' + '|' + i.Symbol as [InvestmentGroup],
	DENSE_RANK() OVER (PARTITION BY a.AccountHolderID, a.IsTaxable, l.InstrumentID ORDER BY TradeDT) as [InvestmentPoolOrder],
	i.FullName as [Instrument],
	i.DisplayName as [InstrumentDisplayName],
	i.Currency as [InstrumentCurrency],
	--l.[TradeLedgerID],
	l.[InstrumentID],
	--l.[AccountID],
	l.[TradeDT],
	l.[ActionType],
	l.[NoUnits],
	--l.[TradeCurrencyID],
	--l.[ActualExchangeRate],
	--l.[EstimatedExchangeRate],
	--l.[TradeValue],
	l.[TradeValueGBP],
	l.[Notes]
FROM
	TradeLedger l
	INNER JOIN Account a
		ON a.AccountID = l.AccountID
	INNER JOIN AccountHolder ah
		ON ah.AccountHolderID = a.AccountHolderID
	INNER JOIN Instrument i
		ON i.InstrumentID = l.InstrumentID
	INNER JOIN Instrument tc
		ON tc.InstrumentID = l.TradeCurrencyID
GO

CREATE OR ALTER VIEW vTradeHistory
AS
WITH cteInvestmentPoolHistory AS (
	SELECT
		l.*,
		l.NoUnits as [NewPoolTotalUnits],
		l.TradeValueGBP as [NewPoolBaseCostGBP],
		CAST(0 as MONEY) as [RealisedGainGBP]
	FROM
		vTradeLedger l
	WHERE
		InvestmentPoolOrder = 1
	UNION ALL
	SELECT
		l.*,
		CAST(IIF(l.ActionType = 'Sell', c.NewPoolTotalUnits - l.NoUnits, c.NewPoolTotalUnits + l.NoUnits) as NUMERIC(36, 12)) as [NewPoolTotalUnits],
		CASE l.ActionType
			WHEN 'Sell' THEN CAST((1 - (l.NoUnits / c.NewPoolTotalUnits)) * c.NewPoolBaseCostGBP as MONEY) --The proportion of units remaining * previous avg cost base
			WHEN 'Transfer' THEN IIF(l.NoUnits < 0, c.NewPoolBaseCostGBP - l.TradeValueGBP, c.NewPoolBaseCostGBP + l.TradeValueGBP) --Invert TradeValueGBP for transfers OUT
			ELSE c.NewPoolBaseCostGBP + l.TradeValueGBP
		END as [NewPoolBaseCostGBP],
		CASE
			WHEN l.ActionType = 'Sell' THEN CAST(l.TradeValueGBP - ((l.NoUnits / c.NewPoolTotalUnits) * c.NewPoolBaseCostGBP) as MONEY) --Trade Value - (The proportion of units sold * previous avg cost base)
			ELSE 0
		END as [RealisedGainGBP]
	FROM
		vTradeLedger l
		INNER JOIN cteInvestmentPoolHistory c
			ON c.TaxBucket = l.TaxBucket
			AND c.Symbol = l.Symbol
			AND c.InvestmentPoolOrder = l.InvestmentPoolOrder - 1
	)
SELECT
	*,
	CAST(IIF(EXISTS (SELECT 1 FROM cteInvestmentPoolHistory n WHERE n.TaxBucket = c.TaxBucket AND n.Instrument = c.Instrument AND n.InvestmentPoolOrder > c.InvestmentPoolOrder), 0, 1) as BIT) as [IsFinalPosition]
FROM
	cteInvestmentPoolHistory c
GO

/*
SELECT
	Symbol,
	Currency,
	ValuationDate,
	SUM(CostBase) as [TotalCostBase],
	SUM(Value) as [TotalValue],
	SUM(Gain) as [Gain]
FROM vHoldingValueHistory
--WHERE HoldingID = 169
WHERE Symbol = 'LMI3.L'
GROUP BY
	Symbol,
	Currency,
	ValuationDate
ORDER BY Symbol, ValuationDate

SELECT
	ValuationDate,
	SUM(CostBaseGBP) as CostBase,
	SUM(ValueGBP) as Value,
	SUM(GainGBP) as Gain
FROM vHoldingValueHistory
WHERE ValuationDate >= '2024-02-01'
AND CONVERT(varchar(30), ValuationDate, 120) LIKE '%00:00:00%'
GROUP BY
	ValuationDate
ORDER BY ValuationDate

SELECT
	--Currency COLLATE Latin1_General_CS_AS,
	ValuationDate,
	--dbo.fn_GetExchangeRate(Currency, ValuationDate),
	--CostBase / dbo.fn_GetExchangeRate(Currency, ValuationDate) as CostBaseGBP,
	SUM(CostBase) as [TotalCostBase],
	SUM(CostBase) / dbo.fn_GetExchangeRate(Currency, ValuationDate) as [TotalCostBaseGBP],
	SUM(Value) as [TotalValue],
	SUM(Value) / dbo.fn_GetExchangeRate(Currency, ValuationDate) as [TotalValueGBP],
	SUM(Gain) / dbo.fn_GetExchangeRate(Currency, ValuationDate) as [Gain]
FROM vHoldingValueHistory
WHERE ValuationDate = '2024-02-24 00:00:00'
GROUP BY ValuationDate

select * from Instrument

select * from InstrumentHistory_Daily
select * from InstrumentHistory_Intraday

select * from InstrumentHistory_Intraday where InstrumentID = 18 order by HistoryDT desc

--Delete daily prices that are 90% less than previous and next daily prices
DELETE d1
select *
FROM
  Instrument i
  INNER JOIN InstrumentHistory_Daily d1
    ON d1.InstrumentID = i.InstrumentID
  INNER JOIN InstrumentHistory_Daily p
    ON p.InstrumentID = d1.InstrumentID
   AND p.HistoryDT = (SELECT MAX(HistoryDT) FROM InstrumentHistory_Daily WHERE InstrumentID = d1.InstrumentID AND HistoryDT < d1.HistoryDT)
  INNER JOIN InstrumentHistory_Daily n
    ON n.InstrumentID = d1.InstrumentID
   AND n.HistoryDT = (SELECT MIN(HistoryDT) FROM InstrumentHistory_Daily WHERE InstrumentID = d1.InstrumentID AND HistoryDT > d1.HistoryDT) 
WHERE
  (p.ClosePrice/d1.ClosePrice > 90
  AND n.ClosePrice/d1.ClosePrice > 90)
  OR
  (p.OpenPrice/d1.OpenPrice > 90
  AND n.OpenPrice/d1.OpenPrice > 90)
  OR
  (p.HighPrice/d1.HighPrice > 90
  AND n.HighPrice/d1.HighPrice > 90)
  OR
  (p.LowPrice/d1.LowPrice > 90
  AND n.LowPrice/d1.LowPrice > 90)

SELECT *
FROM
  Instrument i
  INNER JOIN InstrumentHistory_Daily d1
    ON d1.InstrumentID = i.InstrumentID
  INNER JOIN InstrumentHistory_Daily p
    ON p.InstrumentID = d1.InstrumentID
   AND p.HistoryDT = (SELECT MAX(HistoryDT) FROM InstrumentHistory_Daily WHERE InstrumentID = d1.InstrumentID AND HistoryDT < d1.HistoryDT)
  INNER JOIN InstrumentHistory_Daily n
    ON n.InstrumentID = d1.InstrumentID
   AND n.HistoryDT = (SELECT MIN(HistoryDT) FROM InstrumentHistory_Daily WHERE InstrumentID = d1.InstrumentID AND HistoryDT > d1.HistoryDT) 
WHERE
  p.ClosePrice/d1.ClosePrice > 90
  AND n.ClosePrice/d1.ClosePrice > 90


select * from Instrument i inner join InstrumentHistory_Daily d on d.InstrumentID = i.InstrumentID
where i.Symbol = 'IAG.L' and d.HistoryDT between '2020-10-05' and '2020-10-07' order by d.HistoryDT

*/
