Run during cheapest hour afternoon

this is how I run my bbqkees controlled warmwater boiler during cheap hours in the afternoon (dynamic electricity contract).
Most of it is copy pasted from elsewhere which I can’t find anymore.
First have the nordpool integration up and running.
Then create this sensor:
(in sensor.yaml , I use file editor)

  - platform: template
    sensors:
      cheapest_hours_energy_tomorrow:
        device_class: timestamp
        friendly_name: Cheapest Mittag sequential electricity hours
        value_template: >
          {%- set numberOfSequentialHours = 1 -%}
          {%- set lastHour = 17 -%}
          {%- set firstHour = 11 -%}

          {%- if state_attr('sensor.nordpool_kwh_nl_eur_3_09_0', 'tomorrow_valid') == true -%}
            {%- set ns = namespace(counter=0, list=[], cheapestHour=today_at("00:00") + timedelta( hours = (24)), cheapestPrice=999.00) -%}
            {%- for i in range(firstHour + numberOfSequentialHours, lastHour+1) -%}
              {%- set ns.counter = 0.0 -%}
              {%- for j in range(i-numberOfSequentialHours, i) -%}
                {%- set ns.counter = ns.counter + state_attr('sensor.nordpool_kwh_nl_eur_3_09_0', 'tomorrow')[j] -%}
              {%- endfor -%}
              {%- set ns.list = ns.list + [ns.counter] -%}
              {%- if ns.counter < ns.cheapestPrice -%}
                {%- set ns.cheapestPrice = ns.counter -%}
                {%- set ns.cheapestHour = today_at("00:00") + timedelta( hours = (24 + i - numberOfSequentialHours)) -%}
              {%- endif -%}
            {%- endfor -%}
            {{ ns.cheapestHour }}
            {%- set ns.cheapestPrice = ns.cheapestPrice / numberOfSequentialHours -%}
          {%- endif -%}

create a helper like this:
input_datetime.device_start_time
and an automation:

alias: Set dhw start time for next afternoon at 6pm
description: ""
trigger:
  - platform: time
    at: "18:00:00"
condition: []
action:
  - service: input_datetime.set_datetime
    data:
      time: >-
        {{ (as_timestamp(states('sensor.cheapest_hours_energy_tomorrow')) +
        (3600*0.2))| timestamp_custom('%H:%M') }}
    target:
      entity_id: input_datetime.device_start_time
mode: single

and finally this automation:

alias: dhw on device start time
description: ""
trigger:
  - platform: time
    at: input_datetime.device_start_time
condition:
  - condition: numeric_state
    entity_id: sensor.boiler_wwcurtemp2
    below: "33"
    enabled: true
action:
  - delay:
      hours: 0
      minutes: 1
      seconds: 0
      milliseconds: 0
  - device_id: f
    domain: select
    entity_id: select.thermostat_wwmode
    type: select_option
    option: normal
  - delay:
      hours: 0
      minutes: 5
      seconds: 20
      milliseconds: 0
  - device_id: f
    domain: select
    entity_id: select.thermostat_wwmode
    type: select_option
    option: "off"
mode: single
1 Like