Calculating the pence per kwh stored in my battery

I have just installed solar battery storage which is linked to octopus agile tariff and solar panels, so can charge from either. I’m trying to get the processing right to calculate the current p/kwh of the energy stored in the battery so I can determine if its better to charge or discharge based on grid prices.
Complicating the matter is that each 30mins the grid price changes and the battery also soaks up excess solar which has a cost of 0p.
Has anyone tackled this already, I’ve been tweaking for 3 days and my processing never seems to get it right. The p/kwh keeps going up too fast…
I can share my process flows if needed, but wondered if anyone already has the answer?!

Interesting question, it’s not something I’ve done but I can imagine it might be quite complicated to get right with input processing.

Is it a matter of calculating a cumulative cost of energy stored in the battery value?

solar_kwh_inc =  (solar_power x timestep) / 3600000
agile_kwh_inc =  (agile_charge_power x timestep) / 3600000
Value of electric in battery = Integration of: 
((solar_kwh_inc  x solar_price) + (agile_kwh_inc x agile_price))

unit cost of electric in battery = Value of electric in battery / state of charge in kwh

If you are treating the cost of the solar power as zero then

agile_kwh_inc =  (agile_charge_power x timestep) / 3600000
Value of electric in battery = Integration of:
(agile_kwh_inc x agile_price))
unit cost of electric in battery = Value of electric in battery / state of charge in kwh

Next we would need to subtract the value of any discharge and perhaps account for battery wear?

Or perhaps it is easier to first try and calculate the number of kWh that are stored in the battery from solar vs agile and then just multiply the result of this with the unit costs… that would be a bit cleaner?

Then subtracting the amount discharged from the recorded stored solar and agile:

solar_discharge_kwh = battery_discharge_kwh * (stored_solar_kwh / stored_total_kwh)
agile_discharge_kwh = battery_discharge_kwh * (stored_agile_kwh / stored_total_kwh)
stored_solar_kwh -= solar_discharge_kwh 
stored_agile_kwh -= agile_discharge_kwh 

I think this would need a number of new input processors to achieve…