Calculating values for Grid Consumption and Return to Grid

Hi, I have a SMA inverter which just provides solar energy generated in kWh (its cumulitive for its lifetime like 38,932kWh) and i also have a home energy monitor which is monitoring actual usage (whether supplied by solar or grid)

I have created the below sensors in template and they show up (tick for this Noob), however my issue is that for instance today i exported 15kWh by the time the sun went down, well now the Net Solar is decreasing from 15 till it finally hits zero… and no doubt tomorrow, the Net Power will start at negative 15 (showing 0 as i didnt use any power during the day) which it will work its way up from before it starts to register…

i need the sensors to only increment positive and not count backwards i guess… any help???

template:
  - sensor:
      - name: "Net Power"
        unit_of_measurement: "kWh"
        unique_id: sensor.netpower
        device_class: energy
        state_class: total_increasing
        state: >
          {% set usage = states('sensor.power_meter_electric_consumption_kwh') | float %}
          {% set generation = states('sensor.sb6_0_1av_41_598_pv_gen_meter') | float %}
          {% if (usage - generation + 37820) < 0 %}
             0
          {% else %}
             {{ (usage - generation + 37820) | round(4) }}
          {% endif %}

      - name: "Net Solar"
        unit_of_measurement: "kWh"
        unique_id: sensor.netsolar
        device_class: energy
        state_class: total_increasing
        state: >
          {% set usage = states('sensor.power_meter_electric_consumption_kwh') | float %}
          {% set generation = states('sensor.sb6_0_1av_41_598_pv_gen_meter') | float %}
          {% if (usage - generation + 37820) < 0 %}
            {{ (0 - (usage - generation + 37820)) | round(4) }}
          {% else %}
             0
          {% endif %}

Hey!
Have you solved the problem? I’m new to HA and I have the same issue. Don’t know how to calculate correct values!

Thank you.

Yeah I think so, so long ago now I’d have to look at it to send you the code