Gamestudio Links
Zorro Links
Newest Posts
IBKR datasave problem
by NewbieZorro. 06/11/25 15:11
Marking Exit trades
by jcl. 06/11/25 14:02
SGT_FW
by Aku_Aku. 06/02/25 17:54
The Perfect Adventure Game
by tian. 05/27/25 04:32
ADX values
by Yogpot. 05/25/25 15:11
Transfer of Lots between Algos?
by Jack_Zodiac. 05/25/25 09:30
AUM Magazine
Latest Screens
Stug 3 Stormartillery
Iljuschin 2
Galactic Strike X
Zeal-X2
Who's Online Now
0 registered members (), 357 guests, and 3 spiders.
Key: Admin, Global Mod, Mod
Newest Members
WardyJoubertIII, NewbieZorro, Squarei, tian, Yogpot
19139 Registered Users
Previous Thread
Next Thread
Print Thread
Rate Thread
Page 9 of 9 1 2 3 4 5 6 7 8 9
Tale of the Five Guardians [Re: TipmyPip] #488607
02/14/25 06:58
02/14/25 06:58
Joined: Sep 2017
Posts: 147
T
TipmyPip Offline OP
Member
TipmyPip  Offline OP
Member
T

Joined: Sep 2017
Posts: 147
The Tale of the Five Guardians and the Perceptron Oracle

In the bustling metropolis of Zorropolis, where digital assets danced in the ever-changing winds of the market, a young trader named Ava sought the secret to consistent fortune. Many had tried and failed, lost in the noise of random market movements. But Ava was different. She believed in logic, precision, and—most importantly—machine learning.

Ava had heard whispers of the ancient Perceptron Oracle, a mystical force known for its unparalleled predictions. But to summon the Oracle, one needed to gather the wisdom of the Five Guardians of the Market. Each guardian held a vital piece of the market puzzle, and together, they could unlock the Oracle’s true potential.

The Guardians:

The Saucer Sage – A sharp-eyed seer who noticed when trends gently shifted gears, like a saucer smoothly turning.
The Zero Line Nomad – A wanderer who lived on the line between profit and loss, signaling when it was time to cross to the winning side.
The Valley Whisperer – A quiet guide who knew when the market had sunk to its lowest point, whispering, “Now is the time to rise.”
The Divergence Shaman – An enigmatic figure who could spot when prices and momentum drifted apart, revealing hidden opportunities.
The Trend Warden – A steadfast guardian who ensured that Ava only traded when the trend and momentum agreed, warning against false hopes.
Ava ventured through the digital plains, seeking each guardian and gathering their signals—like ancient runes carved into her MLsignals tablet. Each guardian offered a signal, but Ava knew that not all signals were created equal. She had to decide which wisdom mattered most.

But how?

She had heard tales of failed traders who tried to guess these weights manually, only to be consumed by the market’s volatility.

Ava needed the Oracle.

At the heart of Zorropolis, she placed the signals into the hands of the Perceptron Oracle, whispering, “Guide me.”

The Oracle, an ancient machine learning entity, processed the signals, calculating the perfect balance—assigning dynamic weights to each guardian's wisdom. With each passing trade, the Oracle learned, adapting to the ever-shifting market winds.

And so, Ava’s strategy was born:

Signals from the Five Guardians combined into a single weighted force.
The Perceptron Oracle dynamically adjusted these weights, ensuring Ava’s trades were always aligned with the market’s pulse.
Ava’s digital ship sailed smoothly through the market’s waves, entering trades when the Oracle foresaw profit, and retreating when danger loomed.
In the end, Ava didn’t just find fortune—she found balance, with a strategy as elegant as a puzzle perfectly solved.
(please keep in mind, that the sharing of the code is to inspire your mind, and find ideas to build probabilistic state machines which will turn your dreams into reality, But be aware, that the code will not produce for you millions. :-)

Code
var MLsignals[7];  // Additional signal for threshold learning

#define condition1 MLsignals[0]
#define condition2 MLsignals[1]
#define condition3 MLsignals[2]
#define condition4 MLsignals[3]
#define condition5 MLsignals[4]
#define threshold MLsignals[5]  // Dynamic threshold
#define finalOutput MLsignals[6]  // Final Perceptron output

var MLp[5];  // Individual Perceptron outputs

function run() 
{
    set(PARAMETERS|RULES);  // Enable parameter optimization, training, and rule generation

    StartDate = 20220101;          // Start date for training
    EndDate = 20250101;            // End date for training
    NumWFOCycles = 10;             // Walk-Forward Optimization cycles
    BarPeriod = 5;                // Bar timeframe in minutes
    LookBack = 200;                // Lookback period for indicators
    Capital = 1000;                // Initial capital

    vars MedianPrice = series((priceHigh() + priceLow()) / 2);
    vars AO = series(SMA(MedianPrice, 5) - SMA(MedianPrice, 34));  // Awesome Oscillator
    vars RSI = series(RSI(series(priceClose()), 14));              // RSI Indicator

    while (asset(loop(
        "EUR/USD", "GBP/USD", "USD/JPY", "USD/CHF", "USD/CAD", "AUD/USD", "NZD/USD",
        "EUR/GBP", "EUR/JPY", "EUR/CHF", "GBP/JPY", "GBP/CHF", "AUD/JPY", "AUD/CHF", "GBP/CHF", "NZD/CAD",
        "NZD/JPY", "NZD/CHF", "CAD/JPY", "CAD/CHF", "CHF/JPY", "EUR/AUD", "EUR/NZD",
        "EUR/CAD", "GBP/AUD", "GBP/NZD", "GBP/CAD", "AUD/NZD")))
    {
        // Define machine learning input conditions
        condition1 = ifelse(AO[2] < AO[1] && AO[1] < AO[0], 1, 0);
        condition2 = ifelse(crossOver(AO, 0), 1, 0);
        condition3 = ifelse(valley(AO), 1, 0);
        condition4 = ifelse(priceClose(1) > priceClose(2) && AO[1] < AO[2], 1, 0);
        condition5 = ifelse(AO[0] > 0 && RSI[0] > 50, 1, 0);

        // Train individual Perceptrons for each condition
        MLp[0] = adviseLong(PERCEPTRON+RETURNS, 0, &condition1, 1);
        MLp[1] = adviseLong(PERCEPTRON+RETURNS, 0, &condition2, 1);
        MLp[2] = adviseLong(PERCEPTRON+RETURNS, 0, &condition3, 1);
        MLp[3] = adviseLong(PERCEPTRON+RETURNS, 0, &condition4, 1);
        MLp[4] = adviseLong(PERCEPTRON+RETURNS, 0, &condition5, 1);

        // Train Perceptron to find the optimal threshold dynamically
        threshold = adviseLong(PERCEPTRON+RETURNS, 0, MLp, 5);  

        // Final Perceptron for the trading decision
        finalOutput = adviseLong(PERCEPTRON+RETURNS, 0, MLp, 5);

        // Trading logic with dynamically learned threshold
        if (finalOutput > threshold) {
            enterLong();
        } else if (finalOutput < -threshold) {
            enterShort();
        }
    }

    // Plot indicators and results
    plot("AO", AO, NEW, BLUE);
    plot("RSI", RSI, NEW, RED);
    plot("Threshold", threshold, NEW, GREEN);
    plot("FinalOutput", finalOutput, NEW, BLACK);
}

