i have a cell in excel with a figure that updates live , id like a formula that will alert ie text "alert" any time the value moves up or down suddenly in short span /burst
Assistant
To create an alert in Excel that detects a sudden jump or drop in a live-updating value, you can use a formula comparing the current value with the previous value and trigger text like "Alert" when the difference exceeds a certain threshold.
Assumptions:
Your live-updating value is in cell A2, and it updates regularly.
You keep a historical value in A1 (previous value), or you can track changes by storing previous values in another cell.
You will decide on a threshold value to define what counts as a "sudden" move.
Approach 1: Manual previous value in another cell
Because Excel formulas are not designed to remember previous values automatically (unless you use VBA), you typically need to store your previous value somewhere.
Step 1: Assume:
A2: Current live-updating value.
B2: Previous value (you update this manually or via VBA).
Step 2: Formula in C2 to alert on sudden move:
excel
=IF(ABS(A2 - B2) > Threshold, "Alert", "")
Replace Threshold with your chosen number. For example, if a move of more than 10 units is considered sudden:
excel
=IF(ABS(A2 - B2) > 10, "Alert", "")
Approach 2: Using VBA to track previous value automatically
Since Excel formulas can't remember past values automatically, you can add a simple VBA macro to track changes and flag alerts.
Here's a simple code snippet you can use:
vba
Dim PrevValue As Variant
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Me.Range("A2")) Is Nothing Then
If IsEmpty(PrevValue) Then
PrevValue = Target.Value
Else
Dim diff As Double
diff = Abs(Target.Value - PrevValue)
If diff > 10 Then ' Set threshold here
Me.Range("C2").Value = "Alert"
Else
Me.Range("C2").Value = ""
End If
PrevValue = Target.Value
End If
End If
End Sub
This macro tracks changes in cell A2.
If the difference exceeds 10, it writes "Alert" in C2.
To add this, press ALT+F11 in Excel to open VBA editor, double-click your sheet on the left, and paste this code.
Save your workbook as a macro-enabled workbook .xlsm.
Approach 3: Simplified with iterative calculation (less reliable)
If you enable iterative calculations (in Excel Options → Formulas), you could create a formula that references its own previous result. But this method is tricky and not recommended unless you are very familiar with iterative formulas.
Summary:
Without VBA: You need to manually keep the previous value somewhere and compare.
With VBA: You can automate tracking previous values and alerting.
If needed, I can help you write the VBA macro step-by-step or suggest a template for a workbook. Let me know!
User
im using libre calc how can i do this in vba
Assistant
LibreOffice Calc uses LibreOffice Basic (not VBA) and its API is different from Excel VBA.
To achieve your requirement in LibreOffice Calc—i.e., to alert ("Alert" text) when a live-updated cell value moves up or down suddenly by more than a threshold compared to its previous value—you need to write a macro in LibreOffice Basic, and connect it to an event (e.g., content change event on the sheet or on the cell).
Step-by-step for LibreOffice Calc
1. Decide your setup:
Let's say your live updating value is in cell A2.
You want to put the alert status ("Alert") in cell C2.
Threshold: You define a number for what counts as a sudden move (say 10).
2. Store previous value:
Since Calc has no automatic memory of previous values, you have to store the previous value somewhere. You can store it in a hidden sheet/cell or in document properties, or use a document variable.
To keep things simple, let’s store the previous value in cell B2 (hidden or visible).
A2 = current value (updates live)
B2 = previous value (your code will update this)
C2 = alert (formula set by macro)
3. Write the macro
You will create a macro that runs when the document sheet changes, compares A2 to B2, and writes "Alert" in C2 if the difference is above threshold; otherwise, clears C2. Also, the macro then updates B2 with the new current value in A2.
Example macro:
basic
User
error:
A scripting framework error occurred while running the basic script
Standard.Module1_track_price.CheckSuddenMove.
Message: wrong number of parameters
Assistant
The error "wrong number of parameters" usually means the event handler macro signature does not match what LibreOffice expects.
When you assign a macro to the Sheet's Content changed event, the macro does not receive any parameters or receives a different argument structure than what we assumed.
How to fix this:
Change the macro to not expect parameters or handle the parameters properly.
For the Content changed event on a Sheet, the macro signature must be:
basic
Sub CheckSuddenMove(Optional oEvent As Object)
' Your code here
End Sub
or
basic
Sub CheckSuddenMove()
' Your code here
End Sub
If you use the parameter (often recommended), mark it as Optional.
Updated macro with Optional parameter and ignoring parameters you don't need
basic
Sub CheckSuddenMove(Optional oEvent As Object)
Dim oSheet As Object
Dim currentValue As Double
Dim prevValue As Double
Dim threshold As Double
Dim alertCell As Object
Dim prevValueCell As Object
Dim currentValueCell As Object
Dim diff As Double
threshold = 10 ' Define your threshold
oSheet = ThisComponent.Sheets(0) ' First sheet
currentValueCell = oSheet.getCellRangeByName("A2")
prevValueCell = oSheet.getCellRangeByName("B2")
alertCell = oSheet.getCellRangeByName("C2")
' Make sure cells have numeric content
If IsNumeric(currentValueCell.getValue()) Then
currentValue = currentValueCell.getValue()
Else
currentValue = 0
End If
If IsNumeric(prevValueCell.getValue()) Then
prevValue = prevValueCell.getValue()
Else
prevValue = currentValue ' Initialize prev value if empty
prevValueCell.setValue(prevValue)
alertCell.String = ""
Exit Sub
End If
diff = Abs(currentValue - prevValue)
If diff > threshold Then
alertCell.String = "Alert"
Else
alertCell.String = ""
End If
' Update previous value
prevValueCell.setValue(currentValue)
End Sub
User
im using a value like 0.64127
can i put my threshold to 0.0001 ie forex pip
Assistant
Yes! You can absolutely use a very small threshold like 0.0001 (which suits Forex pip-level moves) in your LibreOffice Calc macro.
What you need to do:
Just set the threshold variable in the macro to 0.0001 instead of 10.
For example, update this line in your macro:
basic
threshold = 0.0001 ' Threshold for sudden move (1 pip)
Full example snippet with your pip threshold:
basic
Sub CheckSuddenMove(Optional oEvent As Object)
Dim oSheet As Object
Dim currentValue As Double
Dim prevValue As Double
Dim threshold As Double
Dim alertCell As Object
Dim prevValueCell As Object
Dim currentValueCell As Object
Dim diff As Double
threshold = 0.0001 ' Threshold set to 1 pip
oSheet = ThisComponent.Sheets(0) ' First sheet
currentValueCell = oSheet.getCellRangeByName("A2")
prevValueCell = oSheet.getCellRangeByName("B2")
alertCell = oSheet.getCellRangeByName("C2")
' Get current value, check it's numeric
If IsNumeric(currentValueCell.getValue()) Then
currentValue = currentValueCell.getValue()
Else
currentValue = 0
End If
' Get previous value, or initialize
If IsNumeric(prevValueCell.getValue()) Then
prevValue = prevValueCell.getValue()
Else
prevValue = currentValue ' Initialize previous value
prevValueCell.setValue(prevValue)
alertCell.String = ""
Exit Sub
End If
diff = Abs(currentValue - prevValue)
If diff > threshold Then
alertCell.String = "Alert"
Else
alertCell.String = ""
End If
' Update previous value
prevValueCell.setValue(currentValue)
End Sub
A few tips:
Make sure your value in A2 is of type Number, not Text.
Store previous value in B2 (hidden or visible).
Put the alert text in C2.
Assign macro to the Sheet > Content changed event of your sheet.
If your live data updates quite frequently, and multiple changes happen quickly, this approach will flag any change in A2 larger than 1 pip (0.0001).
If you want I can help a bit more for making the macro trigger only when A2 changes, or any other feature!
User
id like it to update dynamically ie after every new figure/price in A2 ,B2 hold the previous figure and continues changing on its own, so i dont have to keep running it manually to update
Assistant
Understood! You want the checking of sudden moves to happen automatically every time cell A2 changes, so that:
B2 always holds the previous value of A2,
C2 shows "Alert" whenever the jump/dip is greater than the threshold,
This runs automatically without manually running the macro.
In LibreOffice Calc, this is achievable by:
Assigning the macro to the "Content changed" event of the sheet (or ideally, the "Content changed" event of cell A2),
Ensuring your macro runs automatically on each change,
And your macro updates B2, compares old vs new, and writes the alert.
Step-by-step summary for your dynamic alert:
1. Macro code
Use this macro below which automatically triggers, compares current vs previous, alerts if needed, and updates the previous value.
basic
Sub CheckSuddenMove(Optional oEvent As Object)
Dim oSheet As Object
Dim currentValue As Double
Dim prevValue As Double
Dim threshold As Double
Dim alertCell As Object
Dim prevValueCell As Object
Dim currentValueCell As Object
Dim diff As Double
threshold = 0.0001 ' Your pip threshold
oSheet = ThisComponent.Sheets(0) ' Change sheet index if needed
currentValueCell = oSheet.getCellRangeByName("A2")
prevValueCell = oSheet.getCellRangeByName("B2")
alertCell = oSheet.getCellRangeByName("C2")
' Only proceed if A2 contains numeric value
If Not IsNumeric(currentValueCell.getValue()) Then Exit Sub
currentValue = currentValueCell.getValue()
If IsNumeric(prevValueCell.getValue()) Then
prevValue = prevValueCell.getValue()
Else
prevValue = currentValue
prevValueCell.setValue(prevValue)
alertCell.String = ""
Exit Sub
End If
diff = Abs(currentValue - prevValue)
If diff > threshold Then
alertCell.String = "Alert"
Else
alertCell.String = ""
End If
' Update previous value for next check
prevValueCell.setValue(currentValue)
End Sub
User
i did this :
Assign the macro to Calc sheet event “Content changed”
Right-click the sheet tab at the bottom (e.g., "Sheet1").
Select Sheet Events…
Find the event called Content changed.
Click the Macro... button.
Select your macro (CheckSuddenMove) in the macro organizer window.
Click OK.
but the value in B2 updats only when i rerun the macro
Assistant
Thanks for the update! The macro should automatically run every time the sheet content changes if assigned to the Content changed event. If B2 only updates when you manually run the macro, that means the macro is not being triggered automatically on edits. This usually happens because:
The event assignment did not actually register; or
The event is triggered on some changes but not on changes caused by external data refresh or formulas; or
Your value in A2 is coming from a formula or external data source and LibreOffice Calc doesn't trigger the "Content changed" event for formula recalculation.
Important: LibreOffice "Content changed" event is triggered only for manual edits, not for formula recalculations or data changes from linked external sources.
If your "live update" in A2 comes from some formula (like an external data refresh, or a live link), then "Content changed" event won't fire!
What can you do?
Option 1: Use a macro with a Timer to periodically check the value
You can write a LibreOffice Basic macro that runs every X seconds, checks the value in A2, compares it to B2, updates B2 if changed, and writes "Alert" in C2.
Example — periodic check macro using LibreOffice Basic and a timer
basic
User
Error:
BASIC syntax error.
Symbol g_TimerId already defined differently
my required values are in the following cells:
Global g_TimerId as Long
Sub StartAutoCheck()
' Start timer that runs every 1 second (1000 ms)
g_TimerId = CreateUnoService("com.sun.star.awt.Timer")
g_TimerId.Interval = 1000 ' milliseconds
AddHandler g_TimerId, "timer", GetRef("AutoCheck")
g_TimerId.Enabled = True
End Sub
Sub StopAutoCheck()
If g_TimerId Is Nothing Then Exit Sub
g_TimerId.Enabled = False
RemoveHandler g_TimerId, "timer", GetRef("AutoCheck")
Set g_TimerId = Nothing
End Sub
Sub AutoCheck(e As Object)
Dim oSheet As Object
Dim currentValue As Double
Dim prevValue As Double
Dim threshold As Double
Dim alertCell As Object
Dim prevValueCell As Object
Dim currentValueCell As Object
Dim diff As Double
code
threshold = 0.00015
oSheet = ThisComponent.Sheets(0) ' Change if not first sheet
currentValueCell = oSheet.getCellRangeByName("B3")
prevValueCell = oSheet.getCellRangeByName("E3")
alertCell = oSheet.getCellRangeByName("F3")
If Not IsNumeric(currentValueCell.getValue()) Then Exit Sub
currentValue = currentValueCell.getValue()
If IsNumeric(prevValueCell.getValue()) Then
prevValue = prevValueCell.getValue()
Else
prevValue = currentValue
prevValueCell.setValue(prevValue)
alertCell.String = ""
Exit Sub
End If
diff = Abs(currentValue - prevValue)
If diff > threshold Then
alertCell.String = "Alert"
Else
alertCell.String = ""
End If
prevValueCell.setValue(currentValue)
End Sub
Assistant
The "Symbol g_TimerId already defined differently" error means the global variable g_TimerId was declared more than once or has conflicting declarations.
LibreOffice Basic allows you to declare global variables only once at the module level, not inside subs or multiple times.
How to fix:
Move the declaration outside any subroutine, at the very top of your module, like this:
basic
Global g_TimerId As Object
Note: It should be As Object because the timer service is an object, notAs Long.
Then keep your subs without redeclaring the variable.
Corrected full example with your cell refs (B3, E3, F3):
basic
' Declare global variable once here, at the very top of your module
Global g_TimerId As Object
Sub StartAutoCheck()
' Create a timer to run every 1 second
g_TimerId = CreateUnoService("com.sun.star.awt.Timer")
g_TimerId.Interval = 1000 ' milliseconds
AddHandler g_TimerId, "timer", GetRef("AutoCheck")
g_TimerId.Enabled = True
End Sub
Sub StopAutoCheck()
If g_TimerId Is Nothing Then Exit Sub
g_TimerId.Enabled = False
RemoveHandler g_TimerId, "timer", GetRef("AutoCheck")
Set g_TimerId = Nothing
End Sub
Sub AutoCheck(e As Object)
Dim oSheet As Object
Dim currentValue As Double
Dim prevValue As Double
Dim threshold As Double
Dim alertCell As Object
Dim prevValueCell As Object
Dim currentValueCell As Object
Dim diff As Double
threshold = 0.00015 ' Your desired threshold
oSheet = ThisComponent.Sheets(0) ' Change if needed
currentValueCell = oSheet.getCellRangeByName("B3")
prevValueCell = oSheet.getCellRangeByName("E3")
alertCell = oSheet.getCellRangeByName("F3")
If Not IsNumeric(currentValueCell.getValue()) Then Exit Sub
currentValue = currentValueCell.getValue()
If IsNumeric(prevValueCell.getValue()) Then
prevValue = prevValueCell.getValue()
Else
prevValue = currentValue
prevValueCell.setValue(prevValue)
alertCell.String = ""
Exit Sub
End If
diff = Abs(currentValue - prevValue)
If diff > threshold Then
alertCell.String = "Alert"
Else
alertCell.String = ""
End If
prevValueCell.setValue(currentValue)
End Sub
User
basic runtime error
Object variable not set
error pointing to line 7:
code
g_TimerId.Interval = 1000 ' milliseconds
Assistant
The error "Object variable not set" at the line
basic
g_TimerId.Interval = 1000
means the g_TimerId object was not successfully created by CreateUnoService("com.sun.star.awt.Timer"). LibreOffice cannot create the timer service this way in LibreOffice Basic, because LibreOffice Basic does NOT support the com.sun.star.awt.Timer service for timers.
What’s going on?
Excel VBA has Application.OnTime and other timer-like objects, but LibreOffice Basic does NOT provide a native timer service.
The "com.sun.star.awt.Timer" service does not exist in LibreOffice API.
The snippet I gave you earlier was incorrect because it assumes a timer service that is not in LibreOffice.
How to do periodic checking in LibreOffice Basic?
Unfortunately, LibreOffice Basic does not have built-in timer support like VBA.
Common workarounds are:
Use LibreOffice Python macros with external timers or event loops (advanced).
Use a loop inside a macro with Wait() calls — but this will freeze the UI, not recommended.
Use a "manual refresh" button or event to run the macro when you want.
Use Calc's "Recalculate" event if your data changes trigger recalculation.
Practical solutions for your problem:
Option 1: Manual macro trigger (best for most users):
Put a Button on your sheet:
Insert > Button
Assign the macro CheckSuddenMove to the button.
Click the button whenever you want to check for sudden moves.
Option 2: Assign macro to "Recalculate" event
If your cell updates by formula recalculation, assign macro to the document's "Calculate" event, so it runs after formulas update.
Go to Tools > Customize > Events tab
Select Calculate event
Assign your CheckSuddenMove macro
This way macro runs whenever the sheet recalculates (formula or manual recalc).
Here’s how your macro would look in that case (same as before):
User
so theres not formula that can snap shot a cell in libre calc ie the previous value
Assistant
Correct — there is no standard formula in LibreOffice Calc (or Excel) that by itself can "remember" or "snapshot" the previous value of a cell automatically as the cell changes over time.
Why?
Spreadsheet formulas recalculate from scratch on every update.
Formulas cannot store or retain historical values without external help.
They only operate on current cell values or values visible somewhere in the sheet.
What are your options in LibreOffice Calc to track previous values "automatically"?
1. Use a macro (event-triggered or timer-driven)
A macro can read the current cell value, compare it to a stored "previous value" somewhere (like another cell), and update that stored value for next time. This is what we tried with macros like CheckSuddenMove.
2. Manual snapshot using copy-paste
Manually copy the current value elsewhere before it changes.
Using iterative calculation with circular references and some helper cells, you can somewhat simulate historical value storage, but it is fragile and error-prone.
Example formula you might see in Excel or Calc using iterative calc on cell B2:
basic
=IF(A2<>B2, A2, B2)
Where B2 stores previous value.
You enable iterative calculation in Tools → Options → LibreOffice Calc → Calculate → Iterative References.
But this doesn't perfectly track previous values if A2 changes multiple times quickly or resets.
4. Use a helper column or sheet to manually record value history
If you want a log or history, you would need a macro to append cell A2's value to a list somewhere as it changes.
Summary
No simple formula alone can track previous values automatically.
Your best approach is a LibreOffice Basic macro triggered on change or calculation events.
Alternatively, manual methods or iterative references but those are limited.
If you want, I can help you with:
A macro that logs changes to another sheet (history),
A helper solution with iterative calc formulas,
Or instructions for setting up event-driven macros correctly in LibreOffice Calc.
Yes, you can definitely monitor and detect sudden changes (alerts) in your live data CSV file using Python. Since you receive BID prices per second in LiveData.csv, a Python script can:
Read and track the latest BID prices per currency pair,
Compare new prices to previous ones,
Trigger an alert when the change exceeds your threshold (e.g., 0.0001 for Forex pairs),
Log or notify you as needed.
Here's a simple Python approach
What this script will do:
Continuously read the CSV file (assuming it's appended every second)
Store last BID prices in memory (for each pair)
When a new line arrives, compare BID to previous value
Show "Alert" if the change is beyond threshold
Key assumptions
Your CSV file is updated continuously (either appended or overwritten)
"Time" column is in sortable format
Script runs continuously, polling the file regularly (e.g., every second)
Example Python script
python
import csv
import time
from collections import defaultdict
# Configuration
csv_file_path = 'LiveData.csv'
threshold = 0.0001 # Your alert threshold
last_bid_prices = {} # pair -> last bid price
def read_csv_latest_rows(filename):
"""Reads whole CSV returning all rows"""
with open(filename, newline='') as csvfile:
reader = csv.DictReader(csvfile, delimiter='\t')
return list(reader)
def check_for_alerts(rows):
alerts = []
for row in rows:
pair = row['PAIR']
try:
bid = float(row['BID'])
except ValueError:
continue
prev_bid = last_bid_prices.get(pair)
if prev_bid is not None:
diff = abs(bid - prev_bid)
if diff > threshold:
alerts.append((pair, prev_bid, bid, diff))
last_bid_prices[pair] = bid
return alerts
def main():
print("Starting live BID monitor... (CTRL+C to stop)")
prev_row_count = 0
while True:
try:
rows = read_csv_latest_rows(csv_file_path)
if len(rows) != prev_row_count:
alerts = check_for_alerts(rows)
for pair, old_bid, new_bid, diff in alerts:
print(f"Alert on {pair}: BID changed from {old_bid} to {new_bid} (diff {diff})")
prev_row_count = len(rows)
time.sleep(1) # wait 1 second before checking again
except KeyboardInterrupt:
print("Stopping monitor.")
break
except FileNotFoundError:
print(f"{csv_file_path} not found, waiting...")
time.sleep(5)
except Exception as e:
print(f"Error: {e}")
time.sleep(5)
if __name__ == "__main__":
main()
User
the code gets stuck at Starting live BID monitor... (CTRL+C to stop), until stop it with ctrl c:
Thanks for the update! The message Starting live BID monitor... (CTRL+C to stop) followed by nothing means the script is running but it doesn't find any new data to process or is waiting/sleeping each loop iteration.
Why might it appear "stuck"?
The script loop is designed to:
Read the entire CSV file every second,
Check for changes if the file row count differs from the last loop,
Otherwise, sleep for 1 second and repeat.
If your CSV doesn't change (same number of rows), the script will simply sleep and wait silently.
How can you confirm it's working?
1. Add some debug prints in the loop:
Modify your main while loop as follows:
python
def main():
print("Starting live BID monitor... (CTRL+C to stop)")
prev_row_count = 0
while True:
try:
rows = read_csv_latest_rows(csv_file_path)
print(f"Read {len(rows)} rows from CSV")
if len(rows) != prev_row_count:
alerts = check_for_alerts(rows)
for pair, old_bid, new_bid, diff in alerts:
print(f"Alert on {pair}: BID changed from {old_bid} to {new_bid} (diff {diff})")
prev_row_count = len(rows)
else:
print("No new rows detected")
time.sleep(1)
except KeyboardInterrupt:
print("Stopping monitor.")
break
except FileNotFoundError:
print(f"{csv_file_path} not found, waiting...")
time.sleep(5)
except Exception as e:
print(f"Error: {e}")
time.sleep(5)
Now when you run, every second it will say either number of rows read or "No new rows detected."
2. Check if your LiveData.csv file actually updates
If the file is rewritten every second with the , the script will think nothing changed.
User
note the following :
dulu@dulu:~$ /bin/python3 /media/dulu/PART2HDD/VS_Code_Projects/stock_screener/bid_price_monitor.py
Starting live BID monitor... (CTRL+C to stop)
Read 9 rows from CSV
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
Read 9 rows from CSV
No new rows detected
^Z
[1]+ Stopped
no new rows are created the file remains in the same format with the same number of cells , just that the cell with the bid price changes every second, I can change the interval at which the cell updates ie 5 sec, 10 sec etc
Assistant
Thanks for clarifying! Since your CSV always has the same 9 rows (no rows added/removed), but BID prices update in-place, your original logic that triggers only on row count changes will never detect updates.
Adjust your script to detect value changes regardless of row count
You want to always compare the current BID values with the previously stored ones — even if the number of rows stays the same.
Here’s how:
Remove the check if len(rows) != prev_row_count
Always call check_for_alerts(rows) every time you read the file
Updated main loop:
python
def main():
print("Starting live BID monitor... (CTRL+C to stop)")
while True:
try:
rows = read_csv_latest_rows(csv_file_path)
print(f"Read {len(rows)} rows from CSV")
alerts = check_for_alerts(rows)
for pair, old_bid, new_bid, diff in alerts:
print(f"Alert on {pair}: BID changed from {old_bid} to {new_bid} (diff {diff})")
time.sleep(1) # adjust according to your update interval
except KeyboardInterrupt:
print("Stopping monitor.")
break
except FileNotFoundError:
print(f"{csv_file_path} not found, waiting...")
time.sleep(5)
except Exception as e:
print(f"Error: {e}")
time.sleep(5)
Why this works:
Each time you read the file, you compare all pairs' current BID prices with the last stored values.
If the BID for a pair differs by more than threshold, you get an alert.
You update your last_bid_prices dictionary inside check_for_alerts so next iteration has the latest prices.
Extra tip: Adjust polling frequency to match your update interval
If your file updates every 5 or 10 seconds, set or accordingly to avoid unnecessary file reads.
User
ok now , for threshold jpy pairs use 0.01 and not 0.0001 how can set this thresholds to work on the target pair
Assistant
Great question!
You want to have different thresholds depending on the currency pair — for example:
For JPY pairs (EURJPY.Z, GBPJPY.Z, USDJPY.Z, etc.): threshold = 0.01
For all others: threshold = 0.0001 (or whatever default)
How to do that
Define a dictionary with specific thresholds per pair or per pair pattern.
Then in your check, lookup threshold for that pair, falling back to default if no specific threshold exists.
Example snippet integrating thresholds by pair:
python
# Define thresholds per pair (or pair suffix)
pair_thresholds = {
'JPY': 0.01, # For pairs containing JPY (you'll match this)
# Add any other specific overrides here, e.g.:
# 'GBPUSD.Z': 0.0002,
}
default_threshold = 0.0001
def get_threshold(pair):
# Check if 'JPY' substring is in the pair string (case-insensitive)
if 'JPY' in pair.upper():
return pair_thresholds['JPY']
# Add more complex matching if needed here
return default_threshold
def check_for_alerts(rows):
alerts = []
for row in rows:
pair = row['PAIR']
try:
bid = float(row['BID'])
except ValueError:
continue
prev_bid = last_bid_prices.get(pair)
if prev_bid is not None:
threshold = get_threshold(pair)
diff = abs(bid - prev_bid)
if diff > threshold:
alerts.append((pair, prev_bid, bid, diff))
last_bid_prices[pair] = bid
return alerts
Explanation:
get_threshold(pair) returns 0.01 if "JPY" is in the pair string.
Otherwise returns your default threshold (0.0001).
Certainly! Here is the full updated Python script that applies specific thresholds per pair (like your JPY pairs at 0.01) and a default threshold (0.0001) for all others:
python
import csv
import time
csv_file_path = 'LiveData.csv'
# Thresholds per exact pair name
pair_thresholds = {
'EURJPY.Z': 0.01,
'GBPJPY.Z': 0.01,
'USDJPY.Z': 0.01,
# Add other pairs with custom thresholds here
}
default_threshold = 0.0001
last_bid_prices = {}
def get_threshold(pair):
return pair_thresholds.get(pair.upper(), default_threshold)
def read_csv_latest_rows(filename):
with open(filename, newline='') as csvfile:
reader = csv.DictReader(csvfile, delimiter='\t')
return list(reader)
def check_for_alerts(rows):
alerts = []
for row in rows:
pair = row['PAIR']
try:
bid = float(row['BID'])
except ValueError:
continue
prev_bid = last_bid_prices.get(pair)
if prev_bid is not None:
threshold = get_threshold(pair)
diff = abs(bid - prev_bid)
if diff > threshold:
alerts.append((pair, prev_bid, bid, diff))
last_bid_prices[pair] = bid
return alerts
def main():
print("Starting live BID monitor... (CTRL+C to stop)")
while True:
try:
rows = read_csv_latest_rows(csv_file_path)
print(f"Read {len(rows)} rows from CSV")
alerts = check_for_alerts(rows)
for pair, old_bid, new_bid, diff in alerts:
print(f"Alert on {pair}: BID changed from {old_bid} to {new_bid} (diff {diff})")
time.sleep(5) # Adjust according to your data update frequency
except KeyboardInterrupt:
print("Stopping monitor.")
break
except FileNotFoundError:
print(f"{csv_file_path} not found, waiting...")
time.sleep(5)
except Exception as e:
print(f"Error: {e}")
time.sleep(5)
if __name__ == "__main__":
main()
How to use:
Make sure your LiveData.csv is tab-delimited with headers: Time, BID, ASK, PAIR.
Save this script to a .py file.
Run it with Python 3.
Adjust the time.sleep(5) if your CSV updates faster or slower.
Add more pairs with custom thresholds to pair_thresholds as needed.
If you want any modifications (like logging, output files, notification integrations), just ask!
User
ok how can i edit it so that the console only shows alerts not every:
Read 9 rows from CSV
Read 9 rows from CSV
Read 9 rows from CSV
Read 9 rows from CSV
Read 9 rows from CSV
Read 9 rows from CSV
Read 9 rows from CSV
just:
Alert on USDCAD.Z: BID changed from 1.38626 to 1.38603 (diff 0.00022999999999995246)
and if the diff is positive it should say buy
Alert - Sell on USDCAD.Z: BID Lost from 1.38626 to 1.38603 (diff 0.00022999999999995246)
and
Alert - Buy on GBPJPY.Z: BID Gained from 193.144 to 193.146 (diff 0.001999999999981128)
Assistant
Got it! Here's the updated script with:
No print for "Read X rows from CSV" — only alerts show in the console
Alerts specify "Buy" if BID increased (new_bid > old_bid)
Alerts specify "Sell" if BID decreased (new_bid < old_bid)
Alert messages formatted as you requested
Updated full code:
python
import csv
import time
csv_file_path = 'LiveData.csv'
# Thresholds per exact pair name
pair_thresholds = {
'EURJPY.Z': 0.01,
'GBPJPY.Z': 0.01,
'USDJPY.Z': 0.01,
# Add other pairs with custom thresholds here
}
default_threshold = 0.0001
last_bid_prices = {}
def get_threshold(pair):
return pair_thresholds.get(pair.upper(), default_threshold)
def read_csv_latest_rows(filename):
with open(filename, newline='') as csvfile:
reader = csv.DictReader(csvfile, delimiter='\t')
return list(reader)
def check_for_alerts(rows):
alerts = []
for row in rows:
pair = row['PAIR']
try:
bid = float(row['BID'])
except ValueError:
continue
prev_bid = last_bid_prices.get(pair)
if prev_bid is not None:
threshold = get_threshold(pair)
diff = round(abs(bid - prev_bid), 8) # round diff for readability
if diff > threshold:
direction = "Buy" if bid > prev_bid else "Sell"
# Store alert info with direction for printing later
alerts.append((pair, prev_bid, bid, diff, direction))
last_bid_prices[pair] = bid
return alerts
def main():
print("Starting live BID monitor... (CTRL+C to stop)")
while True:
try:
rows = read_csv_latest_rows(csv_file_path)
alerts = check_for_alerts(rows)
for pair, old_bid, new_bid, diff, direction in alerts:
if direction == "Buy":
print(f"Alert - Buy on {pair}: BID Gained from {old_bid} to {new_bid} (diff {diff})")
else:
print(f"Alert - Sell on {pair}: BID Lost from {old_bid} to {new_bid} (diff {diff})")
time.sleep(5) # Adjust to your update frequency
except KeyboardInterrupt:
print("\nStopping monitor.")
break
except FileNotFoundError:
print(f"{csv_file_path} not found, waiting...")
time.sleep(5)
except Exception as e:
print(f"Error: {e}")
time.sleep(5)
if __name__ == "__main__":
main()
User
if i want to convert this to points:
default_threshold = 0.0001
Assistant
In Forex, "points" or "pips" are commonly used to denote price movement units, but the exact size depends on the currency pair.
Your current default_threshold = 0.0001 means a movement of 1 pip for most pairs like EURUSD.
What do you mean by "convert to points"?
Assuming:
1 pip = 0.0001 for most pairs (those quoted to 4 decimal places),
For JPY pairs, 1 pip = 0.01 (because they are quoted to 2 decimal places),
If you want to convert threshold to points, understanding what 1 point is:
Often, 1 pip = 10 points (or pips = 10 pipettes / points); in some contexts, just 1 point = smallest decimal increment.
How to handle points in your code
If you want your threshold to be given in pips or points, and convert it to price difference, do this:
Example for handling threshold in pips (for 4-decimal pairs):
1 pip = 0.0001
1 point = 0.00001
If user inputs threshold = 3 pips → actual threshold = 3 * 0.0001 = 0.0003
Modify your code to accept thresholds in pips / points
Let's say you want to configure thresholds in pips, then convert them to decimal price moves:
python
# Define thresholds in pips (integer or float)
pair_thresholds_pips = {
'EURJPY.Z': 1, # 1 pip = 0.01 price move here
'GBPJPY.Z': 1,
'USDJPY.Z': 1,
# ...
}
pair_pip_values = {
'JPY': 0.01, # For pairs with JPY, 1 pip = 0.01
'DEFAULT': 0.0001, # For other pairs
}
default_threshold_pips = 1 # 1 pip default
def get_threshold(pair):
pair_upper = pair.upper()
# Determine pip value
if 'JPY' in pair_upper:
pip_value = pair_pip_values['JPY']
else:
pip_value = pair_pip_values['DEFAULT']
# Get threshold in pips if specified or default
threshold_pips = pair_thresholds_pips.get(pair_upper, default_threshold_pips)
# Convert threshold in pips to price difference
return threshold_pips * pip_value
Integrate this snippet replacing your previous pair_thresholds and default_threshold logic.
Summary:
Store thresholds in pips (integers like 1, 3, 5).
Convert to absolute price movement depending on pair type (JPY or not).
Use that converted threshold value for comparisons.
If you want me to rewrite the full script with this pip-to-price-threshold conversion included, just ask!
User
would this be right:
code
print(f"Alert - Buy on {pair}: BID Gained from {old_bid} to {new_bid} (+ {diff*10}) Points")
Assistant
Yes, that syntax is correct Python f-string usage, but you need to be clear what multiplying by 10 means in your context.
What your line does:
python
print(f"Alert - Buy on {pair}: BID Gained from {old_bid} to {new_bid} (+ {diff*10}) Points")
It prints the numeric value of diff*10 inline, which means you’re representing the diff multiplied by 10 as "Points".
A few tips for clarity:
diff in your script is the absolute price difference, e.g. 0.00023 for EURUSD.
If 1 point = 0.00001 (which is usually the case), then diff * 10 means:
You are treating diff in decimal price units,
Multiplying by 10 gives number of points only if 1 point = 0.0001 (which is typically a pip, not a point).
Concretely:
For EURUSD (diff around 0.0001), points = diff / 0.00001 = diff * 10000
For GBPJPY (diff around 0.01), points = diff / 0.001 = diff * 100
So multiplying diff by 10 will not always correctly convert to points.
Correct approach — convert diff to points properly:
If you define:
1 point = 0.00001 on 4-decimal pairs (like EURUSD),
1 point = 0.001 on 2-decimal JPY pairs (e.g. USDJPY),
You can do:
python
def get_point_value(pair):
if 'JPY' in pair.upper():
return 0.001 # 1 point for JPY pairs
else:
return 0.00001 # 1 point for others
point_value = get_point_value(pair)
points = diff / point_value
Then print:
python
print(f"Alert - Buy on {pair}: BID Gained from {old_bid} to {new_bid} (+ {points:.1f} Points)")
Summary:
Your syntax is right but multiplying diff by 10 is an arbitrary scaling — probably not an accurate points conversion.
To print points accurately, divide the diff by the point size relevant for the pair.
If you want a snippet with points conversion incorporated, just say!
def read_csv_latest_rows(filename):
with open(filename, newline='') as csvfile:
reader = csv.DictReader(csvfile, delimiter='\t')
return list(reader)
def check_for_alerts(rows):
alerts = []
for row in rows:
pair = row['PAIR']
try:
bid = float(row['BID'])
except ValueError:
continue
prev_bid = last_bid_prices.get(pair)
if prev_bid is not None:
threshold = get_threshold(pair)
diff = round(abs(bid - prev_bid), 8) # round diff for readability
if diff > threshold:
direction = "Buy" if bid > prev_bid else "Sell"
# Store alert info with direction for printing later
alerts.append((pair, prev_bid, bid, diff, direction))
last_bid_prices[pair] = bid
return alerts
def main():
print("Starting live BID monitor... (CTRL+C to stop)")
while True:
try:
rows = read_csv_latest_rows(csv_file_path)
alerts = check_for_alerts(rows)
for pair, old_bid, new_bid, diff, direction in alerts:
if direction == "Buy":
print(f"Alert - Buy on {pair}: BID Gained from {old_bid} to {new_bid} (+ {diff * 1000}) Points") # pip/0.00001*10
else:
print(f"Alert - Sell on {pair}: BID Lost from {old_bid} to {new_bid} (- {diff * 1000}) Points ")
time.sleep(5) # Adjust to your update frequency
except KeyboardInterrupt:
print("\nStopping monitor.")
break
except FileNotFoundError:
print(f"{csv_file_path} not found, waiting...")
time.sleep(5)
except Exception as e:
print(f"Error: {e}")
time.sleep(5)
if name == "main":
main()
output:
dulu@dulu:~$ /bin/python3 /media/dulu/PART2HDD/VS_Code_Projects/stock_screener/bid_price_monitor.py
Starting live BID monitor... (CTRL+C to stop)
Alert - Buy on GBPJPY.Z: BID Gained from 193.102 to 193.15 (+ 48.0) Points
Alert - Buy on GBPJPY.Z: BID Gained from 193.141 to 193.168 (+ 27.0) Points
Alert - Sell on AUDUSD.Z: BID Lost from 0.64105 to 0.64078 (- 0.27) Points
Alert - Buy on EURJPY.Z: BID Gained from 162.411 to 162.465 (+ 54.0) Points
Alert - Buy on EURUSD.Z: BID Gained from 1.12757 to 1.1277 (+ 0.12999999999999998) Points
Alert - Buy on GBPJPY.Z: BID Gained from 193.176 to 193.215 (+ 39.0) Points
Alert - Sell on GBPUSD.Z: BID Lost from 1.34108 to 1.34091 (- 0.17) Points
Alert - Sell on USDCAD.Z: BID Lost from 1.38504 to 1.38456 (- 0.48000000000000004) Points
Alert - Buy on USDJPY.Z: BID Gained from 143.986 to 144.008 (+ 22.0) Points
Alert - Buy on USDCAD.Z: BID Gained from 1.38456 to 1.38481 (+ 0.25) Points
Assistant
The main issue is that you multiply diff by a fixed 1000 when converting to points — this works roughly for JPY pairs (where 1 point = 0.001), but not for others (like EURUSD), where 1 point = 0.00001.
To fix this properly, you need to calculate the point value depending on the pair, then convert diff to points by dividing by that point value.
Here is your fixed and improved code, including:
Dynamic point values per pair (JPY pairs have 0.001 point size, others 0.00001)
Correct points calculation and formatted output
Slight rounding for clearer printed points
python
User
how can i export the data into a csv file and append it as alerts appear on the console
Assistant
You can easily append alerts to a CSV file each time they are generated, alongside printing them to the console.
Here’s how to modify your existing script to append alert lines to a CSV file, say alerts_log.csv:
Steps to add alert logging:
Open the CSV file in append mode when printing alerts.
Write each alert as a new line with columns you want, e.g.: Timestamp, Pair, Old_BID, New_BID, Points, Direction
Use Python's built-in csv module to write rows safely.
Here’s your updated script snippet with alert CSV logging:
python
Not yet included in a published release.
Sub CheckSuddenMove(oEvent)
Dim oSheet As Object
Dim currentValue As Double
Dim prevValue As Double
Dim threshold As Double
Dim alertCell As Object
Dim prevValueCell As Object
Dim currentValueCell As Object
Dim diff As Double
threshold = 10 ' Define your threshold here
oSheet = ThisComponent.Sheets(0) ' First sheet; change index if needed
currentValueCell = oSheet.getCellRangeByName("A2")
prevValueCell = oSheet.getCellRangeByName("B2")
alertCell = oSheet.getCellRangeByName("C2")
' Make sure the cells contain numbers
If IsNumeric(currentValueCell.getValue()) Then
currentValue = currentValueCell.getValue()
Else
currentValue = 0
End If
If IsNumeric(prevValueCell.getValue()) Then
prevValue = prevValueCell.getValue()
Else
prevValue = currentValue ' First time, set prev = current
prevValueCell.setValue(prevValue)
alertCell.String = ""
Exit Sub
End If
diff = Abs(currentValue - prevValue)
If diff > threshold Then
alertCell.String = "Alert"
Else
alertCell.String = ""
End If
' Update previous value with current
prevValueCell.setValue(currentValue)
End Sub
4. Assign the macro to the sheet event
Open Calc.
Go to Tools > Macros > Organize Macros > LibreOffice Basic...
Create a new macro or add above code to a module.
Then assign the macro to the "Content changed" event:
Right-click sheet tab > Sheet Events...
Find "Content changed" event
Click Macro...
Select your macro CheckSuddenMove
Press OK.
5. How it works:
Every time you change something on the sheet, the macro triggers.
It compares the current value in A2 to stored previous value in B2.
If difference > threshold, it writes "Alert" in C2.
Then updates B2 to new current value.
If difference ≤ threshold, it clears C2 and still updates B2.
Notes:
This simple macro assumes A2 contains numeric values.
You can adjust the threshold inside the macro.
To avoid the alert triggering on unrelated changes, you may consider checking if the changed cell is A2 only. That would be an enhancement.
Optional: Restrict macro to run only when A2 changes:
Enhance CheckSuddenMove like this:
basic
Sub CheckSuddenMove(oEvent)
Dim changedRange As Object
changedRange = oEvent.Range
If Not changedRange.Address(0,0) = "A2" Then
Exit Sub ' Do nothing if other cells changed
End If
' ... rest of code from above
End Sub
BUT note that oEvent.Range sometimes returns multiple cells if multiple cells changed at once, so you may need to test carefully or simplify.
If you want, I can draft a ready-to-import macro file or provide detailed help on any step!
How to assign correctly:
Make sure you assign this macro to Sheet > Sheet Events > Content changed.
The macro must be in a standard module (e.g., Standard.Module1).
The macro must have either zero or exactly one Optional parameter.
Optional: Limit macro trigger to just when A2 changes (advanced)
If you want fine control and to avoid unnecessary re-triggers on other cells, you can handle the parameter oEvent if it gives info on changed range, but Sheet Content changed event does not always provide that reliably.
If you want that, you can assign the macro to the Cell Content changed event of cell A2 instead:
Right-click cell A2 > Assign Macro (depending on your LibreOffice version).
Or assign macro to "Content changed" event for cell A2 only instead of whole sheet.
Summary
Make your macro accept Optional oEvent As Object (or no parameters).
Assign macro to the event.
Retry, and it should not give the wrong number of parameters error.
If you want me to help you setup full working sample step-by-step, just ask!
2. Assign the macro to Calc sheet event “Content changed”
Right-click the sheet tab at the bottom (e.g., "Sheet1").
Select Sheet Events…
Find the event called Content changed.
Click the Macro... button.
Select your macro (CheckSuddenMove) in the macro organizer window.
Click OK.
3. What happens now?
Whenever you edit ANY cell on that sheet, LibreOffice will run this macro.
The macro grabs the current value in A2.
Compares with saved previous value in B2.
Alerts in C2 if difference > 0.0001.
Updates B2 as the new previous value, ready for the next change.
4. Optional enhancement: Run macro only when A2 changes
Running the macro on every change to the sheet might be inefficient if you have lots of other data.
You can modify the macro to check if the changed cell includes A2, but the Sheet Content changed event’s parameter oEvent may not reliably expose the changed range.
Workaround: Assign the macro to A2's cell event if your LibreOffice version supports it:
Select cell A2.
In the menu go to Sheet > Cell Events (if available in your version).
Assign CheckSuddenMove.
If not available, stick with Sheet Content changed.
OR modify macro to:
basic
Sub CheckSuddenMove(Optional oEvent As Object)
Dim changedRange As Object
Dim addresses() As String
Dim i As Integer
Dim foundA2 As Boolean
foundA2 = False
If Not IsMissing(oEvent) Then
changedRange = oEvent.Range
If Not IsNull(changedRange) Then
addresses = Split(changedRange.AbsoluteName, ",")
For i = LBound(addresses) To UBound(addresses)
If Trim(addresses(i)) = "A2" Then
foundA2 = True
Exit For
End If
Next i
End If
End If
If Not foundA2 Then Exit Sub ' Exit if A2 not changed
' -- Then continue with your comparison code below
' (same as previously)
Dim oSheet As Object
Dim currentValue As Double
Dim prevValue As Double
Dim threshold As Double
Dim alertCell As Object
Dim prevValueCell As Object
Dim currentValueCell As Object
Dim diff As Double
threshold = 0.0001
oSheet = ThisComponent.Sheets(0)
currentValueCell = oSheet.getCellRangeByName("A2")
prevValueCell = oSheet.getCellRangeByName("B2")
alertCell = oSheet.getCellRangeByName("C2")
If Not IsNumeric(currentValueCell.getValue()) Then Exit Sub
currentValue = currentValueCell.getValue()
If IsNumeric(prevValueCell.getValue()) Then
prevValue = prevValueCell.getValue()
Else
prevValue = currentValue
prevValueCell.setValue(prevValue)
alertCell.String = ""
Exit Sub
End If
diff = Abs(currentValue - prevValue)
If diff > threshold Then
alertCell.String = "Alert"
Else
alertCell.String = ""
End If
prevValueCell.setValue(currentValue)
End Sub
Note: The above check for changed range may or may not work perfectly depending on your LibreOffice version and event, so test carefully.
5. Save your workbook as macro-enabled format (.ods) to keep macros.
Summary
Your macro triggers automatically at every sheet change.
It compares A2 to previous value stored in B2.
Shows "Alert" in C2 if jump > 0.0001.
Updates B2 to current value so the next change compares properly.
No manual running needed.
If you want a full working .ods example or help debugging your macro, just ask!
Global g_TimerId as Long
Sub StartAutoCheck()
' Start timer that runs every 1 second (1000 ms)
g_TimerId = CreateUnoService("com.sun.star.awt.Timer")
g_TimerId.Interval = 1000 ' milliseconds
AddHandler g_TimerId, "timer", GetRef("AutoCheck")
g_TimerId.Enabled = True
End Sub
Sub StopAutoCheck()
If g_TimerId Is Nothing Then Exit Sub
g_TimerId.Enabled = False
RemoveHandler g_TimerId, "timer", GetRef("AutoCheck")
Set g_TimerId = Nothing
End Sub
Sub AutoCheck(e As Object)
Dim oSheet As Object
Dim currentValue As Double
Dim prevValue As Double
Dim threshold As Double
Dim alertCell As Object
Dim prevValueCell As Object
Dim currentValueCell As Object
Dim diff As Double
threshold = 0.0001
oSheet = ThisComponent.Sheets(0) ' Change if not first sheet
currentValueCell = oSheet.getCellRangeByName("A2")
prevValueCell = oSheet.getCellRangeByName("B2")
alertCell = oSheet.getCellRangeByName("C2")
If Not IsNumeric(currentValueCell.getValue()) Then Exit Sub
currentValue = currentValueCell.getValue()
If IsNumeric(prevValueCell.getValue()) Then
prevValue = prevValueCell.getValue()
Else
prevValue = currentValue
prevValueCell.setValue(prevValue)
alertCell.String = ""
Exit Sub
End If
diff = Abs(currentValue - prevValue)
If diff > threshold Then
alertCell.String = "Alert"
Else
alertCell.String = ""
End If
prevValueCell.setValue(currentValue)
End Sub
How to use this:
Add the above code to your macro module.
Run the StartAutoCheck macro once manually (or link it to document open event) — this sets a timer to run the check every second.
When you want to stop the automatic checking, run StopAutoCheck.
Important:
The timer macro runs in the background and checks/corrects B2 and C2 for changes in A2 every second.
This works even if A2 changes because of formula/result update or external data refresh.
You must run StartAutoCheck once per session.
Linking it to the document open event so it starts automatically:
Go to Tools → Customize → Events Tab.
Assign the macro StartAutoCheck to Open Document event.
Now it will start checking whenever the file opens.
Option 2: If your value in A2 updates manually (you type or paste new values), then the Content changed event should work fine.
If not, make sure:
Your macro is assigned to the exact sheet you are editing.
You did not assign it to the whole document by mistake.
The macro has no error.
You actually triggered an edit event by typing or changing the value manually (not a formula recalculation).
Summary
If A2 is updated by formulas or external refresh, event-based macro won't fire.
Use a timer-based macro running every second or so.
Assign StartAutoCheck to run on document open to automate.
If you want, I can prepare the timer macro with better comments and help create it step-by-step in your LibreOffice.
Would you like me to do that?
Summary:
Remove any other Global g_TimerId declarations elsewhere in the module.
Make sure only oneGlobal g_TimerId As Object exists, at the top.
g_TimerId must be typed as Object, NOT Long.
Paste the rest of your subs as above below the global declaration.
Optional:
Run StartAutoCheck macro once manually to start periodic checking.
Run StopAutoCheck to stop it.
Or assign StartAutoCheck to document open event to start automatically.
If you still see errors or want a complete working example .ods file, just ask!
basic
Sub CheckSuddenMove(Optional oEvent As Object)
Dim oSheet As Object
Dim currentValue As Double
Dim prevValue As Double
Dim threshold As Double
Dim alertCell As Object
Dim prevValueCell As Object
Dim currentValueCell As Object
Dim diff As Double
threshold = 0.00015
oSheet = ThisComponent.Sheets(0)
currentValueCell = oSheet.getCellRangeByName("B3")
prevValueCell = oSheet.getCellRangeByName("E3")
alertCell = oSheet.getCellRangeByName("F3")
If Not IsNumeric(currentValueCell.getValue()) Then Exit Sub
currentValue = currentValueCell.getValue()
If IsNumeric(prevValueCell.getValue()) Then
prevValue = prevValueCell.getValue()
Else
prevValue = currentValue
prevValueCell.setValue(prevValue)
alertCell.String = ""
Exit Sub
End If
diff = Abs(currentValue - prevValue)
If diff > threshold Then
alertCell.String = "Alert"
Else
alertCell.String = ""
End If
prevValueCell.setValue(currentValue)
End Sub
How to assign this macro on Calculate event:
Tools > Customize > Events tab
Select Calculate event
Click Macro...
Choose your macro and click OK.
Option 3: Use a Python macro with timer (advanced)
If you really want automatic periodic checks, it usually requires more advanced scripting, like Python macros hooked to timers or external scripts triggering LibreOffice, which is beyond typical LibreOffice Basic usage.
TL;DR
LibreOffice Basic does not support VBA-like timer objects.
Use either:
Manual button click to run your macro, OR
Hook to the Calculate event if your data changes cause recalculation.
Avoid trying to create timer-based macros in LibreOffice Basic.
If any help required to set up the Calculate event or button, just ask!
How to use this:
Save as bid_monitor.py
Ensure your LiveData.csv has tab-separated values, with columns exactly: Time, BID, ASK, PAIR
Run in terminal:
code
python bid_monitor.py
The script will scan the full CSV every second and compare the latest BID for each pair with the previously stored BID.
It prints alerts whenever price jumps more than your threshold.
Notes / Improvements you can consider
Performance: If the file grows large, reading entirely every second is costly. You can implement a more efficient approach like tailing the file or storing last file size/position.
Timestamp ordering: You may want to process rows incrementally based on timestamp (here we just read all, assuming CSV is fully updated every time).
Output: Send alerts via email, logging to file, or user interface.
Error handling: More robust parsing and validation.
More granular alerts: Track upward/downward move, or % change.
Cross-platform alerts: Integrate with desktop notifications or messaging platforms.
If you want, I can help you build a more robust version or integrate it with LibreOffice Calc via Python UNO bridge or just output alerts to a separate file.
Let me know if you'd like that!
r
o
j
ec
t
s
/
s
t
oc
ks
cr
ee
n
er
/
bi
dp
r
i
c
em
o
ni
t
or
.
p
y
S
t
a
r
t
in
g
l
i
v
e
B
I
D
m
o
ni
t
or
...
(
C
T
R
L
+
Ctostop)CStoppingmonitor.dulu@dulu:
same number of rows
If new rows are appended or old rows removed, the length of rows changes, so it will process.
If file content updates but row count does not, the script ignores this for simplicity.
What if your live data is updated in place (not by adding/removing rows)?
Your script currently detects changes only if row count changes. But if your CSV is fully rewritten every second with the same number of rows but updated BID values, your code will not detect these price changes.
How to fix for that scenario?
Modify the script to always check for alerts regardless of row count change.
If you'd like, I can provide you a ready-to-run updated full script with this logic incorporated. Just say!
Explanation of changes:
Removed the old print of row counts.
Added direction logic based on whether new BID > prev BID.
Adjusted alert message per your format specifying Buy or Sell.
Rounded diff to 8 decimal places for cleaner output.
Run this script, and you will only see alerts printed for pairs where the BID changed beyond their threshold, formatted with Buy or Sell and price movement message.
If you want to log to file or get notifications instead, just ask!
import csv
import time
csv_file_path = '/home/dulu/.mt5/drive_c/Program Files/MetaTrader 5/MQL5/Files/LiveData.csv'
# Thresholds per exact pair name
pair_thresholds = {
'EURJPY.Z': 0.01,
'GBPJPY.Z': 0.01,
'USDJPY.Z': 0.01,
# Add other pairs here if needed
}
default_threshold = 0.0001
last_bid_prices = {}
def get_threshold(pair):
return pair_thresholds.get(pair.upper(), default_threshold)
def get_point_value(pair):
# Define point size per pair, based on JPY or others
pair = pair.upper()
if 'JPY' in pair:
return 0.001 # 1 point = 0.001 for JPY pairs
else:
return 0.00001 # 1 point = 0.00001 for others
def read_csv_latest_rows(filename):
with open(filename, newline='') as csvfile:
reader = csv.DictReader(csvfile, delimiter='\t')
return list(reader)
def check_for_alerts(rows):
alerts = []
for row in rows:
pair = row['PAIR']
try:
bid = float(row['BID'])
except ValueError:
continue
prev_bid = last_bid_prices.get(pair)
if prev_bid is not None:
threshold = get_threshold(pair)
diff = round(abs(bid - prev_bid), 8) # rounded price diff
if diff > threshold:
direction = "Buy" if bid > prev_bid else "Sell"
alerts.append((pair, prev_bid, bid, diff, direction))
last_bid_prices[pair] = bid
return alerts
def main():
print("Starting live BID monitor... (CTRL+C to stop)")
while True:
try:
rows = read_csv_latest_rows(csv_file_path)
alerts = check_for_alerts(rows)
for pair, old_bid, new_bid, diff, direction in alerts:
point_value = get_point_value(pair)
points = round(diff / point_value, 1) # convert diff to points
if direction == "Buy":
print(f"Alert - Buy on {pair}: BID Gained from {old_bid} to {new_bid} (+ {points}) Points")
else:
print(f"Alert - Sell on {pair}: BID Lost from {old_bid} to {new_bid} (- {points}) Points")
time.sleep(5) # Adjust as needed
except KeyboardInterrupt:
print("\nStopping monitor.")
break
except FileNotFoundError:
print(f"{csv_file_path} not found, waiting...")
time.sleep(5)
except Exception as e:
print(f"Error: {e}")
time.sleep(5)
if __name__ == "__main__":
main()
Explanation of changes:
get_point_value(pair) returns correct multipliers for JPY vs others.
Points calculated as diff / point_value — e.g.,
For EURUSD: point_value=0.00001 → points = diff / 0.00001
For USDJPY: point_value=0.001 → points = diff / 0.001
Rounded output points to 1 decimal place for clarity.
Alert messages print points with +/- sign depending on Buy or Sell.
Example output (should look like):
code
Alert - Buy on GBPJPY.Z: BID Gained from 193.102 to 193.15 (+ 48.0) Points
Alert - Sell on AUDUSD.Z: BID Lost from 0.64105 to 0.64078 (- 27.0) Points
Alert - Buy on EURJPY.Z: BID Gained from 162.411 to 162.465 (+ 54.0) Points
Alert - Buy on EURUSD.Z: BID Gained from 1.12757 to 1.1277 (+ 13.0) Points
...
Let me know if you'd like me to help with other improvements or logging!
import csv
import time
from datetime import datetime
csv_file_path = '/home/dulu/.mt5/drive_c/Program Files/MetaTrader 5/MQL5/Files/LiveData.csv'
alert_log_file = 'alerts_log.csv' # Output alert CSV file
# Thresholds per exact pair name
pair_thresholds = {
'EURJPY.Z': 0.01,
'GBPJPY.Z': 0.01,
'USDJPY.Z': 0.01,
# Add other pairs here if needed
}
default_threshold = 0.0001
last_bid_prices = {}
def get_threshold(pair):
return pair_thresholds.get(pair.upper(), default_threshold)
def get_point_value(pair):
pair = pair.upper()
if 'JPY' in pair:
return 0.001 # 1 point = 0.001 for JPY pairs
else:
return 0.00001 # 1 point = 0.00001 for others
def read_csv_latest_rows(filename):
with open(filename, newline='') as csvfile:
reader = csv.DictReader(csvfile, delimiter='\t')
return list(reader)
def check_for_alerts(rows):
alerts = []
for row in rows:
pair = row['PAIR']
try:
bid = float(row['BID'])
except ValueError:
continue
prev_bid = last_bid_prices.get(pair)
if prev_bid is not None:
threshold = get_threshold(pair)
diff = round(abs(bid - prev_bid), 8)
if diff > threshold:
direction = "Buy" if bid > prev_bid else "Sell"
alerts.append((pair, prev_bid, bid, diff, direction))
last_bid_prices[pair] = bid
return alerts
def log_alert(alert):
"""
Append alert to CSV file:
alert = (pair, old_bid, new_bid, diff, direction)
"""
pair, old_bid, new_bid, diff, direction = alert
point_value = get_point_value(pair)
points = round(diff / point_value, 1)
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
with open(alert_log_file, mode='a', newline='') as file:
writer = csv.writer(file)
writer.writerow([timestamp, pair, old_bid, new_bid, points, direction])
def main():
print("Starting live BID monitor... (CTRL+C to stop)")
# Write CSV header if the log file does not exist or is empty
try:
with open(alert_log_file, 'x', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Timestamp', 'Pair', 'Old_BID', 'New_BID', 'Points', 'Direction'])
except FileExistsError:
pass # file exists, no need to write header
while True:
try:
rows = read_csv_latest_rows(csv_file_path)
alerts = check_for_alerts(rows)
for alert in alerts:
pair, old_bid, new_bid, diff, direction = alert
point_value = get_point_value(pair)
points = round(diff / point_value, 1)
sign = '+' if direction == 'Buy' else '-'
print(f"Alert - {direction} on {pair}: BID {'Gained' if direction=='Buy' else 'Lost'} from {old_bid} to {new_bid} ({sign} {points}) Points")
log_alert(alert) # Append alert to CSV
time.sleep(5)
except KeyboardInterrupt:
print("\nStopping monitor.")
break
except FileNotFoundError:
print(f"{csv_file_path} not found, waiting...")
time.sleep(5)
except Exception as e:
print(f"Error: {e}")
time.sleep(5)
if __name__ == "__main__":
main()
Explanation:
The function log_alert(alert) writes the alert line to alerts_log.csv appending to file.
On start, the script tries to create the log file and add a header row (won’t overwrite existing file).
Each alert printed to console is also appended to the CSV file.
Timestamp is added to help you trace when the alert happened.
Result
You’ll get console alerts and a continuously growing CSV file you can open in Excel, LibreOffice, or analyze with other tools.
If you want help formatting the CSV file differently or adding more fields, just let me know!