Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 18 additions & 6 deletions backend_api_python/app/routes/strategy.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import re
import traceback
import time
import os

from app.services.strategy import StrategyService
from app.services.strategy_compiler import StrategyCompiler
Expand Down Expand Up @@ -1989,6 +1990,7 @@ def ai_generate_strategy():
payload = request.get_json() or {}
lang = _request_lang()
prompt = payload.get('prompt', '')
language_prompt = f"The comments in the code should be in {payload.get('language', 'English')}"
if not prompt.strip():
return jsonify({'code': '', 'msg': _strategy_ai_text('prompt_empty', lang), 'params': None})

Expand Down Expand Up @@ -2185,7 +2187,7 @@ def ai_generate_strategy():

content = llm.call_llm_api(
messages=[
{"role": "system", "content": system_prompt},
{"role": "system", "content": system_prompt+language_prompt},
{"role": "user", "content": user_content},
],
model=llm.get_code_generation_model(),
Expand Down Expand Up @@ -2287,7 +2289,7 @@ def ai_generate_strategy():

content = llm.call_llm_api(
messages=[
{"role": "system", "content": system_prompt},
{"role": "system", "content": system_prompt+language_prompt},
{"role": "user", "content": user_content},
],
model=llm.get_code_generation_model(),
Expand All @@ -2313,8 +2315,16 @@ def ai_generate_strategy():
if not isinstance(updates, dict):
return jsonify({'code': '', 'params': None, 'msg': _strategy_ai_text('invalid_json_params', lang)})
return jsonify({'code': '', 'params': updates, 'msg': _strategy_ai_text('success', lang)})

system_prompt = """You are a quantitative trading strategy code generator.
try:
_backtest_framework_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'..', 'services', 'backtest.py'
)
with open(_backtest_framework_path, 'r', encoding='utf-8') as _f:
frame_context = _f.read()
except Exception:
frame_context = ""
system_prompt = f"""You are a quantitative trading strategy code generator.
Generate Python strategy code that follows this framework:
- def on_init(ctx): Initialize strategy parameters using ctx.param(name, default)
- def on_bar(ctx, bar): Core logic called on each K-line bar
Expand Down Expand Up @@ -2342,6 +2352,8 @@ def ai_generate_strategy():
- When sizing with ctx.equity * some_pct, keep some_pct as a 0–1 ratio.
- Template UI may show 0–100; only the Python default literals should be ratios.
- If user says "80% position", use ctx.param('position_pct', 0.8) and qty = ctx.equity * ctx.position_pct / price.
Strategy runtime framework context:
{frame_context}
"""

extra = ''
Expand All @@ -2362,7 +2374,7 @@ def ai_generate_strategy():

content = llm.call_llm_api(
messages=[
{"role": "system", "content": system_prompt},
{"role": "system", "content": system_prompt+language_prompt},
{"role": "user", "content": user_prompt},
],
model=llm.get_code_generation_model(),
Expand Down Expand Up @@ -2422,7 +2434,7 @@ def _repair_strategy_code_via_llm(bad_code: str, validation: dict) -> str:
)
repaired_content = llm.call_llm_api(
messages=[
{"role": "system", "content": system_prompt},
{"role": "system", "content": system_prompt+language_prompt},
{"role": "user", "content": repair_prompt},
],
model=llm.get_code_generation_model(),
Expand Down
11 changes: 8 additions & 3 deletions backend_api_python/app/services/backtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -729,6 +729,7 @@ def run_multi_timeframe(
mtf_requested=True,
mtf_active=True,
)
result['logs'] = signals.get('logs', [])
self._attach_actual_range_to_result(result, df_signal)
logger.info("Backtest result formatted successfully")
except Exception as e:
Expand Down Expand Up @@ -1773,6 +1774,7 @@ def _run_script_strategy(
ea['fillRule'] = 'next_bar_open'
result['executionAssumptions'] = ea
self._attach_actual_range_to_result(result, df)
result['logs'] = signals.get('logs', [])
return result

def run_code_strategy(
Expand Down Expand Up @@ -2007,7 +2009,7 @@ def run(
if df.empty:
raise ValueError("No candle data available in the backtest date range")


# 2. Execute indicator code to get signals (pass backtest params)
backtest_params = {
'leverage': leverage,
Expand Down Expand Up @@ -2444,8 +2446,10 @@ def _execute_script_strategy(self, code: str, df: pd.DataFrame, runtime: Optiona
volume=float(row.get('volume') or 0),
timestamp=row.get('time')
)
on_bar(ctx, bar)

try:
on_bar(ctx, bar)
except Exception as e:
ctx.log(traceback.format_exc())
for order in ctx._orders:
action = str(order.get('action') or '').lower()
intent = str(order.get('intent') or 'auto').lower()
Expand Down Expand Up @@ -2521,6 +2525,7 @@ def _execute_script_strategy(self, code: str, df: pd.DataFrame, runtime: Optiona
'close_short': close_short,
'add_long': add_long,
'add_short': add_short,
'logs': ctx.flush_logs(),
}
except Exception as e:
logger.error(f"Strategy script execution error: {e}")
Expand Down
Loading