Last edited by TipmyPip; 02/20/25 23:45.
Multi-File Converting csv to .t6 [Re: TipmyPip] #488610
02/14/25 19:42
02/14/25 19:42
Joined: Sep 2017
Posts: 147
T
TipmyPip Offline OP
Member
TipmyPip  Offline OP
Member
T

Joined: Sep 2017
Posts: 147
Converting a list of files with high volume, to *.t6 files:

Code
#define NUM_PAIRS 28    // Number of currency pairs
#define NUM_TIMEFRAMES 2  // Number of timeframes to process

// Arrays to store the currency pairs and timeframes
string Pairs[NUM_PAIRS];
string Timeframes[NUM_TIMEFRAMES];

/*
 * Format string for parsing CSV data.
 * The '+' indicates the CSV file has a header line to skip.
 * %Y - Year (4 digits)
 * %m - Month (2 digits)
 * %d - Day (2 digits)
 * %H - Hour (2 digits, 24-hour format)
 * %M - Minute (2 digits)
 * %f3 - Open price (floating point with 3 decimals)
 * %f1 - High price (floating point with 1 decimal)
 * %f2 - Low price (floating point with 2 decimals)
 * %f4 - Close price (floating point with 4 decimals)
 * %f6 - Volume (floating point with 6 decimals)
 *
 * This must match the structure of your CSV files.
 */
string Format = "+%Y.%m.%d,%H:%M,%f3,%f1,%f2,%f4,%f6";

// Function to initialize currency pairs and timeframes
// Modify this to include/remove pairs or adjust timeframes as needed.
function initializePairsAndTimeframes() {
	// Currency pairs
	Pairs[0] = "EURUSD";
	Pairs[1] = "GBPUSD";
	Pairs[2] = "USDJPY";
	Pairs[3] = "USDCHF";
	Pairs[4] = "USDCAD";
	Pairs[5] = "AUDUSD";
	Pairs[6] = "NZDUSD";
	Pairs[7] = "EURGBP";
	Pairs[8] = "EURJPY";
	Pairs[9] = "EURCHF";
	Pairs[10] = "GBPJPY";
	Pairs[11] = "GBPCHF";
	Pairs[12] = "AUDJPY";
	Pairs[13] = "AUDCHF";
	Pairs[14] = "NZDCAD";
	Pairs[15] = "NZDJPY";
	Pairs[16] = "NZDCHF";
	Pairs[17] = "CADJPY";
	Pairs[18] = "CADCHF";
	Pairs[19] = "CHFJPY";
	Pairs[20] = "EURAUD";
	Pairs[21] = "EURNZD";
	Pairs[22] = "EURCAD";
	Pairs[23] = "GBPAUD";
	Pairs[24] = "GBPNZD";
	Pairs[25] = "GBPCAD";
	Pairs[26] = "AUDNZD";
	Pairs[27] = 0;  // End marker

	// Timeframes in minutes (e.g., 60 = 1 hour, 240 = 4 hours)
	Timeframes[0] = "60";
	Timeframes[1] = "240";
}

/*
 * Function to convert a CSV file to a .t6 file.
 * This version splits the CSV data by year and saves each year as a separate .t6 file.
 *
 * Parameters:
 * InName - The path and name of the input CSV file.
 * Pair - The currency pair string to include in the output filename.
 *
 * Outputs:
 * Files are saved as {CurrencyPair}_{Year}.t6, e.g., EURAUD_2025.t6
 */
function ConvertCSV(string InName, string Pair) {
	int Records = dataParse(1, Format, InName);  // Parse the CSV with the defined format
	printf("\n%d lines read from %s", Records, InName);  // Print the number of records read

	if(Records) {
		int i, Start = 0, Year, LastYear = 0;
		for(i = 0; i < Records; i++) {
			Year = ymd(dataVar(1, i, 0)) / 10000;  // Extract the year from the date
			if(!LastYear) LastYear = Year;  // Set the first encountered year

			// Handle the last record
			if(i == Records - 1) { 
				LastYear = Year; 
				Year = 0; 
				i++;
			}

			// When the year changes, save the data segment to a new .t6 file
			if(Year != LastYear) { 
				// Construct the output file name as {Pair}_{Year}.t6
				string OutName = strf("C:\\Users\\**username**\\Zorro\\History\\%s_%4i.t6", Pair, LastYear);
				printf("\nSaving file: %s", OutName);        
				dataSave(1, OutName, Start, i - Start);  // Save the data segment to .t6
				Start = i;  // Update the start index for the next segment
				LastYear = Year;  // Update the current year
			}
		}
	}
}

/*
 * Main function:
 * Loops through all specified currency pairs and timeframes,
 * checks for CSV files in the specified directory, and converts them to .t6 files.
 */
function main() {
	initializePairsAndTimeframes();  // Initialize pairs and timeframes
	int p, t;  // Loop counters for pairs and timeframes

	// Loop through each currency pair
	for(p = 0; Pairs[p]; p++) {
		// Loop through each timeframe
		for(t = 0; t < NUM_TIMEFRAMES; t++) {
			// Construct the CSV file path dynamically
			// Path: C:\Users\**username**\Zorro\History\{CurrencyPair}{Timeframe}.csv
			string FileName = strf("C:\\Users\\**user//name**\\Zorro\\History\\%s%s.csv", Pairs[p], Timeframes[t]);
			printf("\nChecking file: %s", FileName);  // Log the file being checked

			if(file_length(FileName)) {  // Check if the file exists
				printf("\nConverting %s...", FileName);  // Log the conversion process
				ConvertCSV(FileName, Pairs[p]);  // Call the conversion function with the pair name
			} else {
				printf("\nFile not found: %s", FileName);  // Log missing files
			}
		}
	}
	quit("Conversion done!");  // Exit the script when all files are processed
}

Last edited by TipmyPip; 02/14/25 21:05.
Re: Tale of the Five Guardians [Re: TipmyPip] #488616
02/19/25 01:25
02/19/25 01:25
Joined: Apr 2020
Posts: 10
Germany
M
M_D Offline
Newbie
M_D  Offline
Newbie
M

Joined: Apr 2020
Posts: 10
Germany
100% Kudos to this one ... enjoyed reading laugh
Awaiting more tales from Ava ...
... maybe next one will be in deepest darkness in DecisionTree Forest outside Zorropolis.
I heard rumours that The Trend Warden und The Valley Whisperer meet another Guardian ... not sure, his name sounded like The Time Bender.
Rumours say The Time Bender enables The Trend Warden and The Valley Whisperer to jump instantly through Timeframes, allowing them to monitor dimensionally trends and valleys ...

The Lost Computation of Zorropolis [Re: TipmyPip] #488617
02/19/25 03:24
02/19/25 03:24
Joined: Sep 2017
Posts: 147
T
TipmyPip Offline OP
Member
TipmyPip  Offline OP
Member
T

Joined: Sep 2017
Posts: 147
The Oracle’s Challenge: A Computational Puzzle
The Lost Computation of Zorropolis
The Perceptron Oracle, once the most advanced computational entity in Zorropolis, has stopped functioning. No one knows why.

