Custom Price Levels and Averages
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © drmch2020

//@version=5
indicator("Custom Price Levels and Averages", shorttitle="CPLA", overlay=true)

// Input parameters
inputTimeframe = input("D", title="Input Timeframe")
distancePercentageUp = input(1.5, title="Distance Percentage Up")
distancePercentageDown = input(1.5, title="Distance Percentage Down")
position = input(100, title="Position (USD)")
increaseFactor = input(1.5, title="Increase Factor")

// Color customization
colorPriceA = input(color.white, title="Color Price A")
colorPriceB = input(color.white, title="Color Price B")
colorPriceC = input(color.white, title="Color Price C")
colorAvgPriceUp = input(color.white, title="Color Avg Price Up")
colorPriceX = input(color.white, title="Color Price X")
colorPriceY = input(color.white, title="Color Price Y")
colorPriceZ = input(color.white, title="Color Price Z")
colorAvgPriceDown = input(color.white, title="Color Avg Price Down")

// Function to calculate the average price
calcAvgPrice(priceA, priceB, priceC, position, increaseFactor) =>
    (priceA * position + priceB * (position * increaseFactor) + priceC * position * increaseFactor * increaseFactor) /  (position + position * increaseFactor + position * increaseFactor * increaseFactor)

// Calculate last candle close price
lastPrice = request.security(syminfo.tickerid, inputTimeframe, close)

// Calculate prices
priceA = lastPrice * (1 + distancePercentageUp / 100)
priceB = priceA * (1 + distancePercentageUp / 100)
priceC = priceB * (1 + distancePercentageUp / 100)
priceX = lastPrice * (1 - distancePercentageDown / 100)
priceY = priceX * (1 - distancePercentageDown / 100)
priceZ = priceY * (1 - distancePercentageDown / 100)

// Calculate average prices
avgPriceUp = calcAvgPrice(priceA, priceB, priceC, position, increaseFactor)
avgPriceDown = calcAvgPrice(priceX, priceY, priceZ, position, increaseFactor)

// Plot horizontal lines
plot(priceA, color=colorPriceA, linewidth=1, title="Price A")
plot(priceB, color=colorPriceB, linewidth=1, title="Price B")
plot(priceC, color=colorPriceC, linewidth=1, title="Price C")
plot(avgPriceUp, color=colorAvgPriceUp, linewidth=1, title="Avg Price Up")
plot(priceX, color=colorPriceX, linewidth=1, title="Price X")
plot(priceY, color=colorPriceY, linewidth=1, title="Price Y")
plot(priceZ, color=colorPriceZ, linewidth=1, title="Price Z")
plot(avgPriceDown, color=colorAvgPriceDown, linewidth=1, title="Avg Price Down")

