Custom Indicator
3 replies
Hoschie
2 years ago #287649
Hi I wrote a custome indicator for SupplyAndDemand, but when I use it on AlgoWizard. There is no trade. Did I something wrong? See Attachment.
Kind regards,
Hoschie
0
Theo Gottwald
2 years ago #287678
### Analysis of the Script
The script is written in Java and appears to be for **StrategyQuant**, which is a platform for automated trading strategies. The class SupplyDemand represents an indicator that calculates supply and demand levels for financial markets.
Here’s a breakdown of key components:
1. **Package and Imports**:
The script imports several libraries from the StrategyQuant platform, which provide functionalities like data handling, trading logic, logging, and custom indicator creation.
2. **Building Block Definition**:
The annotation @BuildingBlock defines the indicator as a building block for StrategyQuant’s environment. The name, display, and returnType define the name of the indicator and how it will appear in the platform, as well as the type of data it will return (in this case, price data).
3. **Parameters**:
– Input: A DataSeries object representing the input price series (likely OHLC data).
– Period: Defines how many bars (or periods) are used in the calculation. By default, it’s set to 10.
4. **Output**:
Value: A DataSeries representing the calculated supply-demand value for each bar.
5. **Core Logic**:
– OnBarUpdate(): This method is triggered every time a new bar (time period) is updated. It attempts to call the updateIndicator() method and catches any exceptions.
– updateIndicator(): This method checks if the input data and output series are valid, calculates the supply-demand value, and logs the output.
– calculateIndicatorValue(): This method calculates the average of the highest and lowest price over the defined Period and returns that as the indicator value.
6. **Error Handling**:
The code handles two types of exceptions:
– TradingException for custom trading errors.
– General Exception for unexpected errors, with both logged for debugging.
### Purpose and Use
The indicator computes an average of the highest and lowest prices over a given period to determine a midpoint price that can be interpreted as a supply or demand level. This midpoint can be used by traders to identify potential areas of support or resistance in a market. The value might signal possible price reversals, helping traders make buy or sell decisions.
### Possible Bugs or Improvements
1. **Null Checks**:
The Input and Value series are checked for null values, but only once when updating. A potential issue could occur if these become null during the indicator’s lifecycle (for example, if the data changes or is removed). You could add more robust checks or warnings if this occurs.
2. **Logging Frequency**:
The logging is quite verbose, especially when it logs on every bar update (Log.info("SupplyDemand: Set value...")). This could create performance issues or excessive log files in a live trading environment. Reducing the frequency or using a higher log level (like debug instead of info) could help.
3. **Performance Considerations**:
In the calculateIndicatorValue() method, the loop iterates over the Period to find the highest and lowest values. If the Period is very long (e.g., 1000), this might slow down performance. Consider optimizing this if the script is expected to run on large datasets or for high-frequency trading strategies.
4. **Edge Case Handling**:
The method uses CurrentBar < Period to handle the early bars (when there isn’t enough data to calculate the indicator). It just returns the first value in Input. This is acceptable but might produce inaccurate results for those first bars. You could consider more sophisticated logic (e.g., using a partial calculation or smoothing) to deal with this issue.
### Conclusion
This script is a custom supply-demand indicator for StrategyQuant, designed to calculate the average of the highest and lowest prices over a set period. It is useful for identifying market support and resistance levels.
It functions well overall but could benefit from a few performance improvements and enhanced logging control.
[code]
package SQ.Blocks.Indicators.SupplyDemand;
import com.strategyquant.lib.*;
import com.strategyquant.datalib.*;
import com.strategyquant.tradinglib.*;
import SQ.Internal.IndicatorBlock;
@BuildingBlock(name=”(XXX) SupplyDemand”, display=”SupplyDemand(#Period#)[#Shift#]”, returnType = ReturnTypes.Price)
@Help(“SupplyDemand help text”)
public class SupplyDemand extends IndicatorBlock {
@Parameter
public DataSeries Input;
@Parameter(defaultValue=”10″, isPeriod=true, minValue=2, maxValue=1000, step=1)
public int Period;
@Output
public DataSeries Value;
@Override
protected void OnBarUpdate() {
try {
updateIndicator();
} catch (TradingException e) {
Log.error(“SupplyDemand: TradingException in OnBarUpdate: ” + e.getMessage());
} catch (Exception e) {
Log.error(“SupplyDemand: Unexpected error in OnBarUpdate: ” + e.getMessage());
}
}
private void updateIndicator() throws TradingException {
// Ensure Input and Value are not null
if (Input == null) {
throw new TradingException(“Input DataSeries is null”);
}
if (Value == null) {
throw new TradingException(“Value DataSeries is null”);
}
double indiValue;
if (CurrentBar < Period) {
// Use an average of available values instead of just the first one for early bars
indiValue = averageOfAvailableValues();
Log.debug(“SupplyDemand: Using average of available values for early bars”);
} else {
indiValue = calculateIndicatorValue();
Log.debug(“SupplyDemand: Calculated value for bar ” + CurrentBar);
}
Value.set(0, indiValue);
Log.debug(“SupplyDemand: Set value ” + indiValue + ” for bar ” + CurrentBar);
}
private double calculateIndicatorValue() throws TradingException {
double highest = Input.get(0);
double lowest = Input.get(0);
// Optimized loop, start from 1 and avoid unnecessary conditions
for (int i = 1; i < Period; i++) {
highest = Math.max(highest, Input.get(i));
lowest = Math.min(lowest, Input.get(i));
}
Log.debug(“SupplyDemand: Highest: ” + highest + “, Lowest: ” + lowest);
return (highest + lowest) / 2;
}
// Average the values of the available bars when CurrentBar < Period
private double averageOfAvailableValues() {
double sum = 0.0;
int count = Math.min(CurrentBar + 1, Period); // Ensure we do not exceed available bars
for (int i = 0; i < count; i++) {
sum += Input.get(i);
}
return sum / count;
}
}
[/code]
PS: UNTESTED.
**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
Hoschie
2 years ago #287718
Hallo Theo,
vielen Dank.
1
Theo Gottwald
2 years ago #287719
Keine Ursache, ich würde sogar sagen …. nimm dass:
[code]
package SQ.Blocks.Indicators.SupplyDemand;
import com.strategyquant.lib.*;
import com.strategyquant.datalib.*;
import com.strategyquant.tradinglib.*;
import SQ.Internal.IndicatorBlock;
@BuildingBlock(name=”(XXX) SupplyDemand”, display=”SupplyDemand(#Period#)[#Shift#]”, returnType = ReturnTypes.Price)
@Help(“SupplyDemand help text”)
public class SupplyDemand extends IndicatorBlock {
@Parameter
public DataSeries Input;
@Parameter(defaultValue=”10″, isPeriod=true, minValue=2, maxValue=1000, step=1)
public int Period;
@Output
public DataSeries Value;
@Override
protected void OnBarUpdate() {
try {
updateIndicator();
} catch (TradingException e) {
Log.error(“SupplyDemand: TradingException in OnBarUpdate: ” + e.getMessage());
} catch (Exception e) {
Log.error(“SupplyDemand: Unexpected error in OnBarUpdate: ” + e.getMessage());
}
}
private void updateIndicator() throws TradingException {
// Sicherstellen, dass Input und Value nicht null sind
if (Input == null) {
throw new TradingException(“Input DataSeries is null”);
}
if (Value == null) {
throw new TradingException(“Value DataSeries is null”);
}
double indiValue;
if (CurrentBar < Period – 1) {
// Durchschnitt der verfügbaren Werte für frühe Bars verwenden
indiValue = averageOfAvailableValues();
Log.debug(“SupplyDemand: Using average of available values for early bars”);
} else {
indiValue = calculateIndicatorValue();
Log.debug(“SupplyDemand: Calculated value for bar ” + CurrentBar);
}
Value.set(0, indiValue);
Log.debug(“SupplyDemand: Set value ” + indiValue + ” for bar ” + CurrentBar);
}
private double calculateIndicatorValue() throws TradingException {
// Sicherstellen, dass genügend Datenpunkte vorhanden sind
if (Input.size() < Period) {
throw new TradingException(“Not enough data to calculate indicator value”);
}
double highest = Input.get(0);
double lowest = Input.get(0);
// Schleife über die letzten ‘Period’ Bars
for (int i = 1; i < Period; i++) {
double value = Input.get(i);
highest = Math.max(highest, value);
lowest = Math.min(lowest, value);
}
Log.debug(“SupplyDemand: Highest: ” + highest + “, Lowest: ” + lowest);
return (highest + lowest) / 2;
}
// Durchschnitt der verfügbaren Werte berechnen, wenn CurrentBar < Period – 1
private double averageOfAvailableValues() throws TradingException {
int count = CurrentBar + 1; // Anzahl der verfügbaren Bars
// Sicherstellen, dass mindestens ein Datenpunkt vorhanden ist
if (count <= 0) {
throw new TradingException(“No available data to average”);
}
double sum = 0.0;
for (int i = 0; i < count; i++) {
sum += Input.get(i);
}
return sum / count;
}
}[/code]
**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 3 replies - 1 through 3 (of 3 total)