-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrade_agent.py
144 lines (125 loc) · 5.98 KB
/
trade_agent.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
import requests
import urllib
import time
import datetime
from decimal import Decimal, getcontext, localcontext
import os
import json
from walls import Walls, format_number
from notification import notification
from db import Wall, OrderExecution
from monitoring_client import MonitoringClient
monitoring_client = MonitoringClient()
def print_trade_wall_status(wall, unit_price, proposed_action, history):
holdings = wall.calculate_holdings(history)
potential_cost = wall.potential_spend(history)[1]
print(f"=== Wall Status: {wall.pair} ===")
print(f"Market Price: {format_number(unit_price)} {wall.pair.split('/')[1]} per {wall.pair.split('/')[0]}")
print(f"Holdings: {format_number(holdings)} {wall.pair.split('/')[0]}")
print(f"Potential Cost: {format_number(potential_cost)} {wall.pair.split('/')[1]}")
if proposed_action:
action = 'Buy' if proposed_action[0] == 'buy' else 'Sell'
amount = format_number(proposed_action[1][1])
price = format_number(proposed_action[1][0])
print(f"Action: {action} {amount} at {price}/{wall.pair.split('/')[1]}")
else:
print("Action: None required")
if history:
print("Trade History:")
for action, (amount, total_cost) in history:
price_per_unit = total_cost / amount
verb = 'Bought' if action == 'buy' else 'Sold'
print(f" - {verb} {format_number(amount)} {wall.pair.split('/')[0]} at {format_number(price_per_unit)} {wall.pair.split('/')[1]} each for {format_number(total_cost)} {wall.pair.split('/')[1]} total")
else:
print("Trade History: None")
print("===")
def urlopen(url, timeout=60, max_retries=3, retry_delay=5):
retries = 0
while retries < max_retries:
try:
req = urllib.request.Request(url, headers={'User-Agent': "trade_agent"})
return urllib.request.urlopen(req, timeout=timeout)
except urllib.error.URLError as e:
print(f"Error occurred while making API request: {str(e)}")
retries += 1
if retries < max_retries:
print(f"Retrying in {retry_delay} seconds...")
time.sleep(retry_delay)
else:
raise
def coingecko_details(ids):
all_coins = []
cmc = "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=" + ids
return json.loads(urlopen(cmc, timeout=5).read().decode('utf-8'))
def flatten(xss):
return [x for xs in xss for x in xs]
def market_sell(db_wall, wall, amount, ask, lhs, rhs):
# Automation can happen here
notification("Trade Walls: sell %s estimated %.2e %s for %.2e %s" % (wall.pair, amount, lhs, ask*amount, rhs))
OrderExecution.create(wall=db_wall, amount=amount, total_price=(ask*amount), type='sell')
def market_buy(db_wall, wall, amount, bid, lhs, rhs):
# Automation can happen here
notification("Trade Walls: buy %s estimated %.2e %s for %.2e %s" % (wall.pair, amount, lhs, bid*amount, rhs))
OrderExecution.create(wall=db_wall, amount=amount, total_price=(bid*amount), type='buy')
def get_market_trade_history(db_wall):
return [(order.type, (Decimal(order.amount), Decimal(order.total_price))) for order in db_wall.executions]
def process_walls():
# Query all Wall objects
db_walls = Wall.select()
walls = []
# Print each Wall object
for wall in db_walls:
unit = wall.pair.split("/")[1]
token = wall.pair.split("/")[0]
print(f"{wall.pair} Bid Price: {wall.bid_price} {unit}, Ask price: {wall.ask_price} {unit}, Keep: {wall.keep} {token}, Quantity: {wall.quantity}")
walls.append(Walls(pair=wall.pair, bid_price=Decimal(wall.bid_price), ask_price=Decimal(wall.ask_price), keep=Decimal(wall.keep), quantities=[Decimal(wall.quantity)]))
total_potential = {}
for db_wall, wall in zip(db_walls, walls):
history = get_market_trade_history(db_wall)
base = wall.pair.split("/")[1]
if base not in total_potential:
total_potential[base] = 0
print("Potential spend for", ("%-12s" % wall.pair.split("/")[0]), format_number(wall.potential_spend(history=history)[1]), wall.pair.split("/")[1])
total_potential[base] += wall.potential_spend(history=history)[1]
for coin in total_potential.keys():
print("Total potential spend for ", coin, "=", format_number(total_potential[coin]))
coins = [wall.pair.split("/") for wall in walls]
coins = list(set(flatten(coins)))
details = coingecko_details(",".join(coins))
prices = {}
for coin in coins:
found = False
for d in details:
if d['id'] == coin:
prices[coin] = d['current_price']
found = True
break
if not found:
print("Can't find price for", coin)
ask_cache = {}
bid_cache = {}
for db_wall, wall in zip(db_walls, walls):
pair = wall.pair
lhs = pair.split("/")[0]
rhs = pair.split("/")[1]
lhs_usd_price, rhs_usd_price = prices[lhs], prices[rhs]
unit_price = Decimal(lhs_usd_price) / Decimal(rhs_usd_price)
history = get_market_trade_history(db_wall)
proposed_action = wall.step(Decimal(unit_price), history)
print_trade_wall_status(wall, unit_price, proposed_action, history)
if proposed_action is not None and proposed_action[0] == "buy":
market_buy(db_wall, wall, proposed_action[1][0], proposed_action[1][1], lhs, rhs)
if proposed_action is not None and proposed_action[0] == "sell":
market_sell(db_wall, wall, proposed_action[1][0], proposed_action[1][1], lhs, rhs)
def main():
while True:
try:
process_walls()
monitoring_client.record_success()
time.sleep(60) # Sleep for 60 seconds before the next iteration
except Exception as e:
monitoring_client.record_error(str(e))
print("An error occurred:", str(e))
time.sleep(60) # Sleep for 60 seconds before retrying
if __name__ == "__main__":
main()