Ava, the last known architect of its intelligence, has discovered fragments of a lost equation, scattered across the Oracle’s memory.

She has deduced that the Oracle’s intelligence was not a single function, but rather a system of interdependent computations, built upon:

✅ A state-driven structure, where information propagates through transitions.
✅ A multi-dimensional decision process, where actions affect future computations.
✅ A set of parallel functions, operating independently yet interacting dynamically.
✅ An evolving mathematical model, dependent on time and hidden governing laws.

The Oracle has given no output, because it cannot complete its missing computation.

Your mission is to restore the lost computation—to reconstruct the system so that it can once again process information and resolve to a stable final result.

🧩 The Mathematical Challenge
Your Lite-C program must correctly implement five interconnected computational components:

1️⃣ A Discrete State Evolution Model
The Oracle does not compute a single value. It moves through a structured state space, governed by a function:

𝑆𝑡+1=𝐹(𝑆𝑡,𝐴𝑡,𝑃𝑡)

Where:

𝑆𝑡 represents the state at time 𝑡.
𝐴𝑡 is an unknown action function that must be determined.
𝑃𝑡 is a transition probability function, dynamically computed.
𝐹 is the state evolution function, currently missing.

Your code must:
🔹 Define the possible states 𝑆.
🔹 Determine the transition conditions 𝑃𝑡.
🔹 Implement the missing function 𝐹 so that the Oracle moves correctly between states.

If 𝐹 is incorrect, the system will never stabilize.

2️⃣ An Action Selection Function At every iteration, the system must choose an action that affects its transition.

This action is determined by a hidden function:

𝐴𝑡=arg⁡max⁡ 𝑎∈𝐴𝑅(𝑎,𝑆𝑡)

Where:

𝐴 is the set of possible actions.
𝑅(𝑎,𝑆𝑡) is the reward function, currently unknown.
Your code must:
🔹 Compute 𝑅(𝑎,𝑆𝑡) dynamically—it is not predefined.
🔹 Ensure that 𝐴𝑡 is selected optimally at each step.
🔹 Allow the system to learn from previous decisions—it must improve over time.

3️⃣ A System of Parallel Computations The Oracle’s intelligence was once distributed across multiple computational streams running in parallel:

𝑂𝑖=𝐺𝑖(𝑋𝑖,𝑊𝑖)

Where:

𝑂𝑖 is the output of computation 𝑖.
𝐺𝑖 is an unknown transformation function that must be derived.
𝑋𝑖 represents incoming signals.
𝑊𝑖 represents a set of dynamically adjusted weights.

Your code must:
🔹 Implement at least five separate computational functions.
🔹 Ensure their outputs interact to influence the final state.
🔹 Design a system where 𝑊𝑖 adapts dynamically rather than remaining static.

If the parallel computations do not align correctly, the final result will never emerge.

4️⃣ A Continuous-Time Evolution Equation
The Oracle’s memory reveals traces of a missing differential equation, governing its internal transformations:

𝑑𝑃/𝑑𝑡=𝑘𝑃(1−𝑃)

Where:

𝑃 is a function representing an evolving parameter in the system.
𝑘 is a hidden variable affecting system growth and decay.
𝑡 represents the progression of the system over time.

Your code must:
🔹 Reconstruct the missing function 𝑃.
🔹 Determine the role of 𝑘 dynamically—it cannot be a static value.
🔹 Ensure that 𝑃 follows a logical trajectory toward a stable solution.

5️⃣ A Convergence Condition
The Oracle will only reactivate when its computations resolve to a finite stable value.

The system must find its final state, defined as:

lim 𝑂𝑡 = 𝐶
𝑡→∞

Where 𝐶 is an unknown numerical sequence that the Oracle is unable to compute without the missing framework.

If implemented correctly, your system will:
✅ Allow all computations to interact and evolve dynamically.
✅ Ensure the system transitions between states correctly.
✅ Solve the differential function guiding evolution.
✅ Reach a stable final state rather than looping indefinitely.

If implemented incorrectly, the system will:
❌ Loop endlessly without reaching a stable value.
❌ Terminate prematurely without solving the missing equation.
❌ Fail to compute the final output.

Your program must not directly assign a final value. The final output must emerge as a result of correct computation.

🚀 The Rules
1️⃣ No Hardcoded Solutions – The system must compute the final result, not assign it manually.
2️⃣ No Infinite Loops – The program must converge naturally, or the Oracle will remain broken.
3️⃣ No Fixed Outputs – The answer must emerge dynamically through computation.

🎯 Your Task
Reconstruct the missing computational framework so that the Oracle can once again complete its final computation.

The final output will appear only when:
✅ The system’s states evolve correctly.
✅ The decision-making process selects actions optimally.
✅ The parallel computations interact properly.
✅ The differential equation is solved dynamically.
✅ The system naturally converges to a final result.

Until then, the Oracle will remain silent.

The only way to solve this challenge is to build the correct system.

Are you ready?

🔥 Begin. 🔥

⏳ Time to Code
Write your Lite-C solution and restore the Oracle’s missing logic.

But remember:

The answer will not reveal itself through explanation.
The answer will only emerge through computation.

Good luck, coder. [video:youtube]https://youtu.be/Ea5b9DfeuqY[/video]

You are the Oracle’s last hope.

🔥 BEGIN. 🔥

Attached Files
Zorro01453.zip (21 downloads)
Last edited by TipmyPip; 02/19/25 03:41.
Graph-Enhanced Directional Trading (GEDT) [Re: TipmyPip] #488619
02/19/25 22:48
02/19/25 22:48
Joined: Sep 2017
Posts: 147
T
TipmyPip Offline OP
Member
TipmyPip  Offline OP
Member
T

Joined: Sep 2017
Posts: 147
Graph-Enhanced Directional Trading (GEDT) Strategy

In financial markets, traders seek to identify trends and directional strength to optimize entry and exit points. Traditional technical indicators such as ADX (Average Directional Index) and DI+/DI- (Directional Indicators) measure trend strength but often fail to capture hidden relationships between assets or sectors.

To address this, we define a financial market as a graph
𝐺=(𝑉,𝐸), where:

Each node 𝑖∈𝑉 represents a financial asset.
An edge (𝑖,𝑗)∈𝐸 exists if asset 𝑖 and asset 𝑗 share a significant correlation or dependency.
Each asset 𝑖 is associated with a feature vector 𝑋𝑖 consisting of ADX, DI+, and DI- values:

𝑋𝑖=[𝑥𝑖(ADX),𝑥𝑖(DI+),𝑥𝑖(DI-)]

Problem Statement:
Given a financial graph 𝐺=(𝑉,𝐸) and a set of node features 𝑋𝑖, how can we use information from neighboring assets to improve the predictive power of trend-following indicators and optimize trading decisions?

To solve this, we apply a Graph-Based Feature Aggregation:

𝑥~𝑖 feature = 1 / ∣𝑁(𝑖)∣ ∑ 𝑗 ∈ 𝑁(𝑖)𝑥𝑗 (featurex~)
ifeature​ = ∣N(i)∣1
​

j ∈ N(i) ∑​ x j feature
​

where 𝑁(𝑖) represents the set of neighboring assets of node 𝑖.

