46 lines
1.2 KiB
C#
46 lines
1.2 KiB
C#
using System.Text.Json;
|
|
using Backend.DatabaseHandler;
|
|
using Backend.Interface;
|
|
|
|
namespace Backend.ServiceHander;
|
|
|
|
public sealed class PriceThresholdEvaluator : IAlertEvaluator
|
|
{
|
|
public string AlertType => "price_threshold";
|
|
|
|
public Task<AlertEvaluation> EvaluateAsync(AlertRecord alert, MarketDataService marketData)
|
|
{
|
|
var parameters = JsonSerializer.Deserialize<PriceThresholdParameters>(alert.Parameters)
|
|
?? throw new InvalidOperationException($"Invalid parameters for alert {alert.Id}");
|
|
|
|
var snapshot = marketData.GetLiveQuote(alert.Symbol);
|
|
|
|
if (!snapshot.LastPrice.HasValue)
|
|
{
|
|
return Task.FromResult(new AlertEvaluation { Triggered = false });
|
|
}
|
|
|
|
double price = snapshot.LastPrice.Value;
|
|
bool triggered = parameters.Direction.ToLowerInvariant() switch
|
|
{
|
|
"above" => price >= parameters.Target,
|
|
"below" => price <= parameters.Target,
|
|
_ => false
|
|
};
|
|
|
|
string updatedState = JsonSerializer.Serialize(new { lastPrice = price });
|
|
|
|
return Task.FromResult(new AlertEvaluation
|
|
{
|
|
Triggered = triggered,
|
|
UpdatedLastState = updatedState
|
|
});
|
|
}
|
|
|
|
private sealed class PriceThresholdParameters
|
|
{
|
|
public string Direction { get; set; } = string.Empty;
|
|
public double Target { get; set; }
|
|
}
|
|
}
|