The Conti e posizioni screen follows mockup 02: totals split by strategy, one card per account with key permissions and the last reconciliation, positions with a per-account filter and CSV export, pending stops (Alpaca grouped into permanent and day stops), residues, and exposure by currency. It shows one world only, real accounts when there are any, so simulated and real money never add up. Position values are rounded to the cent per row, as the table shows them, so the figures add up on screen. Settings gain "Conti e chiavi": practice keys are asked to the broker before they are saved and refused when they may withdraw or cannot trade; they are never shown again and the engine restarts to use them. The capital entrusted to each broker is set there in euro. Until any capital is set, the overview points to that section as the first step. The overview now reads one world, nets capital flows out of its results and uses the time-weighted index; open orders exclude protective stops. The demo seed gains cash rows, closed trades, stops, the ECB rate and the reconciliation state, so the ledger itself computes the mockup's figures. Screenshots now capture the whole page and include Conti. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
194 lines
6.8 KiB
C#
194 lines
6.8 KiB
C#
using System.Diagnostics;
|
|
using System.Net.WebSockets;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Nodes;
|
|
|
|
/// <summary>
|
|
/// Screenshots through the DevTools protocol of the Edge or Chrome already installed (ADR 0007). The protocol sets the
|
|
/// exact width: a headless window cannot be narrower than about 500 pixels, too wide for the 390-pixel phone.
|
|
/// </summary>
|
|
internal sealed class Shots : IDisposable
|
|
{
|
|
private readonly Process _browser;
|
|
private readonly ClientWebSocket _socket = new();
|
|
private readonly string _profile;
|
|
private int _id;
|
|
|
|
private Shots(Process browser, string profile)
|
|
{
|
|
_browser = browser;
|
|
_profile = profile;
|
|
}
|
|
|
|
public static Shots Start(string browserPath)
|
|
{
|
|
var profile = Path.Combine(Path.GetTempPath(), "anubis-shots-" + Guid.NewGuid().ToString("N"));
|
|
var info = new ProcessStartInfo(browserPath)
|
|
{
|
|
UseShellExecute = false,
|
|
RedirectStandardOutput = true,
|
|
RedirectStandardError = true,
|
|
};
|
|
foreach (var argument in new[] { "--headless=new", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check",
|
|
"--remote-debugging-port=0", "--user-data-dir=" + profile, "about:blank" })
|
|
{
|
|
info.ArgumentList.Add(argument);
|
|
}
|
|
|
|
var process = Process.Start(info)!;
|
|
process.OutputDataReceived += (_, _) => { };
|
|
process.ErrorDataReceived += (_, _) => { };
|
|
process.BeginOutputReadLine();
|
|
process.BeginErrorReadLine();
|
|
var shots = new Shots(process, profile);
|
|
try
|
|
{
|
|
shots.Connect();
|
|
return shots;
|
|
}
|
|
catch
|
|
{
|
|
shots.Dispose();
|
|
throw;
|
|
}
|
|
}
|
|
|
|
// The browser writes its port into DevToolsActivePort; the page target is found through /json/list.
|
|
private void Connect()
|
|
{
|
|
var portFile = Path.Combine(_profile, "DevToolsActivePort");
|
|
for (var i = 0; i < 60 && !File.Exists(portFile); i++)
|
|
{
|
|
Thread.Sleep(250);
|
|
}
|
|
|
|
var port = File.ReadAllLines(portFile)[0].Trim();
|
|
using var http = new HttpClient();
|
|
string? target = null;
|
|
for (var i = 0; i < 40 && target is null; i++)
|
|
{
|
|
var list = JsonNode.Parse(http.GetStringAsync(new Uri($"http://127.0.0.1:{port}/json/list")).GetAwaiter().GetResult())!.AsArray();
|
|
target = list.FirstOrDefault(t => (string?)t!["type"] == "page")?["webSocketDebuggerUrl"]?.GetValue<string>();
|
|
if (target is null)
|
|
{
|
|
Thread.Sleep(250);
|
|
}
|
|
}
|
|
|
|
_socket.ConnectAsync(new Uri(target ?? throw new InvalidOperationException("Nessuna pagina nel browser.")), CancellationToken.None).GetAwaiter().GetResult();
|
|
Send("Page.enable", new JsonObject());
|
|
}
|
|
|
|
/// <summary>Opens <paramref name="url"/> at the given size and theme and saves the visible part as PNG.</summary>
|
|
public void Take(string url, int width, int height, bool dark, string file)
|
|
{
|
|
Send("Emulation.setDeviceMetricsOverride", new JsonObject
|
|
{
|
|
["width"] = width,
|
|
["height"] = height,
|
|
["deviceScaleFactor"] = 2,
|
|
["mobile"] = width < 768,
|
|
});
|
|
Send("Emulation.setEmulatedMedia", new JsonObject
|
|
{
|
|
["features"] = new JsonArray(new JsonObject { ["name"] = "prefers-color-scheme", ["value"] = dark ? "dark" : "light" }),
|
|
});
|
|
Send("Page.navigate", new JsonObject { ["url"] = url }, waitForEvent: "Page.loadEventFired");
|
|
Thread.Sleep(500);
|
|
|
|
// The whole page, not just the first screen: a page taller than the window grows the window to fit.
|
|
var metrics = Send("Page.getLayoutMetrics", new JsonObject());
|
|
var full = (int)Math.Ceiling(metrics["cssContentSize"]?["height"]?.GetValue<double>() ?? height);
|
|
if (full > height)
|
|
{
|
|
Send("Emulation.setDeviceMetricsOverride", new JsonObject
|
|
{
|
|
["width"] = width,
|
|
["height"] = full,
|
|
["deviceScaleFactor"] = 2,
|
|
["mobile"] = width < 768,
|
|
});
|
|
Thread.Sleep(300);
|
|
}
|
|
|
|
var result = Send("Page.captureScreenshot", new JsonObject { ["format"] = "png" });
|
|
File.WriteAllBytes(file, Convert.FromBase64String(result["data"]!.GetValue<string>()));
|
|
}
|
|
|
|
// Sends one command and waits for its answer (and, if asked, for an event), skipping everything else.
|
|
private JsonNode Send(string method, JsonObject parameters, string? waitForEvent = null)
|
|
{
|
|
var id = ++_id;
|
|
var message = new JsonObject { ["id"] = id, ["method"] = method, ["params"] = parameters };
|
|
_socket.SendAsync(Encoding.UTF8.GetBytes(message.ToJsonString()), WebSocketMessageType.Text, true, CancellationToken.None).GetAwaiter().GetResult();
|
|
JsonNode? answer = null;
|
|
var eventSeen = waitForEvent is null;
|
|
using var limit = new CancellationTokenSource(TimeSpan.FromSeconds(30));
|
|
while (answer is null || !eventSeen)
|
|
{
|
|
var received = Receive(limit.Token);
|
|
if ((int?)received["id"] == id)
|
|
{
|
|
if (received["error"] is { } error)
|
|
{
|
|
throw new InvalidOperationException(method + ": " + error.ToJsonString());
|
|
}
|
|
|
|
answer = received["result"] ?? new JsonObject();
|
|
}
|
|
else if ((string?)received["method"] == waitForEvent)
|
|
{
|
|
eventSeen = true;
|
|
}
|
|
}
|
|
|
|
return answer;
|
|
}
|
|
|
|
private JsonNode Receive(CancellationToken cancellationToken)
|
|
{
|
|
var buffer = new byte[64 * 1024];
|
|
using var all = new MemoryStream();
|
|
WebSocketReceiveResult result;
|
|
do
|
|
{
|
|
result = _socket.ReceiveAsync(buffer, cancellationToken).GetAwaiter().GetResult();
|
|
all.Write(buffer, 0, result.Count);
|
|
}
|
|
while (!result.EndOfMessage);
|
|
|
|
return JsonNode.Parse(all.ToArray(), documentOptions: new JsonDocumentOptions { MaxDepth = 64 })!;
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
_socket.Dispose();
|
|
try
|
|
{
|
|
_browser.Kill(entireProcessTree: true);
|
|
_browser.WaitForExit(5000);
|
|
}
|
|
catch (InvalidOperationException)
|
|
{
|
|
}
|
|
|
|
_browser.Dispose();
|
|
for (var i = 0; i < 10 && Directory.Exists(_profile); i++)
|
|
{
|
|
try
|
|
{
|
|
Directory.Delete(_profile, recursive: true);
|
|
}
|
|
catch (IOException)
|
|
{
|
|
Thread.Sleep(300);
|
|
}
|
|
catch (UnauthorizedAccessException)
|
|
{
|
|
Thread.Sleep(300);
|
|
}
|
|
}
|
|
}
|
|
}
|