Files
mika@stocksharp.com 5b9fd0bf96 Harden analytics and compilation scripts
WHAT A SCRIPT PRINTS. The Python engine writes bytes and picks where to cut them, so a multi-byte
character arrives split between two writes. Decoding each write on its own turned such a character
into replacement marks - "тест 🚀" logged as "тест ???" - so the stream now decodes through a
stateful decoder that keeps an incomplete tail until the rest of its bytes turn up, guarded by a lock
because one stream serves concurrently running scripts. The buffer it decodes into is grown to fit
and then reused rather than allocated per write: this is the sink for everything a running script
prints, a line at a time. Only what the current write decoded is read back, so what a longer earlier
write left further along is never seen.

WHAT A CANCELLED RUN DOES. Init checked no token at all, and its blanket catch around each
common-file write swallowed the cancellation the file system raised - a caller who gave up was told
the environment was ready. It now checks before it starts and before each write, and lets
cancellation leave by the door it came in. The analytics scripts did the same thing differently:
they broke out of their loops on a cancelled token and then carried on to report a result computed
from half the data. They throw instead, in every language and at every level of the loop.

THE PYTHON BRIDGE TO AN ASYNC SEQUENCE. IronPython blocked on MoveNextAsync and DisposeAsync through
GetAwaiter().GetResult(). Those ValueTasks are backed by the async iterator's own state machine
rather than by a Task, and GetResult on such a ValueTask does not wait - it throws unless the
operation has already finished, which over an in-memory storage it has not. Both now bridge through
AsTask(), and DisposeAsync is invoked through IAsyncDisposable because IronPython cannot see an
explicit interface implementation as an instance member.

CORRELATION OVER TIME RATHER THAN OVER POSITION. Pearson collected each instrument's closes into a
flat list and lined the series up by index, so a minute missing from one instrument shifted
everything after it and the answer was a correlation of two series that were never contemporaneous.
The closes are keyed by candle time and correlated over the moments the instruments share.

AND A MATRIX THAT IS NOT ONE. The numpy bridge accepted ragged input and a None row, and produced
whatever fell out. It now says which row is the wrong length instead.
2026-09-14 18:22:25 +03:00

94 lines
3.9 KiB
FSharp

namespace StockSharp.Algo.Analytics
open System
open System.Linq
open System.Collections.Generic
open System.Threading
open System.Threading.Tasks
open Ecng.Common
open Ecng.Drawing
open Ecng.Logging
open FSharp.Control
open StockSharp.Algo.Analytics
open StockSharp.Algo.Storages
open StockSharp.Algo.Candles
open StockSharp.Messages
/// <summary>
/// The analytic script, normalize securities close prices and shows on the same chart.
/// </summary>
type NormalizePriceScript() =
interface IAnalyticsScript with
member this.Run
(
logs: ILogReceiver,
panel: IAnalyticsPanel,
securities: SecurityId[],
fromDate: DateTime,
toDate: DateTime,
storage: IStorageRegistry,
drive: IMarketDataDrive,
format: StorageFormats,
dataType: DataType,
cancellationToken: CancellationToken
) : Task =
task {
cancellationToken.ThrowIfCancellationRequested()
if securities.Length = 0 then
logs.LogWarning("No instruments.")
else
// Create a chart for normalized close prices
let chart = panel.CreateChart<DateTime, decimal>()
let mutable idx = 0
// Iterate over each security
for security in securities do
cancellationToken.ThrowIfCancellationRequested()
idx <- idx + 1
logs.LogInfo("Processing {0} of {1}: {2}...", idx, securities.Length, security)
cancellationToken.ThrowIfCancellationRequested()
// Dictionary to store time -> normalized close price
let series = Dictionary<DateTime, decimal>()
// Get candle storage for this security
let candleStorage = storage.GetCandleMessageStorage(security, dataType, drive, format)
// We'll store the first close price in a mutable option
let mutable firstClose: decimal option = None
let mutable prevDate = DateOnly.MinValue
// Load candles and normalize close prices
do! candleStorage.LoadAsync(fromDate, toDate).WithEnforcedCancellation(cancellationToken)
|> TaskSeq.iter (fun candle ->
cancellationToken.ThrowIfCancellationRequested()
let currDate = DateOnly.FromDateTime(candle.OpenTime.Date)
if currDate <> prevDate then
prevDate <- currDate
logs.LogInfo(" {0}...", currDate)
cancellationToken.ThrowIfCancellationRequested()
match firstClose with
| None ->
// A zero first close provides no normalization base. Remember it,
// but do not draw the raw price as if it were a ratio of one.
firstClose <- Some candle.ClosePrice
if candle.ClosePrice <> 0m then
series.[candle.OpenTime] <- 1m
| Some fc ->
// Divide by the first close price to normalize
if fc <> 0m then
series.[candle.OpenTime] <- candle.ClosePrice / fc
)
// Add the series for this security to the chart
chart.Append(security.ToStringId(), series.Keys, series.Values)
}