How would I make a BTC sensor daily profit. My idea is to subtract the current price of BTC from the value it had at midnight. I currently have a sensor of the current value of my BTC, which has a 30-day history. How do I subtract the current value from the value it had at midnight?
The only way to access the state of a sensor at a specific time is to either save that value in a sensor at that time, or to use an SQL sensor to look up the value. In your case, saving that state at midnight every night is the easier route. You can do this with a trigger-based template sensor, and you can save that value in an attribute so that you can refer to it when you calculate the difference.
something like this. Note that it will be unknown and have errors until midnight when the midnight price is first populated
template:
- trigger:
- platform: state
entity_id:
- sensor.btc_price
- platform: time
at: "00:00:00"
sensor:
name: "BTC Gain Today"
unique_id: b27e6b11-c4a4-41c6-9666-b99df32ea940
state_class: measurement
state: >
{{ 0 if trigger.platform == 'time' else trigger.to_state.state | float - this.attributes.midnight_price | float }}
attributes:
midnight_price: "{{ states('sensor.btc_price') if trigger.platform =='time' else this.attributes.midnight_price }}"
availability: "{{ is_number(states('sensor.btc_price')) }}"
sorry for my stupid questions. Where do I write the code? I haven’t worked with templates yet?
It depends how you have your setup configured; but likely in your configuration.yaml file:
Normal template sensors can be configured from the UI, but trigger-based template sensors like the one I suggested need to be created in yaml.
Also see the documentation for the template sensor:
You have other options as well, if you want to stay inside the UI.
You could create an input number helper, and then set up an automation to run at midnight every night to store the value into that input number helper.
Then you can create a template sensor from the UI that just calculates the difference between that input number helper and the current value of the BTC price.
Mind sharing your sensor for the current value?
Thank you for your willingness. There should probably be a template in the code: not templates: We’ll see what happens after midnight
You are absolutely correct. I’ve edited the original post, thanks!
but it doesn’t work. There is a unavailable after midnight.
I had a typo above, midight
instead of midnight
. I’ve edited my previous post. I also added state_class: measurement
so that it shows up as a line plot in your history, instead of discrete states.
If you want the sensor to start working immediately, reload your template entities (developer tools → YAML → click on template entities) and then go to the “STATES” tab (still in developer tools) and filter/scroll to the new BTC sensor and click on it. Then you can type in a value for the state, and add the “midnight_price” attribute (see example below):