The goal is to use the aggregated signals:

𝑆=⋃𝑖=1𝑁𝑋𝑖​

as input for a Perceptron-based trading model that makes optimal trading decisions based on learned patterns in asset relationships.

Thus, we seek to:

Enhance trend-following indicators via graph-based aggregation.
Improve trading signal reliability by incorporating cross-asset dependencies.
Optimize trade execution using a supervised learning model.
This leads to the Graph-Enhanced Directional Trading (GEDT) Strategy, which dynamically updates market trend strength across a network of assets for improved trade decision-making.



Code
#define NUM_NODES 10
#define SELECTED_NODES 5  // Select only 5 nodes for DI+/DI-

var A[NUM_NODES][NUM_NODES];  // Adjacency matrix
var Signals[20];  // Max 20 elements for Perceptron

int selectedNodes[SELECTED_NODES] = {0, 2, 4, 6, 8};  // Selected nodes for DI+/DI-

void initialize_graph() {
    int i, j;

    // Manually define adjacency matrix
    A[0][1] = 1; A[0][4] = 1;
    A[1][0] = 1; A[1][2] = 1; A[1][5] = 1;
    A[2][1] = 1; A[2][3] = 1; A[2][6] = 1;
    A[3][2] = 1; A[3][4] = 1; A[3][7] = 1;
    A[4][0] = 1; A[4][3] = 1; A[4][8] = 1;
    A[5][1] = 1; A[5][6] = 1; A[5][9] = 1;
    A[6][2] = 1; A[6][5] = 1; A[6][7] = 1;
    A[7][3] = 1; A[7][6] = 1; A[7][8] = 1;
    A[8][4] = 1; A[8][7] = 1; A[8][9] = 1;
    A[9][5] = 1; A[9][8] = 1;
}

var aggregate_features(int node, vars FeatureSeries) {
    var sum = 0;
    int count = 0;
    int j;

    for (j = 0; j < NUM_NODES; j++) {
        if (A[node][j] == 1) {
            sum += FeatureSeries[j];
            count++;
        }
    }
    return ifelse(count > 0, sum / count, 0);
}

void run() {
    set(RULES | TESTNOW);

    if (is(INITRUN)) {
        initialize_graph();
    }

    vars ADX_Feature = series(ADX(14));
    vars DIPlus_Feature = series(PlusDI(14));
    vars DIMinus_Feature = series(MinusDI(14));

    vars Updated_ADX = series(0, NUM_NODES);
    vars Updated_DIPlus = series(0, NUM_NODES);
    vars Updated_DIMinus = series(0, NUM_NODES);

    int layer, i;
    for (layer = 0; layer < 2; layer++) {
        for (i = 0; i < NUM_NODES; i++) {
            Updated_ADX[i] = aggregate_features(i, ADX_Feature);
            Updated_DIPlus[i] = aggregate_features(i, DIPlus_Feature);
            Updated_DIMinus[i] = aggregate_features(i, DIMinus_Feature);
        }
        for (i = 0; i < NUM_NODES; i++) {
            ADX_Feature[i] = Updated_ADX[i];
            DIPlus_Feature[i] = Updated_DIPlus[i];
            DIMinus_Feature[i] = Updated_DIMinus[i];
        }
    }

    // Store ADX values from all 10 nodes
    for (i = 0; i < NUM_NODES; i++) {
        Signals[i] = ADX_Feature[i];
    }

    // Store DI+ and DI- from only SELECTED_NODES
    for (i = 0; i < SELECTED_NODES; i++) {
        Signals[NUM_NODES + i] = DIPlus_Feature[selectedNodes[i]];
        Signals[NUM_NODES + SELECTED_NODES + i] = DIMinus_Feature[selectedNodes[i]];
    }

    // Train Perceptron using only 20 elements
    if (adviseLong(PERCEPTRON, 0, Signals, 20) > 0)
        enterLong();
    if (adviseShort(PERCEPTRON, 0, Signals, 20) > 0)
        enterShort();
}

Attached Files
Last edited by TipmyPip; 02/19/25 22:54.
Optimal Execution Under Incomplete Information [Re: TipmyPip] #488620
02/20/25 09:56
02/20/25 09:56
Joined: Sep 2017
Posts: 147
T
TipmyPip Offline OP
Member
TipmyPip  Offline OP
Member
T

Joined: Sep 2017
Posts: 147
Strategy: Optimal Execution of EUR/USD Orders with Market Microstructure Models

Overview This strategy employs stochastic filtering and impulse control within a Markov-modulated limit order book (LOB). It is designed for high-frequency trading (HFT) and algorithmic execution, optimizing order placement under incomplete information about market liquidity.

We assume that the EUR/USD price evolution follows a Hawkes process, where order flows influence future price movements. Liquidity is treated as a hidden Markov process, which the strategy estimates in real-time.

1. Market Model Assumptions

Price Dynamics: The EUR/USD price follows an Ornstein-Uhlenbeck process with transient and permanent market impacts.
Liquidity Modeling: Hidden Markov-modulated liquidity states influence bid-ask spreads and market depth.
Market Impact: A concave power-law function describes execution price impact, limiting adverse price movement from large orders.
Execution Constraints: The strategy optimizes execution by deciding when and how much to trade, minimizing cost and slippage.

2. Strategy Components

2.1. Signal Generation (Regime Detection)

Use a Hidden Markov Model (HMM) to classify the current market regime:
Regime 1 (High Liquidity): Low market impact, high order book depth.
Regime 2 (Low Liquidity): High market impact, low order book depth.
Compute the posterior probability of the market being in Regime 1 using Bayesian inference.

2.2. Trade Execution (Impulse Control Optimization)

The strategy solves an optimal stopping problem:
If the probability of Regime 1 is high, execute a larger trade to take advantage of liquidity.
If the probability of Regime 2 increases, reduce trade size to minimize market impact.
Execution follows an adaptive liquidation model, using the Kushner-Stratonovich equations to update liquidity estimates.

3. Execution Algorithm

Step 1: Estimate Market Liquidity Using Filtering
Observe order arrivals and price changes.
Compute the expected liquidity state using a stochastic filter.
If liquidity is high (Regime 1), prepare to execute larger orders.

Step 2: Compute Optimal Trade Size
Define an inventory risk function:

𝐽(𝑡,𝑋𝑡) = 𝐸[∑𝑘𝐶(𝑆𝜏𝑘+𝐷𝜏𝑘,Δ𝑋𝜏𝑘)]

where:

𝑋𝑡 is inventory,
𝐶 is transaction cost,
𝑆𝜏𝑘 and 𝐷𝜏𝑘 are price components.

Solve for the optimal order size using a Bellman recursion:

𝑉(𝑡,𝑋𝑡)=max⁡Δ𝑋𝑡𝐸[𝐶(𝑆𝑡+𝐷𝑡,Δ𝑋𝑡)+𝑉(𝑡+1,𝑋𝑡−Δ𝑋𝑡)]

Step 3: Execute Trades Based on Liquidity Regime

Regime 1 (High Liquidity):
Execute larger trades (low price impact).
Use limit orders when spread is narrow.

Regime 2 (Low Liquidity):
Reduce order size to avoid price impact.
Use market orders only when necessary.

