Sample SMA strategy

This commit is contained in:
Michael Schimmel
2025-09-03 13:41:24 +02:00
parent 3e4ca283c9
commit 6b9dcee417
9 changed files with 505 additions and 179 deletions
+206 -35
View File
@@ -10,6 +10,7 @@ uses
System.Classes,
System.Variants,
System.Generics.Collections,
System.Math,
FMX.Types,
FMX.Controls,
FMX.Forms,
@@ -31,6 +32,16 @@ uses
FMX.Objects; // Added for TExecutionScope
type
// A test record
TOHLCV = record
Timestamp: TDateTime;
Open: Double;
High: Double;
Low: Double;
Close: Double;
Volume: Int64;
end;
TForm1 = class(TForm)
Panel1: TPanel;
Memo1: TMemo;
@@ -48,6 +59,7 @@ type
ClearButton: TButton;
FlowOnlyBox: TCheckBox;
SeriesTestButton: TButton;
OHLCButton: TButton;
procedure ClearButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure CrerateTriggerExampleButtonClick(Sender: TObject);
@@ -55,6 +67,7 @@ type
procedure DoTrigger2ButtonClick(Sender: TObject);
procedure DoTriggerButtonClick(Sender: TObject);
procedure FibonacciButtonClick(Sender: TObject);
procedure OHLCButtonClick(Sender: TObject);
procedure PrettyPrintButtonClick(Sender: TObject);
procedure RecursionButtonClick(Sender: TObject);
procedure SeriesTestButtonClick(Sender: TObject);
@@ -62,7 +75,7 @@ type
procedure Test2ButtonClick(Sender: TObject);
private
// Stores the last AST generated by Test1 or Test2 button clicks.
FLastAst: IAstNode;
FLastAst: IExpressionNode;
FGScope: IExecutionScope;
FWorkspace: TAuraWorkspace;
procedure WorkspaceMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
@@ -308,12 +321,11 @@ begin
Memo1.Lines.Add('--- Recursive factorial(20) ---');
sw.Start;
{
root :=
TAst.Block(
[
TAst.VarDecl(
TAst.Identifier('factorial'),
TAst.FunctionCall(
TAst.LambdaExpr(
[TAst.Identifier('n')],
TAst.Block(
@@ -327,7 +339,7 @@ begin
TAst.Identifier('n'),
boMultiply,
TAst.FunctionCall(
TAst.Identifier('factorial'),
TAst.Identifier('Self'),
[TAst.BinaryExpr(TAst.Identifier('n'), boSubtract, TAst.Constant(TScalar.FromInt64(1)))]
)
)
@@ -335,15 +347,9 @@ begin
)
]
)
)
),
[TAst.Constant(TScalar.FromInt64(20))]
),
TAst.FunctionCall(TAst.Identifier('factorial'), [TAst.Constant(TScalar.FromInt64(20))])
]
);
}
root :=
TAst.Block(
[
TAst.VarDecl(
TAst.Identifier('factorial'),
TAst.LambdaExpr(
@@ -357,7 +363,7 @@ begin
TAst.Identifier('n'),
boMultiply,
TAst.FunctionCall(
TAst.Identifier('factorial'),
TAst.Identifier('Self'),
[TAst.BinaryExpr(TAst.Identifier('n'), boSubtract, TAst.Constant(TScalar.FromInt64(1)))]
)
)
@@ -383,16 +389,6 @@ begin
end;
procedure TForm1.SeriesTestButtonClick(Sender: TObject);
type
// A test record to generate a definition from.
TOHLCV = record
Timestamp: TDateTime;
Open: Double;
High: Double;
Low: Double;
Close: Double;
Volume: Int64;
end;
var
jsonDef: string;
recordDef: TScalarRecordDefinition;
@@ -457,8 +453,7 @@ begin
TAst.VarDecl(
TAst.Identifier('secondClose'),
TAst.Indexer(TAst.Identifier('closeColumn'), TAst.Constant(TScalar.FromInt64(1)))
),
TAst.AssignResult(TAst.Identifier('secondClose'))
)
]
)
);
@@ -527,7 +522,7 @@ begin
TAst.Identifier('b'),
TAst.BinaryExpr(TAst.Identifier('a'), boMultiply, TAst.Constant(TScalar.FromInt64(2)))
),
TAst.AssignResult(TAst.BinaryExpr(TAst.Identifier('a'), boAdd, TAst.Identifier('b')))
TAst.BinaryExpr(TAst.Identifier('a'), boAdd, TAst.Identifier('b'))
]
)
);
@@ -570,14 +565,11 @@ begin
TAst.Identifier('createStrategyInstance'),
TAst.LambdaExpr(
[TAst.Identifier('offset')],
Tast.VarDecl(
TAst.Identifier('Result'),
TAst.Block(
[
TAst.VarDecl(TAst.Identifier('baseValue'), TAst.Constant(TScalar.FromInt64(100))),
TAst.BinaryExpr(TAst.Identifier('baseValue'), boAdd, TAst.Identifier('offset'))
]
)
TAst.Block(
[
TAst.VarDecl(TAst.Identifier('baseValue'), TAst.Constant(TScalar.FromInt64(100))),
TAst.BinaryExpr(TAst.Identifier('baseValue'), boAdd, TAst.Identifier('offset'))
]
)
)
),
@@ -721,4 +713,183 @@ begin
end;
end;
procedure TForm1.OHLCButtonClick(Sender: TObject);
const
numRecs = 1000;
lookback = 100;
smaSlowLength = 20;
smaFastLength = 5;
var
recordDef: TScalarRecordDefinition;
series: TScalarRecordSeries;
setupAst: IExpressionNode;
callAst: IExpressionNode;
visitor: IAstVisitor;
i: Integer;
lastClose: Double;
ohlcvRec: TOHLCV;
recordValue: TScalarRecord;
resultValue: TAstValue;
sw: TStopwatch;
begin
// 1. Setup
Memo1.Lines.Clear;
Memo1.Lines.Add(Format('--- Simulating SMA Crossover Strategy for %d ticks ---', [numRecs]));
FGScope.Clear;
RegisterNativeFunctions(FGScope);
sw := TStopwatch.StartNew;
recordDef := TRttiAstHelper.JsonToRecordDefinition(TRttiAstHelper.RecordDefinitionToJson(TypeInfo(TOHLCV)));
series := TScalarRecordSeries.Create(recordDef);
// 2. Create the setup AST. This block defines all necessary functions.
setupAst :=
TAst.Block(
[
// let sumRange = (s, n) => (n <= 0) ? 0.0 : (s[n - 1] + sumRange(s, n - 1));
TAst.VarDecl(
TAst.Identifier('sumRange'),
TAst.LambdaExpr(
[TAst.Identifier('s'), TAst.Identifier('n')],
TAst.TernaryExpr(
TAst.BinaryExpr(TAst.Identifier('n'), boLessOrEqual, TAst.Constant(TScalar.FromInt64(0))),
TAst.Constant(TScalar.FromDouble(0.0)), // Base case for recursion
TAst.BinaryExpr(
TAst.Indexer(
TAst.Identifier('s'),
TAst.BinaryExpr(TAst.Identifier('n'), boSubtract, TAst.Constant(TScalar.FromInt64(1)))
),
boAdd,
TAst.FunctionCall(
TAst.Identifier('sumRange'),
[
TAst.Identifier('s'),
TAst.BinaryExpr(TAst.Identifier('n'), boSubtract, TAst.Constant(TScalar.FromInt64(1)))
]
)
)
)
)
),
// let CreateSMA = (len) => (series) => sumRange(series, len) / len;
TAst.VarDecl(
TAst.Identifier('CreateSMA'),
TAst.LambdaExpr(
[TAst.Identifier('len')],
TAst.LambdaExpr(
[TAst.Identifier('series')],
TAst.BinaryExpr(
TAst.FunctionCall(TAst.Identifier('sumRange'), [TAst.Identifier('series'), TAst.Identifier('len')]),
boDivide,
TAst.Identifier('len')
)
)
)
),
// let smaFast = CreateSMA(5);
TAst.VarDecl(
TAst.Identifier('smaFast'),
TAst.FunctionCall(TAst.Identifier('CreateSMA'), [TAst.Constant(TScalar.FromInt64(smaFastLength))])
),
// let smaSlow = CreateSMA(20);
TAst.VarDecl(
TAst.Identifier('smaSlow'),
TAst.FunctionCall(TAst.Identifier('CreateSMA'), [TAst.Constant(TScalar.FromInt64(smaSlowLength))])
),
// Define the main strategy function
TAst.VarDecl(
TAst.Identifier('maCrossStrategy'),
TAst.LambdaExpr(
[TAst.Identifier('ohlcv')],
TAst.Block(
[
TAst.VarDecl(
TAst.Identifier('close'),
TAst.MemberAccess(TAst.Identifier('ohlcv'), TAst.Identifier('Close'))
),
TAst.VarDecl(
TAst.Identifier('valSmaFast'),
TAst.FunctionCall(TAst.Identifier('smaFast'), [TAst.Identifier('close')])
),
TAst.VarDecl(
TAst.Identifier('valSmaSlow'),
TAst.FunctionCall(TAst.Identifier('smaSlow'), [TAst.Identifier('close')])
),
TAst.TernaryExpr(
TAst.BinaryExpr(TAst.Identifier('valSmaFast'), boGreater, TAst.Identifier('valSmaSlow')),
TAst.Constant(TScalar.FromInt64(1)), // Buy signal
TAst.Constant(TScalar.FromInt64(-1))
) // Sell signal
]
)
)
)
]
);
FLastAst := setupAst; // Store for visualization
visitor := TEvaluatorVisitor.Create(FGScope);
// Execute the setup script once to define all functions in the scope.
setupAst.Accept(visitor);
// Create the AST for the function call that will be executed on each tick.
callAst := TAst.FunctionCall(TAst.Identifier('maCrossStrategy'), [TAst.Identifier('current_series')]);
// 3. Simulation Loop
Memo1.Lines.Add('Starting simulation...');
Application.ProcessMessages;
lastClose := 1000.0;
Randomize;
var nw := Now;
for i := 1 to numRecs do
begin
// Generate a random OHLCV record
ohlcvRec.Timestamp := nw + (i / (24 * 60));
ohlcvRec.Open := lastClose + (Random * 0.05);
ohlcvRec.Close := lastClose + (Random - 0.49) * 2;
ohlcvRec.High := Max(ohlcvRec.Open, ohlcvRec.Close) + Random;
ohlcvRec.Low := Min(ohlcvRec.Open, ohlcvRec.Close) - Random;
ohlcvRec.Volume := RandomRange(1000, 50000);
lastClose := ohlcvRec.Close;
recordValue :=
TScalarRecord.Create(
recordDef,
[
TScalarValue.FromDateTime(ohlcvRec.Timestamp),
TScalarValue.FromDouble(ohlcvRec.Open),
TScalarValue.FromDouble(ohlcvRec.High),
TScalarValue.FromDouble(ohlcvRec.Low),
TScalarValue.FromDouble(ohlcvRec.Close),
TScalarValue.FromInt64(ohlcvRec.Volume)
]
);
series.Add(recordValue, lookback);
// Execute the strategy if we have enough data for the slowest indicator
if series.TotalCount >= smaSlowLength then
begin
// Place the current data into the scope for the callAst to find
FGScope.SetValue('current_series', TAstValue.FromRecordSeries(series));
// Correctly call the strategy function via its identifier
resultValue := callAst.Accept(visitor);
if (i mod 100 = 0) or (i = numRecs) then
begin
Memo1.Lines.Add(Format('Tick %d/%d: Close = %.2f, Signal = %s', [i, numRecs, ohlcvRec.Close, resultValue.ToString]));
Application.ProcessMessages;
end;
end;
end;
sw.Stop;
Memo1.Lines.Add('--- Simulation Finished ---');
Memo1.Lines.Add(Format('Total time: %d ms', [sw.ElapsedMilliseconds]));
end;
end.