Any good ideas are welcome. Nordpool Energy Price per hour

Peak = 08:00 to 20:00

Off peak 1 = 00:00 to 08:00

Off peak 2 = 20:00 to 00:00

Average = arithmetic average

I have the following template for getting the offset in hours until the lowest price for 3 consecutive hours occurs. I’m sure this template can be improved but it gets the job done.

{# SETTINGS START #}
{# Norpool sensor id#}
{% set nordpoolSensor = "sensor.nordpool_kwh_se4_sek_3_095_025" %}
{# number of consecutive hours to aggregate and compare. If the washing machine takes 3 hours to complete than use 3 #}
{% set usageHours = 3 %}
{# max number of future hours to include in the comparison.#}
{% set maxFutureHours = 24 %}
{# SETTINGS END #}
{# var to store price data #}
{% set priceData = namespace(numbers=[]) %}
{# Get prices from now and the rest of the day #}
{% for i in state_attr(nordpoolSensor,'raw_today') %}  
{% if i.start.hour >= now().hour %}
  {% set priceData.numbers = priceData.numbers + [i.value] %}
{% endif %}
{% endfor %}
{# Get prices for tomorrow if they are available #}
{% if is_state_attr(nordpoolSensor, 'tomorrow_valid', true) %} 
{% for i in state_attr(nordpoolSensor,'raw_tomorrow') %}
  {% set priceData.numbers = priceData.numbers + [i.value] %}
{% endfor %}
{% endif -%}
{# var to store the offset in hours counting from now until the lowest price #}
{% set lowPriceOffset = namespace(h = 0) %}
{# var to store the lowest price #}
{% set lowestPrice = namespace(p = 100000) %}
{# var to store price comparison data #}
{% set tmpPrice = namespace(p = 0) %}
{# for each hourly price available #}
{% for i in priceData.numbers %}
{# check that there are enough future prices to aggregate and compare #}
{% if (loop.index + usageHours - 1) <= priceData.numbers|length and loop.index <= maxFutureHours %}
  {% set outerLoopIndex = loop.index %}
  {% set tmpPrice.p = i %}
  {# add up prices for the usage hours #}
  {% for ii in range(usageHours - 1) %}
	{% set tmpPrice.p = tmpPrice.p + priceData.numbers[outerLoopIndex + ii] %}
  {% endfor %}
  {# check if new price is lower than previous lowest price #}
  {% if tmpPrice.p < lowestPrice.p %}
	{# set to new lowest price and offset #}
	{% set lowestPrice.p = tmpPrice.p %}
	{% set lowPriceOffset.h = outerLoopIndex - 1 %}
  {% endif %}
{% endif %}
{% endfor %}
{{ lowPriceOffset.h }}
2 Likes

Hi, these forward looking sensors are good. Please advise anyone with code to get count of filtered values from list, e.g:

{% set pricelist = state_attr('sensor.nordpool', 'today' ) %}
{{ pricelist }}
{% set pricebelowavg = state_attr('sensor.nordpool', 'average' ) * 0.5 | float %}
{{ pricebelowavg }}
# How to get count of prices below average?

Thanks in advance!

{{ pricelist | reject(">=", pricebelowavg) | list | count }}

1 Like

@faanskit : I used your code to control my water heater, so thanks a lot! I’m a dummy, both in python and HA, so I couldn’t have done this without you. There are many ways to solve this, but I liked your way of including a helper in the interface so that I can choose how many hours it should stay off.

But I chose to make the automation somewhat different from yours. I have just one automation instead of two (for ‘cheap’ and ‘expensive’), and the automation is ran each hour in addition to when one changes the choice in the dropdown-menu. With a if-statement in the automation, I placed the ‘Turn on’ as the else-action so that On is the default (?).

  • My input_select is called ‘vvb_av’, so that should be changed if anyone wishes to use this.
  • I check the existing status of the switch before changing and notifying

Here are my automation in yaml:

alias: VVB-styring (faanskit)
description: Turn off water heater in the (chosen) most expensive hours
trigger:
  - platform: time_pattern
    minutes: "1"
  - platform: state
    entity_id:
      - input_select.vvb_av
condition: []
action:
  - if:
      - condition: numeric_state
        entity_id: sensor.nordpool_kwh_krsand_nok_3_10_025
        above: sensor.nordpool_krsand_on_hours
    then:
      - if:
          - condition: device
            type: is_on
            device_id: CHANGEME_myswitchid
            entity_id: switch.heavy_duty_switch
            domain: switch
        then:
          - type: turn_off
            device_id: CHANGEME_myswitchid
            entity_id: switch.heavy_duty_switch
            domain: switch
          - service: notify.mobile_app_CHANGEME
            data:
              title: Expensive
              message: This is expensive - I'm turning off the water heater
    else:
      - if:
          - condition: device
            type: is_off
            device_id: CHANGEME_myswitchid
            entity_id: switch.heavy_duty_switch
            domain: switch
        then:
          - type: turn_on
            device_id: CHANGEME_myswitchid
            entity_id: switch.heavy_duty_switch
            domain: switch
          - service: notify.mobile_app_CHANGEME
            data:
              title: Cheaper
              message: Not so expensive - I'm turning on the water heater
mode: single

1 Like

I also have a fixed price for consumption, i sell my (not used) electricity back to the grid for spotprice.
I use an automation that sends me a message how much energy I have imported and exported, used to my phone every night when my solar have stopped producing, it also sends what the costs are for the imported energy.
The problem is that i can’t get the exported price, it would be easy if it was a fixed price but when it is spotprice it is much harder. Do you know how to do this?

This is the message it sends every night when stopped producing.
(i run the action now, that why there is no sold energy yet)

I have an Utility Meter that reset each month. How could I present my montly enery cost in Apex Chart with bars? Have tried a few examples but cant get it to work!

Sorry, I’m newbie in HA. As I understood, code 'input_number: … ’ till ‘mode: box’ is helper in configuration.yaml file. But where the code '- platform: template … ’ should be located? Because in yaml file there is syntax error “bad indentation of a mapping entry” .

I am trying to use this template to control my water heater so it turns on the cheapest hour every 24 hours.

But how do I use it?

If I paste it as-is into my configuration.yaml I get the following error:

The system cannot restart because the configuration is not valid: Integration error: platform - Integration 'platform' not found. Integration error: sensors - Integration 'sensors' not found.

This is exactly what I need to determine when to start my water heater, but I only need the single cheapest hour, but I guess I can get that by changing the usageHours parameter to 1.

But how would I use this code in a template to create a binary sensor that´s on only when the lowest price of the day happens? Then use that binary sensor in an utomation to turn on the heater?

I´m a HA noob, so could really use some assistance.

Hi,

I have a question.
Since we don’t have a smart dryer/washing machine yet, I would like to have a sensor that tells me what time to set the timer on (number of hours).
My plan is to have some kind of display in the laundry room that tells me what time the machines should start.

I have the Tibber and Nordpool integration installed. So all the data on the electricity price is already available.

Does anyone have an idea?

I have some ideas. You can just find a cheapest hour (or two) and use that. But for a maximum optimization it depends on how does the dryer power profile look like and how long does it run. For instance, my tumble dryer uses between 900 and 1800 W most of time but then drops to 900 W and finally stays at 200 W for last 10 minutes to cool down.

dryer-profile

Here is how I do it right now: I use external script to calculate cost using power profile for each appliance and rolling window with 1 minute step over price data. I put the calculation result to the InfluxDB where I can easily query current and the minimum price using Flux. Right now I use Grafana dashboard for this info but it should be possible to feed it to some HA sensor too.

Here is how it looks like where you can see that different appliances have slightly different best starting times:

Just for a more background information, my dryer total power usage is 1.781 kWh and runtime is 80 min. For comparison, my dishwasher cycle is 104 min and power usage is 1.139 kWh but it is very different. Most of energy goes to water heating in three different timeslots (using the default cycle):

dishwasher-profile

2 Likes

I’m curious to see if and how one can use this to calculate the cost of an individual power plug.

We do not have per hour cost but a monthly average with a more complex calculation. So I add tax and some other costs to the Nord pool price to calculate somewhat of an average. But it would be cool to use that with a kWh or W meter to get a somewhat actual price of a device per month.

Do anyone of you use this kind of setup and I’f so what sensors etc do you use to accomplish that?

Hi,

I hope that in the future HA will calculate cost for every appliance like it counts the energy usage right now. But as long it does not you can do it yourself.

For a background, I add the example how to calculate the final end user price from Nordpool price. Just change the final formula and price components based on your contract.

I have binary_sensor.workday_sensor because the transmission cost depends on that.

binary_sensor:
  - platform: workday
    name: is_weekend
    country: !secret countrycode
    excludes: [mon, tue, wed, thu, fri]
    workdays: [sat, sun]

Then I set up simple template sensor that gives me the current tariff name of the transmission . Here we have four different transmission tariffs but in my package there are only two prices. Nevertheless I still track all four to make it possible to calculate final price for different packages and compare them. I use this name also in energy dashboard.

sensor:
  - platform: template
    sensors:
      transmission_tariff:
        icon_template: mdi:clock
        value_template: >
          {%- set hour = now().strftime('%H') | int(0) -%}
          {%- set mon = now().strftime('%m') | int(0) -%}
          {%- set winter = (mon >= 11) or (mon <= 3) -%}
          {%- if is_state('binary_sensor.workday_sensor', 'on') -%}
            {%- if (hour < 7) -%}
              Night-time
            {%- elif (hour < 9) and winter -%}
              Daytime
            {%- elif (hour < 12) and winter -%}
              Top Daytime
            {%- elif (hour < 16) and winter -%}
              Daytime
            {%- elif (hour < 20) and winter -%}
              Top Daytime
            {%- elif (hour < 22) -%}
              Daytime
            {%- else -%}
              Night-time
            {%- endif -%}
          {%- else -%}
            {%- if (hour < 16) -%}
              Night-time
            {%- elif (hour < 20) and winter -%}
              Top Weekend
            {%- else -%}
              Night-time
            {%- endif -%}
          {%- endif -%}

And now the final calculation of the end user price itself:

sensor:
  - platform: template
    sensors:
      electricity_final_price:
        unit_of_measurement: '€'
        icon_template: mdi:cash
        value_template: >
          {% set nordpool_price = state_attr('sensor.nordpool_kwh_eur', 'current_price' ) %}
          {% set duty = 0.001 %}
          {% set renewable_energy_tax = 0.0113 %}
          {% set transmission_price = ({ 'Night-time': 0.0178, 'Top Weekend': 0.0178, 'Daytime': 0.0311, 'Top Daytime': 0.0311 }) %}
          {% set vat = 20 %}
          {% set contract_margin_with_vat = 0.0026 %}
          {% set electricity_price = (nordpool_price + duty + renewable_energy_tax + transmission_price[states('sensor.transmission_tariff')]) * (1 + vat / 100) + contract_margin_with_vat %}
          {{ electricity_price }}

Now you can use this price to calculate the cost using current energy usage and price. In this example I use total power of the house but you can set up similar sensor for every plug. Division by 1000 comes from 1 kWh price but the power sensor reading is in Watts.

      energy_cost_now:
        unit_of_measurement: '€'
        icon_template: mdi:cash
        value_template: "{{ (states('sensor.total_power')|float(0) * states('sensor.electricity_final_price')|float(0) / 1000.0) if (states('sensor.electricity_final_price')!='unknown' and states('sensor.total_power')!='unknown') else 'unknown' }}"

This number can be used as an input for Riemann sum integral sensor to get the cumulative sum of the electricity cost. This can be set using helper and I don’t have YAML for that.

To get a hourly, daily, weekly, monthly etc costs you can use Utility Meters with different reset cycles. This can be also set using helper in GUI.

3 Likes

Hey, Marcus,
Did you figure this one out? Thanks!

I use this, found it somewhere in this forum:

binary_sensor:
  - platform: template
    sensors:
      nordpool_cheapest_1_hours:
        value_template: >-
          {% set l=state_attr('sensor.nordpool_kwh_nl_eur_4_10_021', 'raw_today')|sort(attribute='value') %}
          {{ (now() >= l[0].start and now() <= l[0].end) }}
        friendly_name: nordpool cheapo 

I use the same approach to determine the most affordable hours but the sorting does not take the tariff into account. Do you have any idea how to include the tariff in the process? Thanks

I am interested in the same thing. Would be great to be able to include the tariff in the price. All help is much appreciated!

Hi!

In the templete developer tool, I created a code that works - if the total electricity price is one of the three cheapest and boiler is off, I get the value “true”. But when I put this code in configuration.yaml, the binary sensor is created, but the state does not change - it is always off. What am I doing wrong?

binary_sensor:
  - platform: template
    sensors:
      nordpool_cheepest_3h:
        value_template: >-
          - name: Cheep 3 hours
            state: >
              {% set d = {
                  "operator_margin": 0.466,
                  "oik": 0.196, 
                  "nw_fee_night": 2.65, 
                  "nw_fee_day": 5.138
              }
              %}
              {% set ns = namespace(z=[]) %}
              {% set prices = state_attr('sensor.nordpool_kwh_lv_eur_5_00_0', 'raw_today') %}
              {% for price in prices %}
                {% set week_day = as_timestamp(price.start) | timestamp_custom('%w') | float %}
                {% set oclock = as_timestamp(price.start) | timestamp_custom('%H') | float %}  
                  {% if week_day != 0 and week_day != 6 and oclock > 7 and oclock < 23 %}
                    {% set full_price_at_day = ((price.value|float + d.nw_fee_day|float + d.operator_margin|float + d.oik|float) * 1.21) | round(5) %}
                    {% set ns.z =  ns.z + [(oclock,  full_price_at_day)] %} 
                  {% else %}
                    {% set full_price_at_night = ((price.value|float + d.nw_fee_night|float + d.operator_margin|float + d.oik|float) * 1.21) | round(5) %}
                    {% set ns.z =  ns.z + [(oclock, full_price_at_night)] %}
                  {% endif %}
                {%- for key, value in ns.z|sort(attribute='1') -%}  
                  {%- if loop.index <= 3 %}
                    {%- set cheep_price = key | int -%}
                      {%- if now().hour == key -%}
                        {% if is_state('switch.boilers', 'off') %}
                          {{- true -}}
                        {% endif %}
                          {%- else %} 
                        {{- false -}} 
                    {% endif %}
                  {%- else %} {% endif %}
                {% endfor %}
              {% endfor %}

My first suggestion would be to remove the switch.boilers state from that sensor and check boiler state only in automation. Keep it simple and calculate only cheapest hours here.

I also suggest here to calculate only the maximum price of three (or whatever number) cheapest hours and not find the hours. Unless you especially need that information. It is much easier just to compare current price with price from this sensor in automation.