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
+1 -1
View File
@@ -4,7 +4,7 @@
<ProjectVersion>20.3</ProjectVersion>
<FrameworkType>FMX</FrameworkType>
<Base>True</Base>
<Config Condition="'$(Config)'==''">Release</Config>
<Config Condition="'$(Config)'==''">Debug</Config>
<Platform Condition="'$(Platform)'==''">Win64</Platform>
<ProjectName Condition="'$(ProjectName)'==''">ASTPlayground</ProjectName>
<TargetedPlatforms>2</TargetedPlatforms>
+16 -8
View File
@@ -33,7 +33,7 @@ object Form1: TForm1
end
object PrettyPrintButton: TButton
Position.X = 24.000000000000000000
Position.Y = 200.000000000000000000
Position.Y = 381.000000000000000000
TabOrder = 3
Text = 'Print'
TextSettings.Trimming = None
@@ -41,7 +41,7 @@ object Form1: TForm1
end
object DebugButton: TButton
Position.X = 24.000000000000000000
Position.Y = 230.000000000000000000
Position.Y = 411.000000000000000000
TabOrder = 4
Text = 'Debug'
TextSettings.Trimming = None
@@ -59,8 +59,8 @@ object Form1: TForm1
OnClick = RecursionButtonClick
end
object ShowScopeBox: TCheckBox
Position.X = 32.000000000000000000
Position.Y = 256.000000000000000000
Position.X = 24.000000000000000000
Position.Y = 441.000000000000000000
TabOrder = 6
Text = 'Scope'
end
@@ -74,7 +74,7 @@ object Form1: TForm1
end
object CrerateTriggerExampleButton: TButton
Position.X = 24.000000000000000000
Position.Y = 320.000000000000000000
Position.Y = 168.000000000000000000
TabOrder = 9
Text = 'TriggerTest'
TextSettings.Trimming = None
@@ -82,7 +82,7 @@ object Form1: TForm1
end
object DoTriggerButton: TButton
Position.X = 24.000000000000000000
Position.Y = 350.000000000000000000
Position.Y = 198.000000000000000000
TabOrder = 10
Text = 'Trigger!'
TextSettings.Trimming = None
@@ -97,7 +97,7 @@ object Form1: TForm1
end
object ClearButton: TButton
Position.X = 24.000000000000000000
Position.Y = 432.000000000000000000
Position.Y = 472.000000000000000000
Size.Width = 80.000000000000000000
Size.Height = 22.000000000000000000
Size.PlatformDefault = False
@@ -115,7 +115,7 @@ object Form1: TForm1
end
object SeriesTestButton: TButton
Position.X = 24.000000000000000000
Position.Y = 152.000000000000000000
Position.Y = 274.000000000000000000
Size.Width = 80.000000000000000000
Size.Height = 22.000000000000000000
Size.PlatformDefault = False
@@ -124,6 +124,14 @@ object Form1: TForm1
TextSettings.Trimming = None
OnClick = SeriesTestButtonClick
end
object OHLCButton: TButton
Position.X = 24.000000000000000000
Position.Y = 304.000000000000000000
TabOrder = 15
Text = 'OHLC'
TextSettings.Trimming = None
OnClick = OHLCButtonClick
end
end
object Panel2: TPanel
Align = Client
+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.
+24 -4
View File
@@ -76,6 +76,7 @@ type
const Title, Details: string;
const InPin, OutPin: String;
IsExec: Boolean;
HasResult: Boolean;
const ChildVisitorProc: TChildVisitorProc
): TAuraNode;
function VisitOperatorNode(
@@ -181,7 +182,8 @@ implementation
uses
System.Math,
System.StrUtils;
System.StrUtils,
Myc.Data.Scalar;
type
// This visitor converts an AST expression subtree into a single string.
@@ -284,7 +286,7 @@ var
begin
sb := TStringBuilder.Create;
try
sb.Append('(');
sb.Append(#$03BB + '(');
if Length(Node.Parameters) > 0 then
begin
for i := 0 to High(Node.Parameters) do
@@ -677,6 +679,7 @@ begin
'',
'',
true,
false,
procedure(const Visitor: IAstVisitor)
var
expression: IExpressionNode;
@@ -715,6 +718,7 @@ function TAstToAuraNodeVisitor.VisitContainerNode(
const Title, Details: string;
const InPin, OutPin: String;
IsExec: Boolean;
HasResult: Boolean;
const ChildVisitorProc: TChildVisitorProc
): TAuraNode;
var
@@ -724,6 +728,7 @@ var
maxRight: Single;
maxBottom: Single;
control: TControl;
childLastResult: TAuraNodeResult;
begin
const pinNodeHeight = cPinSize + cVerticalPadding;
@@ -764,6 +769,9 @@ begin
childVisitor := TAstToAuraNodeVisitor.Create(FWorkspace, containerNode, childStartPos, FConnections, FCurrentExec.ToArray, FMode);
ChildVisitorProc(childVisitor);
// Capture the result from the child visitor.
childLastResult := (childVisitor as TAstToAuraNodeVisitor).FLastResult;
FCurrentExec.Clear;
FCurrentExec.AddRange((childVisitor as TAstToAuraNodeVisitor).FCurrentExec);
@@ -781,7 +789,7 @@ begin
// The width must be at least the title width, and large enough for children.
containerNode.Width := Max(containerNode.Width, maxRight + FSpacing.X);
containerNode.Height := Max(containerNode.Height, maxBottom + FSpacing.Y + IfThen(OutPin <> '', pinNodeHeight, 0));
containerNode.Height := Max(containerNode.Height, maxBottom + FSpacing.Y);
if OutPin <> '' then
begin
@@ -789,8 +797,19 @@ begin
exitNode.Parent := containerNode;
exitNode.Height := pinNodeHeight;
var exitPin := CreateEntry(exitNode);
// Create and connect a data pin if the container returns a value.
if HasResult and Assigned(childLastResult.OutputPin) then
begin
var dataResultPin := CreateInput(exitNode, 'Result');
FConnections.Add(TPinConnection.Create(childLastResult.OutputPin, dataResultPin));
end;
FinalizeNodeLayout(exitNode);
// Enlarge for the exit node
containerNode.Height := Max(containerNode.Height, maxBottom + FSpacing.Y + exitNode.Height);
exitNode.Position.Point := TPointF.Create(containerNode.Width - exitNode.Width, containerNode.Height - exitNode.Height);
if not IsExec then
@@ -1022,11 +1041,12 @@ begin
// Use the helper to create and populate the container node.
lambdaNode :=
VisitContainerNode(
'Lambda',
#$03BB,
paramStr,
'call',
'return',
false,
true,
procedure(const Visitor: IAstVisitor) begin Node.Body.Accept(Visitor); end
);