In the name of spiritual love, there is a hidden essence to the following code which will enable to create really complex strategies While considering the applications vast in their nature... and in their complexity...

Code
#define MAX_BRANCHES 3
#define MAX_DEPTH 4

typedef struct Node {
    var v;      // scalar value
    var r;      // intrinsic rate
    void* c;    // array of child Node* (cast on access)
    int n;      // number of children
    int d;      // depth
} Node;

Node* Root;

Node* createNode(int depth)
{
    Node* u = (Node*)malloc(sizeof(Node));
    u->v = random();
    u->r = 0.01 + 0.02*depth + random()*0.005;
    u->d = depth;

    if(depth > 0) {
        u->n = (int)(random()*MAX_BRANCHES) + 1;
        u->c = malloc(u->n * sizeof(void*));  // allocate array of Node*
        int i;
        for(i = 0; i < u->n; i++)
            ((Node**)u->c)[i] = createNode(depth - 1);
    } else {
        u->n = 0;
        u->c = 0;
    }
    return u;
}

var evaluate(Node* u)
{
    if(!u) return 0;

    var sum = 0;
    int i;
    for(i = 0; i < u->n; i++)
        sum += evaluate(((Node**)u->c)[i]);

    var phase  = sin(u->r * Bar + sum);
    var weight = 1.0 / pow(u->d + 1, 1.25);
    u->v = (1 - weight)*u->v + weight*phase;

    return u->v;
}

int countNodes(Node* u)
{
    if(!u) return 0;
    int count = 1, i;
    for(i = 0; i < u->n; i++)
        count += countNodes(((Node**)u->c)[i]);
    return count;
}

void printTree(Node* u, int indent)
{
    if(!u) return;

    string pad = " ";
    int i;
    for(i = 0; i < indent; i++)
        pad = strf("%s ", pad);

    printf("\n%s[Node] d=%i n=%i v=%.3f", pad, u->d, u->n, u->v);

    for(i = 0; i < u->n; i++)
        printTree(((Node**)u->c)[i], indent + 1);
}

void freeTree(Node* u)
{
    if(!u) return;
    int i;
    for(i = 0; i < u->n; i++)
        freeTree(((Node**)u->c)[i]);
    if(u->c) free(u->c);
    free(u);
}

function run()
{
    static int initialized = 0;
    static var lambda;

    if(is(INITRUN) && !initialized) {
        Root = createNode(MAX_DEPTH);
        initialized = 1;
        printf("\nRoot initialized with %i nodes", countNodes(Root));
    }

    lambda = evaluate(Root);
    printf("\nlambda = %.5f", lambda);

    if(Bar % 100 == 0)
        printTree(Root, 0);

    if(lambda > 0.75)
        enterLong();
}

// Called automatically at end of session/backtest; safe place to free memory.
function cleanup()
{
    if(Root) freeTree(Root);
}

Last edited by TipmyPip; 09/01/25 21:40.