Sample SMA strategy

This commit is contained in:
Michael Schimmel
2025-09-03 19:21:31 +02:00
parent 6b9dcee417
commit 696fb2f9a0
8 changed files with 709 additions and 204 deletions
+6
View File
@@ -132,6 +132,12 @@ object Form1: TForm1
TextSettings.Trimming = None
OnClick = OHLCButtonClick
end
object DebugBox: TCheckBox
Position.X = 24.000000000000000000
Position.Y = 360.000000000000000000
TabOrder = 17
Text = 'Debug'
end
end
object Panel2: TPanel
Align = Client
+86 -141
View File
@@ -60,6 +60,7 @@ type
FlowOnlyBox: TCheckBox;
SeriesTestButton: TButton;
OHLCButton: TButton;
DebugBox: TCheckBox;
procedure ClearButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure CrerateTriggerExampleButtonClick(Sender: TObject);
@@ -78,6 +79,7 @@ type
FLastAst: IExpressionNode;
FGScope: IExecutionScope;
FWorkspace: TAuraWorkspace;
function CreateVisitor(const AScope: IExecutionScope): IAstVisitor;
procedure WorkspaceMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
public
{ Public declarations }
@@ -102,6 +104,18 @@ begin
FWorkspace.Repaint;
end;
function TForm1.CreateVisitor(const AScope: IExecutionScope): IAstVisitor;
begin
// Conditionally create a debug visitor if the checkbox is checked.
if DebugBox.IsChecked then
begin
Memo1.Lines.Add('--- Creating DEBUG visitor ---');
Result := TDebugEvaluatorVisitor.Create(AScope, Memo1.Lines, ShowScopeBox.IsChecked);
end
else
Result := TEvaluatorVisitor.Create(AScope);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FWorkspace := TAuraWorkspace.Create(Panel2);
@@ -133,6 +147,7 @@ begin
Memo1.Lines.Clear;
Memo1.Lines.Add('--- Debug Evaluator Trace ---');
// This button ALWAYS uses the debug visitor, regardless of the checkbox.
visitor := TDebugEvaluatorVisitor.Create(scope, Memo1.Lines, ShowScopeBox.IsChecked, 0);
sw := TStopwatch.StartNew;
@@ -203,38 +218,7 @@ begin
Application.ProcessMessages; // Update UI before blocking
sw.Start;
{
root :=
TAst.Block(
[
TAst.VarDecl(
TAst.Identifier('fib'),
TAst.LambdaExpr(
[TAst.Identifier('n')],
TAst.IfExpr(
TAst.BinaryExpr(TAst.Identifier('n'), boLess, TAst.Constant(TScalar.FromInt64(2))),
TAst.Assign(TAst.Identifier('Result'), TAst.Identifier('n')),
TAst.Assign(
TAst.Identifier('Result'),
TAst.BinaryExpr(
TAst.FunctionCall(
TAst.Identifier('fib'),
[TAst.BinaryExpr(TAst.Identifier('n'), boSubtract, TAst.Constant(TScalar.FromInt64(1)))]
),
boAdd,
TAst.FunctionCall(
TAst.Identifier('fib'),
[TAst.BinaryExpr(TAst.Identifier('n'), boSubtract, TAst.Constant(TScalar.FromInt64(2)))]
)
)
)
)
)
),
TAst.FunctionCall(TAst.Identifier('fib'), [TAst.Constant(TScalar.FromInt64(30))])
]
);
}
root :=
TAst.Block(
[
@@ -269,7 +253,7 @@ begin
FLastAst := root;
scope := TExecutionScope.Create(nil);
visitor := TEvaluatorVisitor.Create(scope);
visitor := CreateVisitor(scope);
result := root.Accept(visitor);
sw.Stop;
@@ -325,31 +309,6 @@ begin
root :=
TAst.Block(
[
TAst.FunctionCall(
TAst.LambdaExpr(
[TAst.Identifier('n')],
TAst.Block(
[
TAst.IfExpr(
TAst.BinaryExpr(TAst.Identifier('n'), boLess, TAst.Constant(TScalar.FromInt64(2))),
TAst.Assign(TAst.Identifier('Result'), TAst.Constant(TScalar.FromInt64(1))),
TAst.Assign(
TAst.Identifier('Result'),
TAst.BinaryExpr(
TAst.Identifier('n'),
boMultiply,
TAst.FunctionCall(
TAst.Identifier('Self'),
[TAst.BinaryExpr(TAst.Identifier('n'), boSubtract, TAst.Constant(TScalar.FromInt64(1)))]
)
)
)
)
]
)
),
[TAst.Constant(TScalar.FromInt64(20))]
),
TAst.VarDecl(
TAst.Identifier('factorial'),
TAst.LambdaExpr(
@@ -363,7 +322,7 @@ begin
TAst.Identifier('n'),
boMultiply,
TAst.FunctionCall(
TAst.Identifier('Self'),
TAst.Identifier('factorial'),
[TAst.BinaryExpr(TAst.Identifier('n'), boSubtract, TAst.Constant(TScalar.FromInt64(1)))]
)
)
@@ -379,7 +338,7 @@ begin
FLastAst := root;
scope := TExecutionScope.Create(nil);
visitor := TEvaluatorVisitor.Create(scope);
visitor := CreateVisitor(scope);
result := root.Accept(visitor);
sw.Stop;
@@ -437,10 +396,6 @@ begin
// --- 2. Act (in Script) ---
Memo1.Lines.Add('2. Executing script...');
// This script now tests member access and indexing the resulting member series.
// let closeColumn = ohlcvSeries.Close;
// let secondClose = closeColumn[1];
// secondClose
ast :=
TAst.LambdaExpr(
[],
@@ -459,7 +414,7 @@ begin
);
FLastAst := ast;
visitor := TEvaluatorVisitor.Create(FGScope);
visitor := CreateVisitor(FGScope);
resultValue := TAst.FunctionCall(ast, []).Accept(visitor);
Memo1.Lines.Add(' - Script finished.');
@@ -530,7 +485,7 @@ begin
FLastAst := main;
scope := TExecutionScope.Create(FGScope);
visitor := TEvaluatorVisitor.Create(scope);
visitor := CreateVisitor(scope);
result := TAst.FunctionCall(main, []).Accept(visitor);
sw.Stop;
@@ -582,7 +537,7 @@ begin
scope := TExecutionScope.Create(FGScope);
visitor := TEvaluatorVisitor.Create(scope);
visitor := CreateVisitor(scope);
result := root.Accept(visitor);
sw.Stop;
@@ -620,15 +575,9 @@ begin
]
);
// lambdaAst :=
// TAst.LambdaExpr(
// [TAst.Identifier('summand')],
// TAst.Assign(TAst.Identifier('X'), TAst.BinaryExpr(TAst.Identifier('X'), boAdd, TAst.Identifier('summand')))
// );
// Evaluate the lambda to create a closure and store it in the scope.
// The closure captures the scope where 'X' is defined.
visitor := TEvaluatorVisitor.Create(FGScope);
visitor := CreateVisitor(FGScope);
blk.Accept(visitor);
// FLastAst is not used for this parameterized example.
@@ -652,7 +601,7 @@ begin
callAst := TAst.FunctionCall(TAst.Identifier('tickHandler'), [TAst.Constant(TScalar.FromInt64(1))]);
// Execute the call AST.
visitor := TEvaluatorVisitor.Create(FGScope);
visitor := CreateVisitor(FGScope);
callAst.Accept(visitor);
FLastAst := callAst;
@@ -684,7 +633,7 @@ begin
FLastAst := callAst;
// Execute the call AST.
visitor := TEvaluatorVisitor.Create(FGScope);
visitor := CreateVisitor(FGScope);
callAst.Accept(visitor);
// Get the updated value of 'X' from the scope and display it.
@@ -715,8 +664,8 @@ end;
procedure TForm1.OHLCButtonClick(Sender: TObject);
const
numRecs = 1000;
lookback = 100;
numRecs = 100;
lookback = 50;
smaSlowLength = 20;
smaFastLength = 5;
var
@@ -734,7 +683,7 @@ var
begin
// 1. Setup
Memo1.Lines.Clear;
Memo1.Lines.Add(Format('--- Simulating SMA Crossover Strategy for %d ticks ---', [numRecs]));
Memo1.Lines.Add(Format('--- Simulating O(1) SMA Crossover Strategy for %d ticks ---', [numRecs]));
FGScope.Clear;
RegisterNativeFunctions(FGScope);
sw := TStopwatch.StartNew;
@@ -742,61 +691,66 @@ begin
recordDef := TRttiAstHelper.JsonToRecordDefinition(TRttiAstHelper.RecordDefinitionToJson(TypeInfo(TOHLCV)));
series := TScalarRecordSeries.Create(recordDef);
// 2. Create the setup AST. This block defines all necessary functions.
// 2. Create the setup AST with O(1) SMA implementation
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.Identifier('CreateSMA_O1'),
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')
)
TAst.Block(
[
TAst.VarDecl(TAst.Identifier('sum'), TAst.Constant(TScalar.FromDouble(0.0))),
TAst.VarDecl(TAst.Identifier('values'), TAst.CreateSeries('double')),
TAst.LambdaExpr(
[TAst.Identifier('val')],
TAst.Block(
[
TAst.IfExpr(
TAst.BinaryExpr(
TAst.SeriesLength(TAst.Identifier('values')),
boGreaterOrEqual,
TAst.Identifier('len')
),
TAst.Assign(
TAst.Identifier('sum'),
TAst.BinaryExpr(
TAst.Identifier('sum'),
boSubtract,
TAst.Indexer(
TAst.Identifier('values'),
TAst.BinaryExpr(
TAst.Identifier('len'),
boSubtract,
TAst.Constant(TScalar.FromInt64(1))
)
)
)
),
nil
),
TAst.Assign(
TAst.Identifier('sum'),
TAst.BinaryExpr(TAst.Identifier('sum'), boAdd, TAst.Identifier('val'))
),
TAst.AddSeriesItem(TAst.Identifier('values'), TAst.Identifier('val'), TAst.Identifier('len')),
TAst.BinaryExpr(TAst.Identifier('sum'), boDivide, TAst.SeriesLength(TAst.Identifier('values')))
]
)
)
]
)
)
),
// let smaFast = CreateSMA(5);
TAst.VarDecl(
TAst.Identifier('smaFast'),
TAst.FunctionCall(TAst.Identifier('CreateSMA'), [TAst.Constant(TScalar.FromInt64(smaFastLength))])
TAst.FunctionCall(TAst.Identifier('CreateSMA_O1'), [TAst.Constant(TScalar.FromInt64(smaFastLength))])
),
// let smaSlow = CreateSMA(20);
TAst.VarDecl(
TAst.Identifier('smaSlow'),
TAst.FunctionCall(TAst.Identifier('CreateSMA'), [TAst.Constant(TScalar.FromInt64(smaSlowLength))])
TAst.FunctionCall(TAst.Identifier('CreateSMA_O1'), [TAst.Constant(TScalar.FromInt64(smaSlowLength))])
),
// Define the main strategy function
TAst.VarDecl(
TAst.Identifier('maCrossStrategy'),
TAst.LambdaExpr(
@@ -804,22 +758,25 @@ begin
TAst.Block(
[
TAst.VarDecl(
TAst.Identifier('close'),
TAst.MemberAccess(TAst.Identifier('ohlcv'), TAst.Identifier('Close'))
TAst.Identifier('currentClose'),
TAst.MemberAccess(
TAst.Indexer(TAst.Identifier('ohlcv'), TAst.Constant(TScalar.FromInt64(0))),
TAst.Identifier('Close')
)
),
TAst.VarDecl(
TAst.Identifier('valSmaFast'),
TAst.FunctionCall(TAst.Identifier('smaFast'), [TAst.Identifier('close')])
TAst.FunctionCall(TAst.Identifier('smaFast'), [TAst.Identifier('currentClose')])
),
TAst.VarDecl(
TAst.Identifier('valSmaSlow'),
TAst.FunctionCall(TAst.Identifier('smaSlow'), [TAst.Identifier('close')])
TAst.FunctionCall(TAst.Identifier('smaSlow'), [TAst.Identifier('currentClose')])
),
TAst.TernaryExpr(
TAst.BinaryExpr(TAst.Identifier('valSmaFast'), boGreater, TAst.Identifier('valSmaSlow')),
TAst.Constant(TScalar.FromInt64(1)), // Buy signal
TAst.Constant(TScalar.FromInt64(1)),
TAst.Constant(TScalar.FromInt64(-1))
) // Sell signal
)
]
)
)
@@ -827,13 +784,9 @@ begin
]
);
FLastAst := setupAst; // Store for visualization
visitor := TEvaluatorVisitor.Create(FGScope);
// Execute the setup script once to define all functions in the scope.
FLastAst := setupAst;
visitor := CreateVisitor(FGScope);
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
@@ -846,7 +799,6 @@ begin
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;
@@ -870,20 +822,13 @@ begin
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;
Memo1.Lines.Add(Format('Tick %d/%d: Close = %.2f, Signal = %s', [i, numRecs, ohlcvRec.Close, resultValue.ToString]));
Application.ProcessMessages;
end;
end;
+135 -3
View File
@@ -130,6 +130,9 @@ type
function VisitAssignment(const Node: IAssignmentNode): TAstValue;
function VisitIndexer(const Node: IIndexerNode): TAstValue;
function VisitMemberAccess(const Node: IMemberAccessNode): TAstValue;
function VisitCreateSeries(const Node: ICreateSeriesNode): TAstValue;
function VisitAddSeriesItem(const Node: IAddSeriesItemNode): TAstValue;
function VisitSeriesLength(const Node: ISeriesLengthNode): TAstValue;
end;
TAuraWorkspace = class(TStyledControl)
@@ -204,6 +207,9 @@ type
function VisitAssignment(const Node: IAssignmentNode): TAstValue;
function VisitIndexer(const Node: IIndexerNode): TAstValue;
function VisitMemberAccess(const Node: IMemberAccessNode): TAstValue;
function VisitCreateSeries(const Node: ICreateSeriesNode): TAstValue;
function VisitAddSeriesItem(const Node: IAddSeriesItemNode): TAstValue;
function VisitSeriesLength(const Node: ISeriesLengthNode): TAstValue;
end;
constructor TAstToTextVisitor.Create;
@@ -213,6 +219,18 @@ end;
{ TAstToTextVisitor }
function TAstToTextVisitor.VisitAddSeriesItem(const Node: IAddSeriesItemNode): TAstValue;
var
seriesStr, valueStr, lookbackStr: string;
begin
seriesStr := Node.Series.Accept(Self).AsText;
valueStr := Node.Value.Accept(Self).AsText;
lookbackStr := '';
if Assigned(Node.Lookback) then
lookbackStr := ', ' + Node.Lookback.Accept(Self).AsText;
Result := TAstValue.FromText(Format('%s.add(%s%s)', [seriesStr, valueStr, lookbackStr]));
end;
function TAstToTextVisitor.VisitAssignment(const Node: IAssignmentNode): TAstValue;
begin
Result := TAstValue.FromText(Node.Identifier.Name + ' := ' + Node.Value.Accept(Self).AsText);
@@ -235,6 +253,11 @@ begin
Result := TAstValue.FromText(Node.Value.ToString);
end;
function TAstToTextVisitor.VisitCreateSeries(const Node: ICreateSeriesNode): TAstValue;
begin
Result := TAstValue.FromText('new series(' + Node.Definition + ')');
end;
function TAstToTextVisitor.VisitFunctionCall(const Node: IFunctionCallNode): TAstValue;
var
i: Integer;
@@ -312,6 +335,15 @@ begin
Result := TAstValue.FromText(Format('%s.%s', [baseStr, Node.Member.Name]));
end;
function TAstToTextVisitor.VisitSeriesLength(const Node: ISeriesLengthNode): TAstValue;
var
seriesStr: string;
begin
// Get the string representation of the series identifier by visiting the node.
seriesStr := Node.Series.Accept(Self).AsText;
Result := TAstValue.FromText(Format('length(%s)', [seriesStr]));
end;
function TAstToTextVisitor.VisitTernaryExpression(const Node: ITernaryExpressionNode): TAstValue;
begin
var condStr := Node.Condition.Accept(Self).AsText;
@@ -573,6 +605,62 @@ begin
Result := Pos('{', Text) = 0;
end;
function TAstToAuraNodeVisitor.VisitAddSeriesItem(const Node: IAddSeriesItemNode): TAstValue;
var
details: string;
inputs: TArray<IExpressionNode>;
begin
if (FMode = vmControlFlow) and TryGetDescr(Node, details) then
begin
var addNode := CreateNodeControl('Add to Series', details);
CreateEntry(addNode);
CreateExit(addNode, '');
FinalizeNodeLayout(addNode);
end
else
begin
if Assigned(Node.Lookback) then
inputs := [Node.Series, Node.Value, Node.Lookback]
else
inputs := [Node.Series, Node.Value];
VisitOperatorNode(
inputs,
function(const InputResults: TAuraNodeResultList): TAuraNodeResult
var
addNode: TAuraNode;
seriesPin, valuePin, lookbackPin: TControl;
begin
addNode := BuildNodeControl('Add to Series', '');
CreateEntry(addNode);
seriesPin := CreateInput(addNode, 'Series');
valuePin := CreateInput(addNode, 'Value');
if Assigned(InputResults[0].OutputPin) then
FConnections.Add(TPinConnection.Create(InputResults[0].OutputPin, seriesPin));
if Assigned(InputResults[1].OutputPin) then
FConnections.Add(TPinConnection.Create(InputResults[1].OutputPin, valuePin));
if InputResults.Count > 2 then
begin
lookbackPin := CreateInput(addNode, 'Lookback');
if Assigned(InputResults[2].OutputPin) then
FConnections.Add(TPinConnection.Create(InputResults[2].OutputPin, lookbackPin));
end;
CreateExit(addNode, '');
FinalizeNodeLayout(addNode);
Result.LayoutNode := addNode;
Result.OutputPin := nil; // No data output
end,
vaTop
);
end;
Result := TAstValue.Void;
end;
function TAstToAuraNodeVisitor.VisitAssignment(const Node: IAssignmentNode): TAstValue;
begin
var details: String;
@@ -824,6 +912,18 @@ begin
FinalizeNodeLayout(containerNode);
end;
function TAstToAuraNodeVisitor.VisitCreateSeries(const Node: ICreateSeriesNode): TAstValue;
var
seriesNode: TAuraNode;
begin
// This node creates a new series. It has no inputs, only a data output.
// The definition is a string literal, so it's part of the node's title.
seriesNode := CreateNodeControl('Create Series', Node.Definition);
FLastResult.OutputPin := CreateOutput(seriesNode);
FinalizeNodeLayout(seriesNode);
Result := TAstValue.Void;
end;
function TAstToAuraNodeVisitor.VisitFunctionCall(const Node: IFunctionCallNode): TAstValue;
var
inputExpressions: TArray<IExpressionNode>;
@@ -951,16 +1051,16 @@ begin
// Else branch (if it exists)
elseEndY := thenEndY;
FCurrentExec.Clear;
CreateExit(ifNode, 'Else');
if Assigned(Node.ElseBranch) then
begin
FCurrentExec.Clear;
CreateExit(ifNode, 'Else');
FCurrentPos.X := branchStartX;
FCurrentPos.Y := thenEndY;
Node.ElseBranch.Accept(Self);
elseEndY := FCurrentPos.Y;
execPathes.AddRange(FCurrentExec);
end;
execPathes.AddRange(FCurrentExec);
// Finalize layout now that all pins are added.
FinalizeNodeLayout(ifNode);
@@ -1157,6 +1257,38 @@ begin
end;
end;
function TAstToAuraNodeVisitor.VisitSeriesLength(const Node: ISeriesLengthNode): TAstValue;
begin
// Use the standard helper for operator-style nodes.
VisitOperatorNode(
[Node.Series], // The single input for this operator is the series identifier.
function(const InputResults: TAuraNodeResultList): TAuraNodeResult
var
lengthNode: TAuraNode;
seriesPin, outPin: TControl;
begin
// Create the visual node for the 'length' operation.
lengthNode := BuildNodeControl('Series Length', '');
// Create an input pin for the series and an output pin for the result.
seriesPin := CreateInput(lengthNode, 'Series');
outPin := CreateOutput(lengthNode);
// Connect the output of the visited series identifier to our input pin.
if Assigned(InputResults[0].OutputPin) then
FConnections.Add(TPinConnection.Create(InputResults[0].OutputPin, seriesPin));
// Finalize the node's layout to correctly position the pins.
FinalizeNodeLayout(lengthNode);
// The result of this visitation is the new node and its output pin.
Result.LayoutNode := lengthNode;
Result.OutputPin := outPin;
end
);
Result := TAstValue.Void;
end;
function TAstToAuraNodeVisitor.VisitTernaryExpression(const Node: ITernaryExpressionNode): TAstValue;
begin
var exprStr: String;