Step 4: Monitor Market Impact and Adjust Strategy
Compute the trade execution performance metric:
𝑃 slippage =Executed Price − Mid Price
​
Adjust trade sizes dynamically.



Code
#include <default.c>

#define LOOKBACK 5  
#define FEATURES 5  
#define X_MAX 100   

// Define Perceptron weights and biases manually
var PerceptronWeights[3] = {0.5, -0.3, 0.2};  
var PerceptronBias = 0.1;  

// Sigmoid activation function
var sigmoid(var x) {
    return 1.0 / (1.0 + exp(-x));
}

// Custom Perceptron function to replace `adviseLong()`
var perceptronPredict(vars Features, int size) {
    var weightedSum = PerceptronBias;
    int i;
    for (i = 0; i < size; i++) {  
        weightedSum += PerceptronWeights[i] * Features[i];
    }
    return sigmoid(weightedSum) * 100.0;  
}

// Compute dynamic liquidity probability
var computePiT() {
    vars atr_series = series(ATR(20), LOOKBACK);
    vars spread_series = series(Spread, LOOKBACK);
    vars price_series = series(priceClose(), LOOKBACK);
    vars stddev_series = series(0, LOOKBACK);

    stddev_series[0] = StdDev(price_series, 20);

    vars Features = series(0, 15);
    int i;
    for (i = 0; i < LOOKBACK; i++) { 
        Features[i] = atr_series[i] / priceClose();  
        Features[i + LOOKBACK] = stddev_series[i] / priceClose(); 
        Features[i + 2 * LOOKBACK] = spread_series[i] / 0.001;
    }

    return perceptronPredict(Features, 15) / 100.0;  
}

// Compute dynamic threshold for last 5 candles
void computeThresholdSeries(vars threshold_series) {
    vars atr_series = series(ATR(20), LOOKBACK);
    vars pi_series = series(computePiT(), LOOKBACK);

    int i;
    for (i = 0; i < LOOKBACK; i++) { 
        threshold_series[i] = 40 + (atr_series[i] * 100) - (pi_series[i] * 10);
        threshold_series[i] = clamp(threshold_series[i], 30, 70);
    }
}

function run() {
    set(PARAMETERS);  
    
	 StartDate = 20231231;
    EndDate = 2025;
    NumWFOCycles = 10;
    BarPeriod = 1;
    LookBack = 150;
    Capital = 1000;
	 
    vars X = series(priceClose());
    vars X_diff = series(priceClose(1) - priceClose());
    var pi_t = computePiT(); 

    vars threshold_series = series(0, LOOKBACK);
    computeThresholdSeries(threshold_series);

    vars DTREE_Features = series(0, FEATURES);
    int i;
    for (i = 0; i < LOOKBACK; i++) { 
        DTREE_Features[i] = threshold_series[i];
    }

    var trade_threshold = perceptronPredict(DTREE_Features, FEATURES);
    trade_threshold = clamp(trade_threshold, 30, 70);

    vars TradeFeatures = series(0, 3);
    TradeFeatures[0] = X[0];
    TradeFeatures[1] = X_diff[0];
    TradeFeatures[2] = pi_t;

    var long_prob = perceptronPredict(TradeFeatures, 3);
    var short_prob = perceptronPredict(TradeFeatures, 3) - 10;  

    int trade_flag = ifelse(long_prob > trade_threshold || short_prob > trade_threshold, 1, 0);
    var trade_size = ifelse(is(PARAMETERS), perceptronPredict(TradeFeatures, 3) / 100.0 * X_MAX, 10);
    string order_type = ifelse(long_prob > trade_threshold, "Market", "Limit");

    if (trade_flag) {
        if (long_prob > short_prob) {
            if (strstr(order_type, "Market")) {
                enterLong(trade_size);
            } else {
                enterLong(trade_size);
                Entry = priceClose() * 1.001;  
            }
        } else {
            if (strstr(order_type, "Market")) {
                enterShort(trade_size);
            } else {
                enterShort(trade_size);
                Entry = priceClose() * 0.999;  
            }
        }
    }

    printf("\nTrade Decision: %s", ifelse(trade_flag, "Execute", "Hold"));
    printf("\nTrade Size: %.2f units", trade_size);
    printf("\nOrder Type: %s", order_type);
    printf("\nPredicted Liquidity Probability (pi_t): %.2f", pi_t);
    printf("\nDynamic Threshold (DTREE Replaced): %.2f", trade_threshold);
}

Last edited by TipmyPip; 02/20/25 09:57.
Re: Zorro Trader GPT [Re: TipmyPip] #488622
02/20/25 23:12
02/20/25 23:12
Joined: Sep 2017
Posts: 147
T
TipmyPip Offline OP
Member
TipmyPip  Offline OP
Member
T

Joined: Sep 2017
Posts: 147
Challenges in Developing Machine Learning-Based Algorithmic Trading Systems

Introduction
The development of machine learning-driven trading systems presents a unique set of challenges, blending financial market analysis, algorithmic programming, and data-driven decision-making. While machine learning models promise improved decision-making and adaptability, the process of implementing them in a live trading environment is far from straightforward.

In this essay, we explore the key challenges that arise in projects like ours, based on our experience designing a feature-driven, self-learning trading system using a perceptron-based advisory model. These challenges fall into three broad categories:

Data Representation and Feature Engineering
Machine Learning Training and Model Adaptability
Financial Market Constraints and Changing Conditions
This essay aims to provide insights to traders, developers, and researchers who may face similar issues when developing algorithmic trading strategies.

1. Data Representation and Feature Engineering Issues

1.1 Importance of High-Quality Features

At the core of any machine learning model is feature engineering—the process of selecting and transforming raw market data into meaningful inputs for decision-making. The better the features, the better the model’s ability to predict market movements.

In our project, we incorporated features such as:

ATR (Average True Range) to measure volatility
Bid-Ask Spread to assess market liquidity
Standard Deviation of Closing Prices to capture price dispersion
Price Differences as a measure of momentum
However, several critical problems emerged in the data representation process:

Numerical Instability & Precision Loss

Some features frequently returned zero or negative values, which disrupted the machine learning model’s ability to generalize.
Rounding and scaling errors (e.g., improper use of fix0()) led to loss of precision, resulting in nearly identical feature values across different training cycles.
Feature Redundancy and Lack of Variability

Some computed features did not change significantly over time, leading to a situation where the model was effectively training on static data.
Without diverse and meaningful variations in input data, the machine learning model cannot detect new patterns.
Feature Misalignment with Market Structure

Some features were not well-suited to certain market regimes. For instance, ATR-based volatility measures became less useful during periods of extreme liquidity shifts.
Solution Strategies:

Introduce adaptive feature scaling to ensure values remain within an appropriate range.
Conduct feature importance analysis to identify which variables truly impact predictions.
Incorporate higher-frequency data (like order flow dynamics) to improve predictive power.

2. Challenges in Machine Learning Model Training

2.1 Model Learning Failure
A fundamental issue we encountered was that our machine learning models (Perceptron and Decision Tree) failed to adjust their decision boundaries over multiple training cycles.
This was evident in:

