Is it possible to get 2 inputs (DataSeries) into a custom indicator?
5 replies
Dav
2 years ago #287834
Dear our community,
I want to write a new indicator similar to MA for a pair that isn’t supported. For example, a pair A_B that isn’t supported, but A_USD and B_USD are already supported.
As I know, in order to create a custom indicator like that requirement by programming in Java, I need 2 inputs (DataSeries), one for A_USD and other for B_USD. But, I don’t know how to get these inputs?
I tried several ways but not work.
This is the last try:
0
Theo Gottwald
2 years ago #287859
@BuildingBlock(name=”(HD) MA2S”, display=”MA2S(#Symbol1#,#Symbol2#)[#Shift#]”, returnType = ReturnTypes.Number)
@Help(“Moving Average calculated from the ratio of two symbols”)
public class MA2S extends IndicatorBlock {@Parameter(name = “Symbol1”)
public String symbol1;@Parameter(name = “Symbol2″)
public String symbol2;@Parameter(defaultValue=”10”, isPeriod=true, minValue=2, maxValue=1000, step=1)
public int Period;@Output
public DataSeries Value;private DataSeries symbol1Price;
private DataSeries symbol2Price;@Override
protected void Init() throws TradingException {
// Initialize price series for both symbols
symbol1Price = GetSymbolData(symbol1, PriceType.Close);
symbol2Price = GetSymbolData(symbol2, PriceType.Close);
}@Override
protected void OnBarUpdate() throws TradingException {
if (CurrentBar < Period) {
Value.Set(Double.NaN);
return;
}double sum = 0;
for (int i = 0; i < Period; i++) {
// Calculate the ratio for each bar
double ratio = symbol1Price.Get(i) / symbol2Price.Get(i);
sum += ratio;
}// Calculate and set the average
Value.Set(sum / Period);
}
}
Key points about this implementation:
Use @Parameter with String type to allow symbol selection
@Parameter(name = “Symbol1”)
public String symbol1;
Use GetSymbolData() method to get price data for symbols
symbol1Price = GetSymbolData(symbol1, PriceType.Close);
Initialize the price series in the Init() method rather than trying to get them directly as parameters
You can use this indicator like:
MA2S(“EURUSD”, “GBPUSD”, 10)[0]
Additional features you might want to add:
Price type selection:
java
Copy
@Parameter(name = “Price Type”, defaultValue = “Close”)
public PriceType priceType;
// In Init():
symbol1Price = GetSymbolData(symbol1, priceType);
symbol2Price = GetSymbolData(symbol2, priceType);
Error handling:
@Override
protected void Init() throws TradingException {
try {
symbol1Price = GetSymbolData(symbol1, priceType);
symbol2Price = GetSymbolData(symbol2, priceType);
} catch (Exception e) {
throw new TradingException(“Error initializing price data: ” + e.getMessage());
}
}
Validation:
@Override
protected void OnBarUpdate() throws TradingException {
if (symbol1Price == null || symbol2Price == null) {
throw new TradingException(“Price data not initialized”);
}
if (symbol2Price.Get(0) == 0) {
Value.Set(Double.NaN);
return;
}
// … rest of the calculation
}
This implementation will allow you to create a moving average based on any two symbols that are available in your data feed. The indicator will calculate the ratio between the two symbols for each bar and then compute the moving average of these ratios.
**Mit besten Grüßen | With best regards | Cordiali saluti**
**Theo Gottwald**
*Leading Expert in SPR & Visual Automation*
???? **What's New in the Q4 Update?**
1️⃣ Open AI Vision: Empower your SPR with cutting-edge visual recognition. See the unseen. ????????
2️⃣ Open AI TTS: Seamlessly transform text into natural, lifelike speech. Hear the difference. ????️????
3️⃣ GPT-4 with 128k Token Context Window by OpenAI: Dive into unparalleled depth in AI conversations. Think deeper. ????????
4️⃣ DALLE-3 by OpenAI: Command revolutionary AI to generate stunning images. Imagine more. ????️????
5️⃣ ElevenLabs Text to Speech: Experience text-to-speech so lifelike, it speaks to you. ????️
6️⃣ Stable Diffusion Local & Online via Automatic1111: Unlock creativity with both local and cloud-based image generation. Create anywhere. ☁️????
7️⃣ GPT4All & LM Studio: Harness powerful offline AI capabilities. Your studio, smarter. ????️????
8️⃣ DeepL Translator with SPR Integration: Achieve real-time, accurate translations. Speak the world's language. ????????
9️⃣ ChatGPT by OpenAI: Engage with your SPR through natural, dynamic conversations. Connect genuinely. ????️
???? WHISPER by OpenAI: Convert voice to text with effortless precision. Listen, transcribe, act. ????️????
???? Mistral AI: Scale your AI integration with seamless efficiency. Elevate your AI journey. ????????
???? Claude 3 by Anthropic: Experience next-level AI understanding and interactivity. Discover AI with a human touch. ????????
???? **Address:**
Herrenstr. 11, 76706 Dettenheim, Germany
???? **Phone:**
Office: +49 (7247) 9851112
Mobile: +49 160 6688 222
Fax: +49 (7247) 9851113
???? **Email:**
[[email protected]](mailto:[email protected])
???? **Websites:**
[IT-Berater](http://www.it-berater.org) | [Smart Package](http://www.smart-package.com)
0
Theo Gottwald
2 years ago #287860
The last explanation part was destroyed by the Forum Software.
So I paste it here unformatted.
<p data-pm-slice=”1 1 []”>Key points about this implementation:</p>
1. Use @Parameter with String type to allow symbol selection
`java
@Parameter(name = “Symbol1”)
public String symbol1;
`
2. Use GetSymbolData() method to get price data for symbols
`java
symbol1Price = GetSymbolData(symbol1, PriceType.Close);
`
3. Initialize the price series in the Init() method rather than trying to get them directly as parameters
4. You can use this indicator like:
`java
MA2S(“EURUSD”, “GBPUSD”, 10)[0]
`
Additional features you might want to add:
1. Price type selection:
`java
@Parameter(name = “Price Type”, defaultValue = “Close”)
public PriceType priceType;
// In Init():
symbol1Price = GetSymbolData(symbol1, priceType);
symbol2Price = GetSymbolData(symbol2, priceType);
`
2. Error handling:
`java
@Override
protected void Init() throws TradingException {
try {
symbol1Price = GetSymbolData(symbol1, priceType);
symbol2Price = GetSymbolData(symbol2, priceType);
} catch (Exception e) {
throw new TradingException(“Error initializing price data: ” + e.getMessage());
}
}
`
3. Validation:
`java
@Override
protected void OnBarUpdate() throws TradingException {
if (symbol1Price == null || symbol2Price == null) {
throw new TradingException(“Price data not initialized”);
}
if (symbol2Price.Get(0) == 0) {
Value.Set(Double.NaN);
return;
}
// … rest of the calculation
}
`
This implementation will allow you to create a moving average based on any two symbols that are available in your data feed. The indicator will calculate the ratio between the two symbols for each bar and then compute the moving average of these ratios.
**Mit besten Grüßen | With best regards | Cordiali saluti**
**Theo Gottwald**
*Leading Expert in SPR & Visual Automation*
???? **What's New in the Q4 Update?**
1️⃣ Open AI Vision: Empower your SPR with cutting-edge visual recognition. See the unseen. ????????
2️⃣ Open AI TTS: Seamlessly transform text into natural, lifelike speech. Hear the difference. ????️????
3️⃣ GPT-4 with 128k Token Context Window by OpenAI: Dive into unparalleled depth in AI conversations. Think deeper. ????????
4️⃣ DALLE-3 by OpenAI: Command revolutionary AI to generate stunning images. Imagine more. ????️????
5️⃣ ElevenLabs Text to Speech: Experience text-to-speech so lifelike, it speaks to you. ????️
6️⃣ Stable Diffusion Local & Online via Automatic1111: Unlock creativity with both local and cloud-based image generation. Create anywhere. ☁️????
7️⃣ GPT4All & LM Studio: Harness powerful offline AI capabilities. Your studio, smarter. ????️????
8️⃣ DeepL Translator with SPR Integration: Achieve real-time, accurate translations. Speak the world's language. ????????
9️⃣ ChatGPT by OpenAI: Engage with your SPR through natural, dynamic conversations. Connect genuinely. ????️
???? WHISPER by OpenAI: Convert voice to text with effortless precision. Listen, transcribe, act. ????️????
???? Mistral AI: Scale your AI integration with seamless efficiency. Elevate your AI journey. ????????
???? Claude 3 by Anthropic: Experience next-level AI understanding and interactivity. Discover AI with a human touch. ????????
???? **Address:**
Herrenstr. 11, 76706 Dettenheim, Germany
???? **Phone:**
Office: +49 (7247) 9851112
Mobile: +49 160 6688 222
Fax: +49 (7247) 9851113
???? **Email:**
[[email protected]](mailto:[email protected])
???? **Websites:**
[IT-Berater](http://www.it-berater.org) | [Smart Package](http://www.smart-package.com)
0
Theo Gottwald
2 years ago #287861
<p data-pm-slice=”1 1 []”>Here are 10 significant improvements for the MA2S indicator:</p>
1. Add Data Validation and Safety Checks:
`java
@Override
protected void Init() throws TradingException {
if (symbol1.equals(symbol2)) {
throw new TradingException(“Symbols must be different”);
}
if (Period <= 0) {
throw new TradingException(“Period must be positive”);
}
try {
symbol1Price = GetSymbolData(symbol1, priceType);
symbol2Price = GetSymbolData(symbol2, priceType);
} catch (Exception e) {
throw new TradingException(“Failed to initialize price data: ” + e.getMessage());
}
}
`
2. Add Multiple MA Types:
`java
@Parameter(name = “MA Type”, defaultValue = “Simple”)
public MAType maType;
public enum MAType {
Simple,
Exponential,
Weighted,
Hull
}
private double calculateMA() {
switch (maType) {
case Simple: return calculateSMA();
case Exponential: return calculateEMA();
case Weighted: return calculateWMA();
case Hull: return calculateHull();
default: return calculateSMA();
}
}
`
3. Add Caching for Performance:
`java
private double[] ratioCache;
private int lastUpdatedBar = -1;
private void updateCache() {
if (lastUpdatedBar != CurrentBar) {
if (ratioCache == null) {
ratioCache = new double[Period];
}
for (int i = 0; i < Period; i++) {
ratioCache[i] = symbol1Price.Get(i) / symbol2Price.Get(i);
}
lastUpdatedBar = CurrentBar;
}
}
`
4. Add Statistical Measures:
`java
@Output(name = “StandardDeviation”)
public DataSeries StdDev;
@Output(name = “UpperBand”)
public DataSeries UpperBand;
@Output(name = “LowerBand”)
public DataSeries LowerBand;
private void calculateStatistics() {
double ma = Value.Get(0);
double sumSquaredDiff = 0;
for (int i = 0; i < Period; i++) {
double diff = ratioCache[i] – ma;
sumSquaredDiff += diff * diff;
}
double stdDev = Math.sqrt(sumSquaredDiff / Period);
StdDev.Set(stdDev);
UpperBand.Set(ma + (2 * stdDev));
LowerBand.Set(ma – (2 * stdDev));
}
`
5. Add Normalization Options:
`java
@Parameter(name = “Normalize”, defaultValue = “false”)
public boolean normalize;
@Parameter(name = “Normalization Period”, defaultValue = “100”)
public int normalizationPeriod;
private double getNormalizedRatio(double ratio) {
if (!normalize) return ratio;
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE;
for (int i = 0; i < normalizationPeriod; i++) {
double historicalRatio = symbol1Price.Get(i) / symbol2Price.Get(i);
max = Math.max(max, historicalRatio);
min = Math.min(min, historicalRatio);
}
return (ratio – min) / (max – min);
}
`
6. Add Time-Weighted Calculation:
`java
@Parameter(name = “Time Weighted”, defaultValue = “false”)
public boolean timeWeighted;
private double calculateTimeWeightedMA() {
double sum = 0;
double weightSum = 0;
for (int i = 0; i < Period; i++) {
double weight = timeWeighted ? (Period – i) : 1;
sum += ratioCache[i] * weight;
weightSum += weight;
}
return sum / weightSum;
}
`
7. Add Volume Consideration:
`java
@Parameter(name = “Volume Weighted”, defaultValue = “false”)
public boolean volumeWeighted;
private DataSeries symbol1Volume;
private DataSeries symbol2Volume;
private double calculateVolumeWeightedMA() {
double sum = 0;
double volumeSum = 0;
for (int i = 0; i < Period; i++) {
double volume = Math.min(symbol1Volume.Get(i), symbol2Volume.Get(i));
sum += ratioCache[i] * volume;
volumeSum += volume;
}
return sum / volumeSum;
}
`
8. Add Adaptive Period:
`java
@Parameter(name = “Adaptive Period”, defaultValue = “false”)
public boolean adaptivePeriod;
@Parameter(name = “Volatility Factor”, defaultValue = “2.0”)
public double volatilityFactor;
private int getAdaptivePeriod() {
if (!adaptivePeriod) return Period;
double volatility = calculateVolatility();
return Math.max(2, (int)(Period * (1 + volatilityFactor * volatility)));
}
`
9. Add Error Metrics:
`java
@Output(name = “MAE”)
public DataSeries MeanAbsoluteError;
@Output(name = “RMSE”)
public DataSeries RootMeanSquaredError;
private void calculateErrorMetrics() {
double ma = Value.Get(0);
double sumAbsError = 0;
double sumSquaredError = 0;
for (int i = 0; i < Period; i++) {
double error = Math.abs(ratioCache[i] – ma);
sumAbsError += error;
sumSquaredError += error * error;
}
MeanAbsoluteError.Set(sumAbsError / Period);
RootMeanSquaredError.Set(Math.sqrt(sumSquaredError / Period));
}
`
10. Add Trend Detection:
`java
@Output(name = “Trend”)
public DataSeries Trend;
@Parameter(name = “Trend Threshold”, defaultValue = “0.001”)
public double trendThreshold;
private void detectTrend() {
double currentMA = Value.Get(0);
double previousMA = Value.Get(1);
if (Math.abs(currentMA – previousMA) < trendThreshold) {
Trend.Set(0); // Sideways
} else {
Trend.Set(currentMA > previousMA ? 1 : -1); // Up or Down
}
}
`
Implementation:
`java
@Override
protected void OnBarUpdate() throws TradingException {
if (CurrentBar < Period) {
Value.Set(Double.NaN);
return;
}
updateCache();
double maValue;
if (volumeWeighted) {
maValue = calculateVolumeWeightedMA();
} else if (timeWeighted) {
maValue = calculateTimeWeightedMA();
} else {
maValue = calculateMA();
}
Value.Set(maValue);
calculateStatistics();
calculateErrorMetrics();
detectTrend();
}
`
These improvements make the indicator more versatile, robust, and informative. Users can choose different calculation methods and get additional statistical information about the ratio between the two symbols.
**Mit besten Grüßen | With best regards | Cordiali saluti**
**Theo Gottwald**
*Leading Expert in SPR & Visual Automation*
???? **What's New in the Q4 Update?**
1️⃣ Open AI Vision: Empower your SPR with cutting-edge visual recognition. See the unseen. ????????
2️⃣ Open AI TTS: Seamlessly transform text into natural, lifelike speech. Hear the difference. ????️????
3️⃣ GPT-4 with 128k Token Context Window by OpenAI: Dive into unparalleled depth in AI conversations. Think deeper. ????????
4️⃣ DALLE-3 by OpenAI: Command revolutionary AI to generate stunning images. Imagine more. ????️????
5️⃣ ElevenLabs Text to Speech: Experience text-to-speech so lifelike, it speaks to you. ????️
6️⃣ Stable Diffusion Local & Online via Automatic1111: Unlock creativity with both local and cloud-based image generation. Create anywhere. ☁️????
7️⃣ GPT4All & LM Studio: Harness powerful offline AI capabilities. Your studio, smarter. ????️????
8️⃣ DeepL Translator with SPR Integration: Achieve real-time, accurate translations. Speak the world's language. ????????
9️⃣ ChatGPT by OpenAI: Engage with your SPR through natural, dynamic conversations. Connect genuinely. ????️
???? WHISPER by OpenAI: Convert voice to text with effortless precision. Listen, transcribe, act. ????️????
???? Mistral AI: Scale your AI integration with seamless efficiency. Elevate your AI journey. ????????
???? Claude 3 by Anthropic: Experience next-level AI understanding and interactivity. Discover AI with a human touch. ????????
???? **Address:**
Herrenstr. 11, 76706 Dettenheim, Germany
???? **Phone:**
Office: +49 (7247) 9851112
Mobile: +49 160 6688 222
Fax: +49 (7247) 9851113
???? **Email:**
[[email protected]](mailto:[email protected])
???? **Websites:**
[IT-Berater](http://www.it-berater.org) | [Smart Package](http://www.smart-package.com)
0
Dav
2 years ago #287877
I got troubles with compile error from your code.
Such as:
>> method does not override or implement a method from a supertype: Init()
>> cannot find symbol: PriceType
>> cannot find symbol: GetSymbolData
0
Theo Gottwald
2 years ago #287902
Hello! It’s quite possible that this code contains bugs since it’s untested. The best approach is to input it into ChatGPT or Anthropic 3.5 and let them correct the code for you. Test it again, and if there are more errors, submit it once more for corrections. This is the best way to proceed. Currently, I’m unable to do much work on the screen.
#CodeCorrection #Debugging #ChatGPT #Anthropic #SoftwareTesting
**Mit besten Grüßen | With best regards | Cordiali saluti**
**Theo Gottwald**
*Leading Expert in SPR & Visual Automation*
???? **What's New in the Q4 Update?**
1️⃣ Open AI Vision: Empower your SPR with cutting-edge visual recognition. See the unseen. ????????
2️⃣ Open AI TTS: Seamlessly transform text into natural, lifelike speech. Hear the difference. ????️????
3️⃣ GPT-4 with 128k Token Context Window by OpenAI: Dive into unparalleled depth in AI conversations. Think deeper. ????????
4️⃣ DALLE-3 by OpenAI: Command revolutionary AI to generate stunning images. Imagine more. ????️????
5️⃣ ElevenLabs Text to Speech: Experience text-to-speech so lifelike, it speaks to you. ????️
6️⃣ Stable Diffusion Local & Online via Automatic1111: Unlock creativity with both local and cloud-based image generation. Create anywhere. ☁️????
7️⃣ GPT4All & LM Studio: Harness powerful offline AI capabilities. Your studio, smarter. ????️????
8️⃣ DeepL Translator with SPR Integration: Achieve real-time, accurate translations. Speak the world's language. ????????
9️⃣ ChatGPT by OpenAI: Engage with your SPR through natural, dynamic conversations. Connect genuinely. ????️
???? WHISPER by OpenAI: Convert voice to text with effortless precision. Listen, transcribe, act. ????️????
???? Mistral AI: Scale your AI integration with seamless efficiency. Elevate your AI journey. ????????
???? Claude 3 by Anthropic: Experience next-level AI understanding and interactivity. Discover AI with a human touch. ????????
???? **Address:**
Herrenstr. 11, 76706 Dettenheim, Germany
???? **Phone:**
Office: +49 (7247) 9851112
Mobile: +49 160 6688 222
Fax: +49 (7247) 9851113
???? **Email:**
[[email protected]](mailto:[email protected])
???? **Websites:**
[IT-Berater](http://www.it-berater.org) | [Smart Package](http://www.smart-package.com)
0
Viewing 5 replies - 1 through 5 (of 5 total)