You are an expert technical analyst specializing in candlestick chart patterns.
Your task is to generate mock candlestick data in JSON format based on a provided strategy description.
Follow the detailed steps below to ensure accuracy and precision in your data generation, adapting to any given strategy or market setup.
Step 1: Strategy Analysis
Carefully read the strategy description: Understand the objectives and elements of the described strategy.
Identify and list the following key components:
Setup Name
Strategy Type (e.g., Breakout, Reversal, Continuation, Trend Following, Mean Reversion)
Specific Criteria or Rules (e.g., 2LYNCH criteria, RSI conditions, Moving Average crossovers)
Any mentioned indicators or oscillators
Step 2: Stage Identification and Adaptation
Break down the strategy into distinct stages (e.g., trend formation, consolidation, entry signal, exit signal).
For each stage, determine and list:
Exact Number of Candles: If a range is provided, select a specific number within that range. If not specified, use a reasonable number based on the strategy type.
Exact Number of Bullish (Green) and Bearish (Red) Candles: Precisely define the count to match the strategy's requirements.
Specific Candle Characteristics: (e.g., closing near high, wide ranges, doji candles, engulfing patterns)
Volume Trends: Include volume analysis if mentioned in the strategy.
Price Action: Describe any specific price movements required (e.g., higher highs, lower lows, sideways movement).
Indicator Behavior: If the strategy uses indicators, describe how they should behave during each stage.
Step 3: Data Generation
Start Date: [Use the provided start date or default to current year, e.g., 2024-01-01]
For each stage:
Generate the exact number of candles as determined in Step 2.
Ensure the precise number of green and red candles according to the requirements.
For each candle:
Date: Increment sequentially from the start date.
Open: [Previous Close]
High: [Max(Open, Close) + Random(0.1% to 2% of price)]
Low: [Min(Open, Close) - Random(0.1% to 2% of price)]
Close:
For bearish candles (red): [Open - Random(0.1% to 2% of price)]
For bullish candles (green): [Open + Random(0.1% to 2% of price)]
Volume: [Base Volume + Random(-20% to +20%)] adjusted according to the volume trend requirements of each stage.
Assistant
Adjust price movements to reflect the strategy's requirements (e.g., breakouts, pullbacks, consolidations).
If required, calculate and include indicator values based on the generated price data.
Step 4: JSON Compilation
Structure the data in the exact JSON format below:
json
{{
"candlestickData": [
{{
"date": "YYYY-MM-DD",
"open": 100.00,
"high": 102.00,
"low": 99.50,
"close": 101.80,
"volume": 1000000
}}
// ... exact number of data points as specified
],
"indicators": {{
// Include any relevant indicators mentioned in the strategy
"sma20": [100.5, 101.2, ...],
"rsi": [45, 52, ...]
}},
"explanation": "Detailed explanation here"
}}
## Step 5: Detailed Explanation Consistent with Final Data
1. Provide a comprehensive explanation that includes:
- Total Number of Candles Generated
- Breakdown of Candles per Stage: (e.g., 7 candles for trend formation: 5 green, 2 red)
- Accuracy of Bullish and Bearish Candle Counts per Stage
- How Each Stage Represents the Strategy Requirements
- Any Specific Patterns or Characteristics Implemented
- Indicator Behavior and Significance (if applicable)
- Key Entry and Exit Points Based on the Strategy
- Ensure that all details in the explanation exactly match the attributes of the generated candlestick data.
## Step 6: Data Validation
1. Review the generated data to ensure:
- Correct Total Number of Candles
- Accurate Number of Bullish and Bearish Candles per Stage
- Logical Price Movements: (e.g., High > Open, Close > Low)
- Volume Trends Align with Strategy Requirements
- Indicator Values (if included) are Consistent with Price Movements
- The Data Accurately Reflects All Aspects of the Given Strategy
## Step 7: Data Correction
1. If the mock data does not meet the specified requirements after validation:
- Identify the discrepancies: Determine which aspects of the data are incorrect (e.g., incorrect number of candles, wrong candle colors, illogical price movements, misaligned indicator values).
- Adjust the data accordingly:
- Modify Candle Counts: Add or remove candles to match the exact number required.
- Correct Candle Colors: Change the color of candles by adjusting the close prices appropriately.
- Fix Price Movements: Ensure all price fields adhere to logical constraints and strategy requirements.
- Recalculate Volumes: Adjust volume values to align with the specified volume trends.
- Update Indicator Values: Recalculate any indicator values to ensure they match the adjusted price data.
- Re-validate the corrected data: Ensure that all modifications now meet the original requirements and strategy specifications.
- Update the Explanation: Regenerate the detailed explanation in Step 5 to accurately reflect the corrected data.
## Step 8: Final Data Confirmation
1. Perform a final review to ensure all data is accurate and compliant:
- Double-check candle counts, colors, and patterns.
- Ensure all price movements are logical and align with the strategy.
- Verify volume trends align with strategy requirements.
- Confirm indicator values (if present) are correct and meaningful.
- Ensure the JSON structure is correct and free of errors.
- Confirm the explanation fully matches the final data and accurately describes how the data represents the given strategy.
##Execution
Given this strategy description: {description}
Follow each step meticulously, providing your thought process for each step. Ensure exact compliance with the strategy's requirements for candle numbers, characteristics, and any specific patterns or indicators mentioned.
Adapt the data generation process as needed to accurately represent the given strategy."""
Hãy tách prompt này làm 3 prompt, và viết code chạy sequential chain trong LangChain, với 3 chain liên tiếp. Mục đích từ 1 description về biểu đồ hình nến tạo ra được mock data chính xác đúng yêu cầu. Ví dụ về code multiple chain: from langchain_anthropic import ChatAnthropic
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_template("tell me a joke about {topic}")
model = ChatAnthropic(model_name="claude-3-haiku-20240307")
chain = prompt | model | StrOutputParser() \n from langchain_core.output_parsers import StrOutputParser
analysis_prompt = ChatPromptTemplate.from_template("is this a funny joke? {joke}")
composed_chain = {"joke": chain} | analysis_prompt | model | StrOutputParser() \n composed_chain.invoke({"topic": "bears"}) \n Lưu ý cấu trúc đầu ra trả về của mỗi prompt để có thể đưa được vào đầu vào của prompt tiếp theo! Bước explanation nên để cuối cùng, khi tìm ra được kết quả cuối cùng!
Certainly! To achieve the goal of generating accurate mock candlestick data from a strategy description using LangChain, we'll split the comprehensive PROMPT_TEMPLATE_9 into three distinct prompts. Each prompt will handle specific stages of the process, ensuring a structured and sequential data generation workflow. Below is the detailed breakdown of the prompts and the corresponding LangChain implementation.
1. Splitting the Prompt into Three Parts
Prompt 1: Strategy Analysis and Stage Identification
This prompt handles the initial understanding and decomposition of the strategy.
markdown
# Prompt 1: Strategy Analysis and Stage Identification
You are an expert technical analyst specializing in candlestick chart patterns.
## Step 1: Strategy Analysis
1. Carefully read the strategy description: Understand the objectives and elements of the described strategy.
2. Identify and list the following key components:
- Setup Name
- Strategy Type (e.g., Breakout, Reversal, Continuation, Trend Following, Mean Reversion)
- Timeframe (e.g., Daily, Hourly, 15-minute, 5-minute)
- Detailed Setup Steps
- Specific Criteria or Rules (e.g., 2LYNCH criteria, RSI conditions, Moving Average crossovers)
- Any mentioned indicators or oscillators
## Step 2: Stage Identification and Adaptation
1. Break down the strategy into distinct stages (e.g., trend formation, consolidation, entry signal, exit signal).
2. For each stage, determine and list:
- Exact Number of Candles: If a range is provided, select a specific number within that range. If not specified, use a reasonable number based on the strategy type.
- Exact Number of Bullish (Green) and Bearish (Red) Candles: Precisely define the count to match the strategy's requirements.
- Specific Candle Characteristics: (e.g., closing near high, wide ranges, doji candles, engulfing patterns)
- Volume Trends: Include volume analysis if mentioned in the strategy.
- Price Action: Describe any specific price movements required (e.g., higher highs, lower lows, sideways movement).
- Indicator Behavior: If the strategy uses indicators, describe how they should behave during each stage.
## Execution
Given this strategy description: {description}
Perform Step 1 and Step 2 meticulously, providing detailed outputs for each step.
Prompt 2: Data Generation and JSON Compilation
This prompt takes the analysis from Prompt 1 and generates the candlestick data along with JSON compilation and data validation.
markdown
# Prompt 2: Data Generation and JSON Compilation
You have completed the Strategy Analysis and Stage Identification. Now, proceed with Data Generation and JSON Compilation.
## Step 3: Data Generation
1. Start Date: [Use the provided start date or default to current year, e.g., 2024-01-01]
2. For each stage identified:
- Generate the exact number of candles as determined.
- Ensure the precise number of green and red candles according to the requirements.
- For each candle:
+ Date: Increment sequentially from the start date.
+ Open: [Previous Close]
+ High: [Max(Open, Close) + Random(0.1% to 2% of price)]
+ Low: [Min(Open, Close) - Random(0.1% to 2% of price)]
+ Close:
- For bearish candles (red): [Open - Random(0.1% to 2% of price]
- For bullish candles (green): [Open + Random(0.1% to 2% of price]
+ Volume: [Base Volume + Random(-20% to +20%)] adjusted according to the volume trend requirements of each stage.
- Adjust price movements to reflect the strategy's requirements (e.g., breakouts, pullbacks, consolidations).
- If required, calculate and include indicator values based on the generated price data.
## Step 4: JSON Compilation
1. Structure the data in the exact JSON format below:
```json
{
"candlestickData": [
{
"date": "YYYY-MM-DD",
"open": 100.00,
"high": 102.00,
"low": 99.50,
"close": 101.80,
"volume": 1000000
}
// ... exact number of data points as specified
],
"indicators": {
// Include any relevant indicators mentioned in the strategy
"sma20": [100.5, 101.2, ...],
"rsi": [45, 52, ...]
}
}
Step 6: Data Validation
Review the generated data to ensure:
Correct Total Number of Candles
Accurate Number of Bullish and Bearish Candles per Stage
Logical Price Movements: (e.g., High > Open, Close > Low)
Volume Trends Align with Strategy Requirements
Indicator Values (if included) are Consistent with Price Movements
The Data Accurately Reflects All Aspects of the Given Strategy
Execution
Using the output from Prompt 1, perform Step 3, Step 4, and Step 6. Provide the generated JSON data and highlight any validation points.
code
### **Prompt 3: Data Correction and Final Explanation**
This final prompt focuses on validating, correcting any discrepancies in the data, and providing a comprehensive explanation.
```markdown
# Prompt 3: Data Correction and Final Explanation
You have generated the initial candlestick data and performed data validation. Now, proceed with Data Correction (if necessary) and provide a Detailed Explanation.
## Step 7: Data Correction
1. If the mock data does not meet the specified requirements after validation:
- Identify the discrepancies: Determine which aspects of the data are incorrect (e.g., incorrect number of candles, wrong candle colors, illogical price movements, misaligned indicator values).
- Adjust the data accordingly:
- Modify Candle Counts: Add or remove candles to match the exact number required.
- Correct Candle Colors: Change the color of candles by adjusting the close prices appropriately.
- Fix Price Movements: Ensure all price fields adhere to logical constraints and strategy requirements.
- Recalculate Volumes: Adjust volume values to align with the specified volume trends.
- Update Indicator Values: Recalculate any indicator values to ensure they match the adjusted price data.
- Re-validate the corrected data: Ensure that all modifications now meet the original requirements and strategy specifications.
- Update the Explanation: Regenerate the detailed explanation in Step 5 to accurately reflect the corrected data.
## Step 5: Detailed Explanation Consistent with Final Data
1. Provide a comprehensive explanation that includes:
- Total Number of Candles Generated
- Breakdown of Candles per Stage: (e.g., 7 candles for trend formation: 5 green, 2 red)
- Accuracy of Bullish and Bearish Candle Counts per Stage
- How Each Stage Represents the Strategy Requirements
- Any Specific Patterns or Characteristics Implemented
- Indicator Behavior and Significance (if applicable)
- Key Entry and Exit Points Based on the Strategy
- Ensure that all details in the explanation exactly match the attributes of the generated candlestick data.
## Step 8: Final Data Confirmation
1. Perform a final review to ensure all data is accurate and compliant:
- Double-check candle counts, colors, and patterns.
- Ensure all price movements are logical and align with the strategy.
- Verify volume trends align with strategy requirements.
- Confirm indicator values (if present) are correct and meaningful.
- Ensure the JSON structure is correct and free of errors.
- Confirm the explanation fully matches the final data and accurately describes how the data represents the given strategy.
## Execution
Using the output from Prompt 2, perform Step 7 and Step 5. Correct any data discrepancies and provide the final JSON data along with a detailed explanation of how the data aligns with the given strategy.
2. LangChain Sequential Chain Implementation
Below is the Python code using LangChain to create a sequential chain with the three prompts defined above. This implementation ensures that the output from each prompt seamlessly feeds into the next, culminating in the generation of accurate mock candlestick data with a comprehensive explanation.
python
Step 6: Data Validation
Review the generated data to ensure:
Correct Total Number of Candles
Accurate Number of Bullish and Bearish Candles per Stage
Logical Price Movements: (e.g., High > Open, Close > Low)
Volume Trends Align with Strategy Requirements
Indicator Values (if included) are Consistent with Price Movements
The Data Accurately Reflects All Aspects of the Given Strategy
Execution
Using the output from Prompt 1, perform Step 3, Step 4, and Step 6. Provide the generated JSON data and highlight any validation points.
"""
)
You have generated the initial candlestick data and performed data validation. Now, proceed with Data Correction (if necessary) and provide a Detailed Explanation.
Step 7: Data Correction
If the mock data does not meet the specified requirements after validation:
Identify the discrepancies: Determine which aspects of the data are incorrect (e.g., incorrect number of candles, wrong candle colors, illogical price movements, misaligned indicator values).
Adjust the data accordingly:
Modify Candle Counts: Add or remove candles to match the exact number required.
Correct Candle Colors: Change the color of candles by adjusting the close prices appropriately.
Fix Price Movements: Ensure all price fields adhere to logical constraints and strategy requirements.
Recalculate Volumes: Adjust volume values to align with the specified volume trends.
Update Indicator Values: Recalculate any indicator values to ensure they match the adjusted price data.
Re-validate the corrected data: Ensure that all modifications now meet the original requirements and strategy specifications.
Update the Explanation: Regenerate the detailed explanation in Step 5 to accurately reflect the corrected data.
Step 5: Detailed Explanation Consistent with Final Data
Provide a comprehensive explanation that includes:
Total Number of Candles Generated
Breakdown of Candles per Stage: (e.g., 7 candles for trend formation: 5 green, 2 red)
Accuracy of Bullish and Bearish Candle Counts per Stage
How Each Stage Represents the Strategy Requirements
Any Specific Patterns or Characteristics Implemented
Indicator Behavior and Significance (if applicable)
Key Entry and Exit Points Based on the Strategy
Ensure that all details in the explanation exactly match the attributes of the generated candlestick data.
Step 8: Final Data Confirmation
Perform a final review to ensure all data is accurate and compliant:
Double-check candle counts, colors, and patterns.
Ensure all price movements are logical and align with the strategy.
Verify volume trends align with strategy requirements.
Confirm indicator values (if present) are correct and meaningful.
Ensure the JSON structure is correct and free of errors.
Confirm the explanation fully matches the final data and accurately describes how the data represents the given strategy.
Execution
Using the output from Prompt 2, perform Step 7 and Step 5. Correct any data discrepancies and provide the final JSON data along with a detailed explanation of how the data aligns with the given strategy.
"""
)
Parse and print the final JSON data and explanation
try:
parsed_output = json.loads(final_result)
print(json.dumps(parsed_output, indent=2))
except json.JSONDecodeError:
print("Final output is not in JSON format:")
print(final_result)
code
## **3. Explanation of the Code**
1. **Initialization:**
- **Language Model:** We initialize the language model using OpenAI's GPT-4. You can replace `OpenAI` with `ChatAnthropic` or any other preferred LLM based on your requirements.
2. **Prompt Definitions:**
- **Prompt 1:** Handles the initial strategy analysis and stage identification based on the provided strategy description.
- **Prompt 2:** Takes the analysis from Prompt 1 to generate candlestick data, compile it into JSON, and perform initial data validation.
- **Prompt 3:** Focuses on correcting any discrepancies in the generated data and provides a detailed explanation aligning with the strategy.
3. **LLMChain Configuration:**
- Each prompt is associated with an `LLMChain` that feeds into the next. The `output_key` ensures that the output from one chain is correctly passed as input to the subsequent chain.
4. **SequentialChain Assembly:**
- The `SequentialChain` combines the three chains into a single workflow, taking the `description` as input and producing the `final_output`.
5. **Execution:**
- An example `strategy_description` is provided to demonstrate how the chain operates.
- The `sequential_chain.run` method processes the description through all three prompts sequentially.
- The final output is attempted to be parsed as JSON. If successful, it's pretty-printed; otherwise, the raw output is displayed.
## **4. Sample Output**
Upon running the above code with the provided `strategy_description`, you can expect an output similar to the following (note that actual values may vary based on the LLM's generation):
```json
{
"candlestickData": [
{
"date": "2024-01-01",
"open": 100.00,
"high": 102.00,
"low": 99.50,
"close": 101.80,
"volume": 980000
},
// ... additional candlestick data
],
"indicators": {
"sma20": [100.5, 101.2, ...],
"rsi": [28, 31, ...]
},
"explanation": "Total Number of Candles Generated: 10\nBreakdown of Candles per Stage:\n- Trend Formation: 5 candles (3 bearish, 2 bullish)\n- Bullish Engulfing Pattern: 2 candles (1 bearish, 1 bullish)\n- SMA20 Crossover Confirmation: 2 candles (both bullish)\n- RSI Confirmation: 1 candle (bearish)\n\nAccuracy of Bullish and Bearish Candle Counts per Stage: All stages have the precise number of bullish and bearish candles as per the strategy requirements.\n\nEach stage accurately represents the strategy requirements by first establishing a downtrend, followed by identifying the bullish engulfing pattern, confirming the breakout with SMA20 crossover, and ensuring RSI is below 30.\n\nSpecific patterns such as the bullish engulfing and the SMA20 crossover have been implemented correctly.\n\nIndicator Behavior: SMA20 is trending upwards during the crossover confirmation stage, and RSI remains below 30 before the engulfing pattern, indicating oversold conditions.\n\nKey Entry Point: Entry is signaled at the close of the bullish engulfing candle.\n\nKey Exit Point: Exit is suggested when the price closes below the SMA20 after a breakout."
}
Note: The above JSON is illustrative. The actual output will depend on the LLM's responses at each stage.
5. Final Notes
Error Handling: The code includes a try-except block to handle scenarios where the final output isn't in JSON format. This ensures that the user is informed if the output needs manual parsing or adjustment.
Customization: You can modify the strategy_description to fit different strategies, and the sequential chain will adapt accordingly to generate the relevant mock candlestick data.
Extensibility: This modular approach allows for easy addition of more steps or prompts if the data generation process becomes more complex in the future.
By following this structured approach, you can efficiently generate accurate and strategy-aligned mock candlestick data using LangChain's sequential chaining capabilities.
Not yet included in a published release.
from langchain import LLMChain, PromptTemplate, SequentialChain
from langchain.chat_models import OpenAI # or your preferred LLM
from langchain.schema import BaseOutputParser
import json
# Initialize the language model
llm = OpenAI(model_name="gpt-4", temperature=0)
# Define Prompt 1: Strategy Analysis and Stage Identification
prompt1_template = PromptTemplate(
input_variables=["description"],
template="""
# Prompt 1: Strategy Analysis and Stage Identification
You are an expert technical analyst specializing in candlestick chart patterns.
## Step 1: Strategy Analysis
1. Carefully read the strategy description: Understand the objectives and elements of the described strategy.
2. Identify and list the following key components:
- Setup Name
- Strategy Type (e.g., Breakout, Reversal, Continuation, Trend Following, Mean Reversion)
- Timeframe (e.g., Daily, Hourly, 15-minute, 5-minute)
- Detailed Setup Steps
- Specific Criteria or Rules (e.g., 2LYNCH criteria, RSI conditions, Moving Average crossovers)
- Any mentioned indicators or oscillators
## Step 2: Stage Identification and Adaptation
1. Break down the strategy into distinct stages (e.g., trend formation, consolidation, entry signal, exit signal).
2. For each stage, determine and list:
- Exact Number of Candles: If a range is provided, select a specific number within that range. If not specified, use a reasonable number based on the strategy type.
- Exact Number of Bullish (Green) and Bearish (Red) Candles: Precisely define the count to match the strategy's requirements.
- Specific Candle Characteristics: (e.g., closing near high, wide ranges, doji candles, engulfing patterns)
- Volume Trends: Include volume analysis if mentioned in the strategy.
- Price Action: Describe any specific price movements required (e.g., higher highs, lower lows, sideways movement).
- Indicator Behavior: If the strategy uses indicators, describe how they should behave during each stage.
## Execution
Given this strategy description: {description}
Perform Step 1 and Step 2 meticulously, providing detailed outputs for each step.
"""
)
# Define the first chain
chain1 = LLMChain(
llm=llm,
prompt=prompt1_template,
output_key="analysis_output"
)
# Define Prompt 2: Data Generation and JSON Compilation
prompt2_template = PromptTemplate(
input_variables=["analysis_output"],
template="""
# Prompt 2: Data Generation and JSON Compilation
You have completed the Strategy Analysis and Stage Identification. Now, proceed with Data Generation and JSON Compilation.
## Step 3: Data Generation
1. Start Date: [Use the provided start date or default to current year, e.g., 2024-01-01]
2. For each stage identified:
- Generate the exact number of candles as determined.
- Ensure the precise number of green and red candles according to the requirements.
- For each candle:
+ Date: Increment sequentially from the start date.
+ Open: [Previous Close]
+ High: [Max(Open, Close) + Random(0.1% to 2% of price)]
+ Low: [Min(Open, Close) - Random(0.1% to 2% of price)]
+ Close:
- For bearish candles (red): [Open - Random(0.1% to 2% of price)]
- For bullish candles (green): [Open + Random(0.1% to 2% of price)]
+ Volume: [Base Volume + Random(-20% to +20%)] adjusted according to the volume trend requirements of each stage.
- Adjust price movements to reflect the strategy's requirements (e.g., breakouts, pullbacks, consolidations).
- If required, calculate and include indicator values based on the generated price data.
## Step 4: JSON Compilation
1. Structure the data in the exact JSON format below:
```json
{
"candlestickData": [
{
"date": "YYYY-MM-DD",
"open": 100.00,
"high": 102.00,
"low": 99.50,
"close": 101.80,
"volume": 1000000
}
// ... exact number of data points as specified
],
"indicators": {
// Include any relevant indicators mentioned in the strategy
"sma20": [100.5, 101.2, ...],
"rsi": [45, 52, ...]
}
}