Consistently repeated model outputs after multiple cycles of training.
Static probabilities for long and short signals, suggesting the model was not learning new market behaviors.
Possible causes:

Training Data was Too Homogeneous

Without diverse market conditions in training data, the model struggled to learn different trading regimes.
Weights Not Updating Properly

If weight adjustments remain close to zero in every cycle, the model does not actually improve with each iteration.
Overuse of Fixed Normalization (fix0())

Removing decimal precision from input values likely weakened the depth of training, causing key information to be lost.
Solution Strategies:

Track weight updates after each training cycle to confirm learning is happening.
Introduce a rolling training window where only the most recent bars influence model updates.
Replace aggressive rounding functions (fix0) with normalized feature scaling that preserves market structure.

3. Financial Market Constraints and Changing Conditions

3.1 Market Regime Shifts
Financial markets are highly dynamic, meaning that patterns that existed during one period may become irrelevant later.
One of our biggest challenges was that the trading model performed consistently poorly after retraining, suggesting it was not adapting to new market conditions.

Key issues:

Market Volatility and Liquidity Changes
A model trained on low-volatility conditions may completely fail when a high-volatility regime emerges.
Lack of Order Flow Sensitivity
Our model did not include bid-ask imbalance data, which is critical for understanding short-term price movements.
Decision Threshold Anomalies
In multiple cases, our model produced trade thresholds of exactly zero, which resulted in no trading signals at all.
Solution Strategies:

Regime detection mechanisms that identify when the market has shifted and trigger adaptive model retraining.
Weighting recent price action more heavily in the learning process.
Enhancing feature sets with order book and volume-related indicators.

4. Debugging and Development Roadblocks
Beyond the technical issues in data and machine learning, real-world development also involves practical debugging difficulties:

Logging Issues: While we implemented logging functions, critical errors still required manual analysis of training output.
Error Propagation: A single feature issue (e.g., spread miscalculation) could cascade through the entire system, corrupting multiple layers of logic.
Cycle-Based Training Artifacts: Each new WFO (Walk Forward Optimization) cycle appeared to reset some learned information, introducing unexpected initialization problems.
How We Are Addressing These:

More granular debugging logs that track how each feature changes per training cycle.
Additional sanity checks on input data before passing it into the machine learning system.
Experimenting with incremental training updates instead of full retrains per cycle.
Conclusion
Developing machine learning-driven trading systems is a complex challenge that requires a multi-disciplinary approach across data science, financial modeling, and software engineering.

The key lessons learned from our project include:

Feature Engineering is the Most Critical Factor

Poorly designed features will lead to poor model performance, regardless of the sophistication of the machine learning algorithms.
Machine Learning Models Must Show Continuous Learning

If a model’s outputs are unchanging after multiple retrains, it is likely suffering from a lack of data diversity or improper weight updates.
Financial Markets Are Non-Stationary

Models that do not adapt to changing market conditions will become obsolete quickly.
For those embarking on similar projects, the key takeaway is that algorithmic trading development is an iterative process. No machine learning model will work perfectly out of the box, and extensive debugging, refinement, and real-world validation are necessary to build a robust and reliable system.

By addressing issues in feature selection, model learning dynamics, and real-world market adaptation, developers can improve their chances of creating an effective trading strategy that remains competitive in dynamic financial environments.
_______________________________________________________________________________________________________________________________________

Potential Problems in Machine Learning-Based Trading Strategies Using Perceptron Networks
Implementing a machine learning-driven trading strategy involves several potential pitfalls that can severely impact performance, especially when using Perceptron-based advisory models as seen in the given example. Below, I will walk through the major problems that may arise in this code and discuss how they could impact real-world trading. Tale of the Five Guardians

1. Data Quality and Indicator Calculation Issues

Problem 1: Feature Selection and Indicator Stability
The model relies on:

Awesome Oscillator (AO)
Relative Strength Index (RSI)
Basic price movements (Close Prices)
Potential Issue: Indicator Lag & False Signals
AO is a lagging indicator (based on a 5-period and 34-period SMA) and may not respond quickly to price changes.
RSI fluctuates around 50 and might not provide a strong enough signal on its own.
False crossovers or valleys: When using crossOver(AO, 0) or valley(AO), false signals may occur due to noise in the data.

Example Failure Case: False Crossover

Imagine AO crosses above zero due to a small market fluctuation, but the market immediately reverses.
The Perceptron treats this as a valid signal, leading to a bad trade.
Mitigation
Use volatility filters (e.g., ATR thresholds) to confirm signal strength.
Consider momentum confirmation rules.

2. Perceptron Learning and Weight Adaptation Issues

Problem 2: Perceptron Not Learning Properly

Each MLp[x] learns to recognize a specific condition in the market. However, since conditions are binary (0 or 1), the learning process may struggle due to:
Lack of meaningful variation: If most conditions stay at 0 (e.g., no crossover happens), the Perceptron doesn’t learn a useful pattern.
Bias toward non-trading: If the data is imbalanced, the model might default to always predicting no trade (finalOutput = 0).
Redundant learning: Since multiple Perceptrons are trained on similar conditions, the system might reinforce identical signals, reducing decision diversity.

Example Failure Case: Static Learning
If condition1 (AO trend) is mostly zero in historical data, the Perceptron may never learn an edge.
Over time, MLp[0] ≈ 0, meaning it contributes nothing to the final decision.

Mitigation
Regularly check Perceptron weight updates.
Introduce a fallback strategy for cases where MLp outputs remain static.

3. Dynamic Threshold Learning Issues
Problem 3: Threshold Convergence to Zero
The threshold (MLsignals[5]) is trained dynamically based on MLp outputs, but there are major risks:

If the Perceptron fails to distinguish good trades from noise, threshold will be too low, leading to random trades.
If the Perceptron learns incorrect correlations, threshold may converge to zero, making every price fluctuation trigger a trade.
Example Failure Case: Zero Threshold Anomaly

Code
Bar 1023: Threshold = 0.00001
Bar 1024: FinalOutput = 0.00002 → Triggers Long Entry
Bar 1025: FinalOutput = -0.00003 → Triggers Short Entry


This results in rapid overtrading and unnecessary losses.

Mitigation
Implement a minimum threshold value (e.g., clamp between 5 and 95).
Add a decay factor that prevents the threshold from over-adapting to noise.

4. Market Regime Sensitivity & Overfitting Risks
Problem 4: Overfitting to Specific Market Conditions
Since the model learns from historical patterns, it may:

Fail in new market conditions (e.g., high volatility events not seen in training).
Overreact to short-term anomalies rather than real trends.
Ignore macroeconomic changes (interest rate hikes, black swan events).
Example Failure Case: Overfitting to One Market Condition
Suppose the model trained on low-volatility data (e.g., 2019-2020 forex markets).
If a high-volatility event like COVID-19 news occurs, the learned patterns may break down.

Mitigation
Train with rolling windows rather than one long dataset.
Include market regime filters to adjust Perceptron weights dynamically.

5. Debugging and Visibility Issues

Problem 5: Lack of Visibility on Model Predictions
Without proper debugging logs, it’s difficult to know why a trade was placed.
If finalOutput changes unpredictably, it's unclear which MLp[x] contributed most.
Mitigation
Log raw outputs for each MLp signal.
Print threshold and final decision values at each step.
Final Thoughts
While machine learning offers great potential in trading, its implementation comes with several risks. The key takeaways from this example are:

