package finance

// TickToOHLCV agrega datos de ticks en velas OHLCV segun un intervalo en segundos.
// prices, volumes y timestamps deben tener la misma longitud.
// timestamps son unix seconds. intervalSecs define el ancho de cada vela.
// Retorna slices de open, high, low, close, volume para cada vela generada.
func TickToOHLCV(prices, volumes []float64, timestamps []int64, intervalSecs int64) (open, high, low, close, vol []float64) {
	n := len(prices)
	if n == 0 || intervalSecs <= 0 {
		return
	}
	bucketStart := timestamps[0] - (timestamps[0] % intervalSecs)
	o := prices[0]
	h := prices[0]
	l := prices[0]
	c := prices[0]
	v := volumes[0]

	for i := 1; i < n; i++ {
		currentBucket := timestamps[i] - (timestamps[i] % intervalSecs)
		if currentBucket != bucketStart {
			// Cerrar la vela anterior
			open = append(open, o)
			high = append(high, h)
			low = append(low, l)
			close = append(close, c)
			vol = append(vol, v)
			// Nueva vela
			bucketStart = currentBucket
			o = prices[i]
			h = prices[i]
			l = prices[i]
			c = prices[i]
			v = volumes[i]
		} else {
			if prices[i] > h {
				h = prices[i]
			}
			if prices[i] < l {
				l = prices[i]
			}
			c = prices[i]
			v += volumes[i]
		}
	}
	// Cerrar ultima vela
	open = append(open, o)
	high = append(high, h)
	low = append(low, l)
	close = append(close, c)
	vol = append(vol, v)
	return
}
