forked from cyberjunky/AI---LLMs-For-Automated-Trading
-
Notifications
You must be signed in to change notification settings - Fork 3
/
llm-trading.py
159 lines (123 loc) · 11.1 KB
/
llm-trading.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
'''
RBI - Research, backtest, implement
ai 1 - generate strategy
ai 2 - create backtest instructions
ai 3 - create backtest code
ai 4 - debug & improve backtest code
ai 5 - builds out the algo
ideas
- loop in different ideas to give it a starting place
TODO
- create another ai to check their work and add in missing funcs
- loop strat ideas some
- input more indepth strats in the list
[] output strategies into a pdf
- maybe i can work on my prompt to get a better code output... or jsut ask for the function
- how do we make sure that the full BT is sent
- maybe append the second half of code with other agent... maybe have an init agent, a next agent and a data agent
--paused here: outputs half the backtest. how do we get the 2nd half? multiple agents?
git: https://github.com/moondevonyt/AI---LLMs-For-Automated-Trading
'''
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
import langchainkeys as l
import time
# indicator_list = ["VDU and Pocket Pivot Strategy The VDU and Pocket Pivot strategy is a trading approach that combines the Volume Dry Up (VDU) pattern with the Pocket Pivot pattern. • Look for the VDU candle and the Pocket Pivot candle. The VDU candle should have low volume compared to prior candles, indicating low supply. •The Pocket Pivot candle should have a positive closing price on volume that exceeds any prior negative closing bar for at least 10 days, indicating strong demand. For entry: Volatility Contraction Pattern: Look for a tight consolidation pattern after a VDU. This indicates a final decision point for the stock and potential support level. Indecision Candles: Look for indecision candles or inside bars within the consolidation pattern. These candles suggest that the stock is gathering strength and preparing for a potential breakout. Increase in Volume: Look for a surge in volume as the stock breaks out from the consolidation pattern. This indicates increased demand and potential upward momentum. For Exits: Profit Targets: Set profit targets based on the size of the consolidation pattern or technical analysis levels such as resistance or previous highs. Stop Loss Levels: Place stop-loss orders below the low of the day or the second higher low, depending on risk tolerance and position size.",
# "ZRC Trading System This strategy also incorporates the use of support and resistance levels. It aims to identify potential trade opportunities based on the signals generated by the indicators and the confirmation from price action. Indicators Used: RSI (Relative Strength Index) with a period of 10 CCI (Commodity Channel Index) with a period of 21 MACD (Moving Average Convergence Divergence) with parameters 12, 29, and 9 Entry Guidelines: • Place a vertical line at the 1:00 ET candle on the chart. • Enter a trade when the RSI signal line crosses above/below the 50 level and the CCI signal line crosses above/below the zero level. • Confirm the entry using the MACD Histogram indicator aligning with the signal or moving towards it. Exit Guidelines: • If the entry candle closes in the opposite direction, consider it a failed trade and exit. • Exit the trade if the next candle breaks the range of the previous candle in the opposite direction. • Consider letting the trade run if the previous day's range is broken and the MACD indicates strength. Exit when an exit signal is generated on MACD. For ranging days, use the high/low zones (red dotted lines) in RSI and CCI. If the signal line touches or crosses the extreme high/low zone and returns back, exit the trade. If it only happens on one indicator, use the range of the candle for an exit or wait for the second indicator to confirm the exit. • Exit for a minimum loss and maximum profit by considering factors such as the opposite direction candle, MACD exits, strength of the move, and signal line crosses and touches at key levels.",
# "5 min scalping with ema channel and MACD is a trend following strategy based on two EMAs filtered by MACD. Time Frame 5 min. Indicators 21 EMA, close with level 100 and -100. 5 EMA, close. Slow MACD as filter ( 18. 34, 12). Trading rules 5 min scalping with ema channel and MACD Buy  5 EMA crosses above 21 EMA.  Slow MACD histogram above zero level.  Re-enter when the candle came back above the 21 EMA.  Exit with predetermind profit target tha depends by pairs 8-15 pips, or at the + 100 band.  Initial Stop loss 8 -10 pips below the entry bar.  After 8 pips in gain move stop loss at the breakeven. Sell  5 EMA crosses below 21 EMA.  Slow MACD histogram below zero level.  Re-enter when the candle came back below the 21 EMA.  Exit with predetermind profit target tha depends by pairs 8-15 pips, or at the - 100 band.  Initial Stop loss 8-10 pips below the entry bar.  Do not enter if the bar closes above 100 line or below -100 lines.  After 8 pips in gain move stop loss at the breakeven.",
# 'Indicators Used: • 24 EMA (yellow, dotted) • 12 EMA (violet) • 24 EMA (cornflower blue) • 72 EMA (khaki) Entry Guidelines: • Pullback (conservative) entry: On the hourly chart, when all the 8, 12, and 24 EMAs are above (long) or below (short) the 72 EMA, and price has pulled back to the 12 or 24 EMA, enter for a specific pip target or hold based on the traders judgment of the trend strength. • Initial (aggressive) entry: On the 30-minute chart with the same indicators, when price has moved with authority above or below the 72 EMA, the 8, 12, and 24 •EMAs are pointed in the direction of price, and preferably stacked in a perfect order, enter for a specific pip target and hold if the thrust develops into a real trend. Exit Guidelines: • Profit-taking can be done based on the traders discretion, such as reaching a specific pip target, support and resistance areas, or pivot points. • Consider exiting longer-term trades when the 12 EMA crosses down below the 24 EMA. • Traders may also consider using trailing stops or adjusting stop-loss levels based on market conditions and trend strength.']
indicator_list = [
"RSI Trend Reversal Strategy: This strategy focuses on identifying trend reversals using the RSI (Relative Strength Index) indicator. It combines price action analysis with RSI signals to enter and exit trades. Entry Guidelines and Exit Guidelines are provided along with the specific RSI parameters and price action patterns to look for.",
"EMA Breakout Strategy: This strategy aims to capture breakouts using exponential moving averages (EMA). It identifies periods of consolidation and waits for a breakout above or below the EMAs to enter trades. The specific EMA periods and breakout conditions are detailed in the strategy. Entry Guidelines and Exit Guidelines provide clear instructions for this strategy.",
"MACD Divergence Strategy: This strategy leverages MACD (Moving Average Convergence Divergence) divergences to identify potential trend reversals. It looks for divergences between MACD and price action to spot potential trade setups. Entry Guidelines and Exit Guidelines describe the specific conditions for identifying divergences and executing trades.",
"Fibonacci Retracement Strategy: This strategy utilizes Fibonacci retracement levels to identify potential support and resistance zones. It combines Fibonacci levels with other technical indicators to confirm trade entries and exits. The strategy provides instructions on how to draw and use Fibonacci retracement levels effectively.",
]
time_period = "365"
# Research trading strategies
llm_research = OpenAI(openai_api_key=l.open_ai_key, temperature=0)
research_template = """look at the recent market data for bitcoin and make a trading strategy for it. use {indicator} of your choice. over the last {time_period} days """
research_prompt = PromptTemplate(template=research_template, input_variables=["indicator", "time_period"])
trading_strategies = []
for indicator in indicator_list:
research_chain = LLMChain(prompt=research_prompt, llm=llm_research)
research_result = research_chain.run({"indicator": indicator, "time_period": time_period})
trading_strategies.append(research_result)
# Print the generated trading strategies
for strategy in trading_strategies:
print(strategy)
print('')
print('Done thinking of strategies... moving on to instructions for backtests...')
print('')
time.sleep(5)
#### STRATEGY INSTRUCTIONS LLM ########
# Generate step-by-step instructions for each trading strategy
llm_instructions = OpenAI(openai_api_key=l.open_ai_key, temperature=0)
instructions_template = """
Based on the generated trading strategy:
- Determine the entry condition.
- Define the exit condition.
- Specify the market stay-out condition.
Trading Strategy:
{trading_strategy}
Entry Instructions:
...
Exit Instructions:
...
Market Stay-out Instructions:
...
"""
instructions_prompt = PromptTemplate(template=instructions_template, input_variables=["trading_strategy"])
instructions_chain = LLMChain(prompt=instructions_prompt, llm=llm_instructions)
print('')
# Generate instructions for each trading strategy
for strategy in trading_strategies:
instructions_result = instructions_chain.run({"trading_strategy": strategy})
step_by_step_outlines = [instructions_result]
print(step_by_step_outlines)
# Print the step-by-step outline
for outline in step_by_step_outlines:
print(outline)
print('Finished generating instructions for all strategies...')
#### BACKTESTING CODE LLM ####
# ...
# Generate backtesting code for each trading strategy
llm_backtesting = OpenAI(openai_api_key=l.open_ai_key, temperature=0)
backtesting_template = """
Please code a backtest for this trading strategy with backtesting.py then output the full backtesting code. this is the strategy: {trading_strategy} , use the following code as a template, then give me back the full code:
# Import necessary libraries
from backtesting import Backtest, Strategy
from backtesting.lib import crossover
import talib
import pandas as pd
import numpy as np
# Define the trading strategy class
class MyStrategy(Strategy):
def init(self):
# Add any initialization code here for the strategy
def next(self):
# Add the trading logic here for the strategy
# Load the BTC-USD data
data = pd.read_csv()
data.columns = [column.capitalize() for column in data.columns]
data = data.dropna()
# Instantiate the backtest with your strategy
bt = Backtest(data, MyStrategy, cash=100000, commission=0.005)
# Run the backtest and get the results
stats = bt.run()
# Generate trade statistics, plots, etc., and output the results
stats.print()
bt.plot()
output the full code to me
"""
backtesting_prompt = PromptTemplate(template=backtesting_template, input_variables=["trading_strategy"])
backtesting_chain = LLMChain(prompt=backtesting_prompt, llm=llm_backtesting)
print('Generating backtesting code...')
# Generate backtesting code for each trading strategy
for strategy in trading_strategies:
backtesting_result = backtesting_chain.run({"trading_strategy": strategy})
backtesting_code = backtesting_result
# Print the generated backtesting code
print(backtesting_code)
# Print completion message
print("\nAll done with the research, step-by-step instructions, and backtesting code!")