Market indicators must be carefully chosen to avoid redundancy and noise.
Perceptron training should be monitored to ensure it learns useful patterns.
Threshold learning can break the system if it converges to 0 or extreme values.
Market regime shifts can destroy static models, requiring adaptive learning.
By identifying and mitigating these issues early, algorithmic traders can build more robust and reliable machine-learning trading strategies.

Last edited by TipmyPip; 02/20/25 23:14.
Markov Chain and Stochastic Asset Transitions [Re: TipmyPip] #488661
03/16/25 12:37
03/16/25 12:37
Joined: Sep 2017
Posts: 147
T
TipmyPip Offline OP
Member
TipmyPip  Offline OP
Member
T

Joined: Sep 2017
Posts: 147
Markov Chain and Stochastic Asset Transitions

A computational finance researcher is developing a Markov Chain-based stochastic model for predicting asset transitions in an algorithmic trading system. The trader's model tracks the evolution of asset-algorithm pairs over time and records state transitions in a matrix.

Abstract Problem Definition Let ???? be a finite set of traded assets and ???? be a finite set of trading algorithms.

Each market state ???? is uniquely determined by a pair (????,????) such that:

????(????????,????????)=???????????+????

where:

???? is the index of the asset
???????? from ????,???? is the index of the algorithm ???????? from ????,
?????? is the total number of algorithms.
At any given time ????, the system moves from one state to another, forming a discrete-time stochastic process represented by a transition probability matrix
????, where:

????????????=????(????????=??????????????????1=????????)

i.e., the probability of transitioning from state ???????? to state ????????.

The trader has recorded a total of ???? transitions over a period ???? and wishes to analyze various computationally intensive properties of the model.

Computational Challenge
On a given trading day, the trader observes the following facts:

A total of ????=105 transitions are recorded.
The most frequently visited state is ????(????????,????????), where:

???????? belongs to the top 5% of the most liquid assets.
???????? is the RSI-based strategy.
The highest probability transition is from ????(????????,????????)?????(????????,????????) with a transition frequency ????.Using this data, answer the following computationally intensive questions:

Questions:
1. Eigenvalues and Steady-State Distribution The trader wants to compute the long-term stationary distribution ???? of the Markov Chain, which satisfies:

????????=???? where ???? is the left eigenvector of ???? corresponding to eigenvalue 1.

Compute ???? numerically using an eigenvalue decomposition.

2. Transition Entropy and Predictability

Define the Shannon entropy of transitions as:

????=??????,???????????????? log ?????????????

where ???????????? is the normalized transition probability.

Compute ???? and interpret whether the transitions are highly predictable (low entropy) or random (high entropy).

3. Market Regime Clustering
Using the spectral properties of ????, perform clustering of market states using Laplacian eigenmaps:

????=????????? where ???? is the diagonal degree matrix.

Compute the first ???? eigenvectors of ???? and use k-means clustering to group market states into regimes.

4. Optimal Transition Path for Maximal Reward

Given a reward function ????(????????) that assigns a profit to each state, compute the optimal path through the Markov Chain that maximizes expected reward:

?????(????????)=max?????????(????(????????)+?????????(????????)????????????)

where ???? is the discount factor.

Solve for ????? using dynamic programming (Bellman recursion).

Bonus: Practical Implementation
Implement eigenvalue decomposition numerically to find steady-state probabilities.
Use Monte Carlo simulation to approximate transition entropy.
Apply Laplacian spectral clustering to identify market regimes.
Compute optimal trading state sequences using Markov Decision Processes (MDP).



Code
#ifndef MARKOVCHAINLIB_H
#define MARKOVCHAINLIB_H

#include <default.c> //  Ensures string functions are available

#define MAX_STATES 100

// Declare the Markov Chain transition matrix
int markovChain[MAX_STATES][MAX_STATES];

// Initialize the Markov Chain matrix with zeros manually
void initMarkovChain() {
    int i, j;
    for(i = 0; i < MAX_STATES; i++) {
        for(j = 0; j < MAX_STATES; j++) {
            markovChain[i][j] = 0;
        }
    }
}

//  Fixed: Use `strcmp()` or `==` for comparison
int findIndex(string* array, int size, string target) {
    int i;
    for (i = 0; i < size; i++) {
        if (array[i] == target) {  //  Simplified comparison
            return i; // Found, return index
        }
    }
    return -1; // Not found
}

// Function to get the index of an asset
int assetIdx(string asset) {
    static string assets[28];

    assets[0] = "EUR/USD";  assets[1] = "GBP/USD";  assets[2] = "USD/JPY"; 
    assets[3] = "USD/CHF";  assets[4] = "USD/CAD";  assets[5] = "AUD/USD"; 
    assets[6] = "NZD/USD";  assets[7] = "EUR/GBP";  assets[8] = "EUR/JPY"; 
    assets[9] = "EUR/CHF";  assets[10] = "GBP/JPY"; assets[11] = "GBP/CHF";
    assets[12] = "AUD/JPY"; assets[13] = "AUD/CHF"; assets[14] = "NZD/JPY";
    assets[15] = "NZD/CHF"; assets[16] = "CAD/JPY"; assets[17] = "CAD/CHF";
    assets[18] = "CHF/JPY"; assets[19] = "EUR/AUD"; assets[20] = "EUR/NZD"; 
    assets[21] = "EUR/CAD"; assets[22] = "GBP/AUD"; assets[23] = "GBP/NZD"; 
    assets[24] = "GBP/CAD"; assets[25] = "AUD/NZD"; assets[26] = "GBP/CHF"; 
    assets[27] = "NZD/CAD";

    return findIndex(assets, 28, asset);
}

// Function to get the index of an algorithm
int algoIdx(string algo) {
    static string algos[2]; 
    algos[0] = "rsi";
    algos[1] = "digi";

    return findIndex(algos, 2, algo);
}

// Function to compute the state ID based on asset and algorithm
int getStateID(string asset, string algo) {
    int aIdx = assetIdx(asset);
    int algoIdxValue = algoIdx(algo);
    
    if (aIdx == -1 || algoIdxValue == -1) {
        return -1; // Return invalid state if either index is not found
    }
    
    return aIdx * 2 + algoIdxValue; // Multiply by 2 because we have 2 algorithms
}

// Update the Markov Chain transition count
void updateMarkovChain(int prev, int next) {
    if (prev >= 0 && prev < MAX_STATES && next >= 0 && next < MAX_STATES) {
        markovChain[prev][next]++;
    }
}

#endif // MARKOVCHAINLIB_H




Code
#include "MarkovChainLib.h" // Include the Markov Chain logic

var MLsignals[8];
var Total_Dist = 0;
var Max_Weight = 0.3;
var totalWeight = 0;

#define dist AlgoVar[0]
#define component_weight AlgoVar[1]

