-
Notifications
You must be signed in to change notification settings - Fork 131
/
Copy pathautotrade.py
157 lines (133 loc) · 5.26 KB
/
autotrade.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
import os
from dotenv import load_dotenv
load_dotenv()
import pyupbit
import pandas as pd
import pandas_ta as ta
import json
from openai import OpenAI
import schedule
import time
# Setup
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
upbit = pyupbit.Upbit(os.getenv("UPBIT_ACCESS_KEY"), os.getenv("UPBIT_SECRET_KEY"))
def get_current_status():
orderbook = pyupbit.get_orderbook(ticker="KRW-BTC")
current_time = orderbook['timestamp']
btc_balance = 0
krw_balance = 0
btc_avg_buy_price = 0
balances = upbit.get_balances()
for b in balances:
if b['currency'] == "BTC":
btc_balance = b['balance']
btc_avg_buy_price = b['avg_buy_price']
if b['currency'] == "KRW":
krw_balance = b['balance']
current_status = {'current_time': current_time, 'orderbook': orderbook, 'btc_balance': btc_balance, 'krw_balance': krw_balance, 'btc_avg_buy_price': btc_avg_buy_price}
return json.dumps(current_status)
def fetch_and_prepare_data():
# Fetch data
df_daily = pyupbit.get_ohlcv("KRW-BTC", "day", count=30)
df_hourly = pyupbit.get_ohlcv("KRW-BTC", interval="minute60", count=24)
# Define a helper function to add indicators
def add_indicators(df):
# Moving Averages
df['SMA_10'] = ta.sma(df['close'], length=10)
df['EMA_10'] = ta.ema(df['close'], length=10)
# RSI
df['RSI_14'] = ta.rsi(df['close'], length=14)
# Stochastic Oscillator
stoch = ta.stoch(df['high'], df['low'], df['close'], k=14, d=3, smooth_k=3)
df = df.join(stoch)
# MACD
ema_fast = df['close'].ewm(span=12, adjust=False).mean()
ema_slow = df['close'].ewm(span=26, adjust=False).mean()
df['MACD'] = ema_fast - ema_slow
df['Signal_Line'] = df['MACD'].ewm(span=9, adjust=False).mean()
df['MACD_Histogram'] = df['MACD'] - df['Signal_Line']
# Bollinger Bands
df['Middle_Band'] = df['close'].rolling(window=20).mean()
# Calculate the standard deviation of closing prices over the last 20 days
std_dev = df['close'].rolling(window=20).std()
# Calculate the upper band (Middle Band + 2 * Standard Deviation)
df['Upper_Band'] = df['Middle_Band'] + (std_dev * 2)
# Calculate the lower band (Middle Band - 2 * Standard Deviation)
df['Lower_Band'] = df['Middle_Band'] - (std_dev * 2)
return df
# Add indicators to both dataframes
df_daily = add_indicators(df_daily)
df_hourly = add_indicators(df_hourly)
combined_df = pd.concat([df_daily, df_hourly], keys=['daily', 'hourly'])
combined_data = combined_df.to_json(orient='split')
# make combined data as string and print length
print(len(combined_data))
return json.dumps(combined_data)
def get_instructions(file_path):
try:
with open(file_path, "r", encoding="utf-8") as file:
instructions = file.read()
return instructions
except FileNotFoundError:
print("File not found.")
except Exception as e:
print("An error occurred while reading the file:", e)
def analyze_data_with_gpt4(data_json):
instructions_path = "instructions.md"
try:
instructions = get_instructions(instructions_path)
if not instructions:
print("No instructions found.")
return None
current_status = get_current_status()
response = client.chat.completions.create(
model="gpt-4-turbo-preview",
messages=[
{"role": "system", "content": instructions},
{"role": "user", "content": data_json},
{"role": "user", "content": current_status}
],
response_format={"type":"json_object"}
)
return response.choices[0].message.content
except Exception as e:
print(f"Error in analyzing data with GPT-4: {e}")
return None
def execute_buy():
print("Attempting to buy BTC...")
try:
krw = upbit.get_balance("KRW")
if krw > 5000:
result = upbit.buy_market_order("KRW-BTC", krw*0.9995)
print("Buy order successful:", result)
except Exception as e:
print(f"Failed to execute buy order: {e}")
def execute_sell():
print("Attempting to sell BTC...")
try:
btc = upbit.get_balance("BTC")
current_price = pyupbit.get_orderbook(ticker="KRW-BTC")['orderbook_units'][0]["ask_price"]
if current_price*btc > 5000:
result = upbit.sell_market_order("KRW-BTC", btc)
print("Sell order successful:", result)
except Exception as e:
print(f"Failed to execute sell order: {e}")
def make_decision_and_execute():
print("Making decision and executing...")
data_json = fetch_and_prepare_data()
advice = analyze_data_with_gpt4(data_json)
try:
decision = json.loads(advice)
print(decision)
if decision.get('decision') == "buy":
execute_buy()
elif decision.get('decision') == "sell":
execute_sell()
except Exception as e:
print(f"Failed to parse the advice as JSON: {e}")
if __name__ == "__main__":
make_decision_and_execute()
schedule.every().hour.at(":01").do(make_decision_and_execute)
while True:
schedule.run_pending()
time.sleep(1)