void updateDist() {
    vars EquityCurve = series(EquityLong + EquityShort);
    vars EquityFilt = series(LowPass(EquityCurve, 100));
    dist = (EquityCurve[0] - EquityFilt[0]) * PIP;

    vars rsiSeries = series(RSI(series(price()), 14));
    vars atrSeries = series(ATR(100));
    MLsignals[0] = rsiSeries[0];
    MLsignals[1] = atrSeries[0];
    MLsignals[2] = EquityCurve[0];
    MLsignals[3] = EquityFilt[0];
    MLsignals[4] = dist;
    MLsignals[5] = component_weight;

    if (dist > 0) Total_Dist += dist;
}

void componentWeight() {
    if (dist <= 0) {
        component_weight = 0;
    } else {
        component_weight = ifelse(Total_Dist > 0, dist / Total_Dist, 0);
        if (component_weight > Max_Weight) component_weight = Max_Weight;

        var perceptronOutput = adviseLong(PERCEPTRON+RETURNS, 2, MLsignals, 8);
        Margin = 0.025 * component_weight * Capital * (1 + ifelse(perceptronOutput > 0, perceptronOutput / 100, perceptronOutput / 200));
    }
    totalWeight += component_weight;
}

//  Define the `tradeRSI()` function
void tradeRSI() {
    vars RSIs = series(RSI(series(price()), 14));

    if (crossOver(RSIs, 70)) {
        enterShort(); // RSI crosses above 70 ? Sell
    }
    else if (crossUnder(RSIs, 30)) {
        enterLong(); // RSI crosses below 30 ? Buy
    }
}

//  Define the `tradeDigi()` function
void tradeDigi() {
    if (price() > SMA(series(price()), 50)) {
        enterLong();  // If price is above SMA(50), enter a long trade
    } else {
        enterShort(); // Otherwise, enter a short trade
    }
}

void run() {
    set(PARAMETERS | RULES | PLOTNOW | TESTNOW);  
    StartDate = 20231231;
    EndDate = 2025;
    NumWFOCycles = 10;
    BarPeriod = 60;
    LookBack = 150;
    Capital = 1000;

    initMarkovChain();

    int prevState = -1;

    while (asset(loop(
        "EUR/USD", "GBP/USD", "USD/JPY", "USD/CHF", "USD/CAD", "AUD/USD", "NZD/USD",
        "EUR/GBP", "EUR/JPY", "EUR/CHF", "GBP/JPY", "GBP/CHF", "AUD/JPY", "AUD/CHF", "GBP/CHF", "NZD/CAD",
        "NZD/JPY", "NZD/CHF", "CAD/JPY", "CAD/CHF", "CHF/JPY",
        "EUR/AUD", "EUR/NZD", "EUR/CAD", "GBP/AUD", "GBP/NZD", "GBP/CAD", "AUD/NZD")))
    {
        while (algo(loop("rsi","digi"))) {
            updateDist();
            componentWeight();

            int currentStateID = getStateID(Asset, Algo);
            if (prevState != -1) updateMarkovChain(prevState, currentStateID);
            prevState = currentStateID;

            // FIXED: Replace `strxcmp()` with `strcmp()` or `==`
            if (Algo == "rsi") tradeRSI();
            else if (Algo == "digi") tradeDigi();
        }
    }

    // Normalize weights after all pairs and algos are processed
    while (algo(loop("rsi","digi"))) {
        component_weight /= totalWeight;
        plot(strf("Weight_%s_%s", Asset, Algo), component_weight, NEW, RED);
    }

    PlotWidth = 600;
    PlotHeight1 = 400;
}

Attached Files
Last edited by TipmyPip; 03/16/25 12:40.
VWAP Indicator for Zorro [Re: TipmyPip] #488679
03/26/25 23:22
03/26/25 23:22
Joined: Sep 2017
Posts: 147
T
TipmyPip Offline OP
Member
TipmyPip  Offline OP
Member
T

Joined: Sep 2017
Posts: 147
Here is a working VWAP indicator for Zorro.

Code
// === Helper Functions (must be above run) ===

var vwapPrice(int offset, int type)
{
	switch (type) {
		case 0: return priceClose(offset);
		case 1: return priceOpen(offset);
		case 2: return priceHigh(offset);
		case 3: return priceLow(offset);
		case 4: return (priceHigh(offset) + priceLow(offset)) / 2;
		case 5: return (priceHigh(offset) + priceLow(offset) + priceClose(offset)) / 3;
		case 6: return (priceHigh(offset) + priceLow(offset) + 2*priceClose(offset)) / 4;
		default: return priceClose(offset);
	}
}

var stdDevVWAP(int N, int offset, int type, var vwapValue)
{
	var s = 0;
	int i;
	for (i = 0; i < N; i++) {
		var p = vwapPrice(offset + i, type);
		s += pow(p - vwapValue, 2);
	}
	return sqrt(s / N);
}

var VWAP_Z(int N, int offset, int type)
{
	var sumPV = 0, sumVol = 0;
	int i;
	for (i = 0; i < N; i++) {
		var price = vwapPrice(offset + i, type);
		var volume = marketVol(offset + i);
		sumPV += price * volume;
		sumVol += volume;
	}
	return ifelse(sumVol > 0, sumPV / sumVol, 0);
}

// === Main Strategy/Indicator Function ===

function run()
{
	set(PLOTNOW);

	int N = 20;
	int type = 0; // 0 = PRICE_CLOSE
	var dev1 = 1, dev2 = 2, dev3 = 2.5;

	var vwapVal = VWAP_Z(N, 0, type);
	var stdDev = stdDevVWAP(N, 0, type, vwapVal);

	plot("VWAP", vwapVal, LINE, BLACK);

	plot("UpperBand1", vwapVal + dev1 * stdDev, LINE, RED);
	plot("LowerBand1", vwapVal - dev1 * stdDev, LINE, RED);

	plot("UpperBand2", vwapVal + dev2 * stdDev, LINE, GREEN);
	plot("LowerBand2", vwapVal - dev2 * stdDev, LINE, GREEN);

	plot("UpperBand3", vwapVal + dev3 * stdDev, LINE, BLUE);
	plot("LowerBand3", vwapVal - dev3 * stdDev, LINE, BLUE);
}

ZorroGPT [Re: TipmyPip] #488745
05/23/25 09:22
05/23/25 09:22
Joined: Sep 2017
Posts: 147
T
TipmyPip Offline OP
Member
TipmyPip  Offline OP
Member
T

Joined: Sep 2017
Posts: 147
New Version of ZorroGPT 2.66.1

https://bit.ly/3Hlfg8S

Code
function var ComplexIndicator()
{
    vars Price = series(price());
    vars FastMA = series(SMA(Price, 10));
    vars SlowMA = series(SMA(Price, 30));
    
    // Custom weighted oscillator
    var diff = (FastMA[0] - SlowMA[0]);
    var norm = (abs(FastMA[0]) + abs(SlowMA[0]))/2;
    var rawOsc = diff / (norm + 0.0001); // avoid div by 0
    
    // Non-linear scaling and signal enhancement
    var weight = pow(rawOsc, 3) * sin(4 * rawOsc); // enhanced non-linearity
    var smooth = EMA(series(weight), 14); // smooth the output

    return smooth[0];
}

Last edited by TipmyPip; 05/23/25 09:23.
Page 9 of 9 1 2 3 4 5 6 7 8 9

Moderated by  Petra 

Powered by UBB.threads™ PHP Forum Software 7.7.1