-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbroker_agent.py
333 lines (266 loc) · 12.1 KB
/
broker_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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# coding=utf-8
# !/usr/bin/env python
import json
import threading
import time
import uuid
import spade
from spade.ACLMessage import ACLMessage
from spade.Agent import Agent, random
from spade.Behaviour import ACLTemplate, MessageTemplate, Behaviour
import helper
class BrokerAgent(Agent):
class Speculate(Behaviour):
win_threshold = float(100000)
ip = None
name = None
behaviour = None
msg = None
budget = None
myStocks = []
def initialize(self):
self.ip = self.getName().split(" ")[0]
self.name = self.getName().split(" ")[0].split("@")[0]
self.budget = float(random.randint(10000, 50000))
self.behaviour = random.choice(['risky', 'passive', 'cautious'])
print 'Agent %s\nBudget: %d$\nBehaviour: %s' % (self.ip, self.budget, self.behaviour)
def sign_in(self):
msg_sign_in_to_stock_exchange = json.dumps(
{
'uuid': str(uuid.uuid4()),
'request_type': 'stock_sign_in',
'data': None,
'origin': self.ip
}
)
stared_brokers.append(self.name)
self.send_message_to_stock(msg_sign_in_to_stock_exchange)
def evaluation_done(self):
msg_evaluation_done = json.dumps(
{
'uuid': str(uuid.uuid4()),
'request_type': 'evaluation_done',
'data': None,
'origin': self.ip
}
)
self.send_message_to_stock(msg_evaluation_done)
def ask_for_report(self):
msg_stock_exchange_report = json.dumps(
{
'uuid': str(uuid.uuid4()),
'request_type': 'stock_report',
'data': None,
'origin': self.ip
}
)
self.send_message_to_stock(msg_stock_exchange_report)
def buy_stock(self, stock, number_of_stocks_to_buy):
msg_stock_to_buy = json.dumps(
{
'uuid': str(uuid.uuid4()),
'request_type': 'stock_buy',
'data': stock,
'origin': self.ip,
'stocksToBuy': number_of_stocks_to_buy
}
)
self.send_message_to_stock(msg_stock_to_buy)
def sell_stock(self, stock, number_of_stocks_to_sell):
msg_stock_to_sell = json.dumps(
{
'uuid': str(uuid.uuid4()),
'request_type': 'stock_sell',
'data': stock,
'origin': self.ip,
'stocksToSell': number_of_stocks_to_sell
}
)
self.send_message_to_stock(msg_stock_to_sell)
def declare_win(self):
helper.print_green("\nAgent %s WON! Total sum: %d$" % (self.name, self.get_bank_account()))
msg_stock_win = json.dumps(
{
'uuid': str(uuid.uuid4()),
'request_type': 'stock_win',
'data': None,
'origin': self.ip
}
)
self.send_message_to_stock(msg_stock_win)
def _process(self):
if not (self.name in stared_brokers):
self.initialize()
self.sign_in()
self.msg = self._receive(True)
if self.msg:
request = json.loads(self.msg.content)
if request['request_type'] == 'stock_open':
self.ask_for_report()
if request['request_type'] == 'stock_report_data':
self.evaluate_stock_state(request['data'])
if request['request_type'] == 'stock_bought':
self.add_to_my_stocks(request)
if request['request_type'] == 'stock_sold':
self.remove_from_my_stocks(request)
if request['request_type'] == 'stock_share_change':
self.adjust_stock_prices(request)
if request['request_type'] == 'stock_close':
print 'Agent %s stopped trading, Won %d$' % (self.ip, self.budget)
self.kill()
def evaluate_stock_state(self, stock_data):
print '\nAgent %s evaluating stock data...' % self.name
took_action = False
if self.get_bank_account() >= self.win_threshold:
self.declare_win()
took_action = True
else:
stock_data = json.loads(stock_data)
for stock in stock_data:
# buy or wait or sell
take_action_odds = random.randint(1, 100)
action = random.choice(['buy', 'sell', 'stale'])
if self.behaviour == 'risky':
# takes action in 80 % of cases
if take_action_odds < 80:
# spend max 40% of my money on this stock and buy all stocks"
if action == 'buy' and not self.check_if_i_own_stock(stock):
self.buy_stock_evaluation(40, stock)
took_action = True
elif action == 'sell' and self.check_if_i_own_stock(stock):
self.sell_stock_evaluation(stock)
took_action = True
else:
took_action = False
elif self.behaviour == 'cautious':
# takes action in 40 % of cases
if take_action_odds < 40:
# spend max 10% of my money on stock and buy only growing or stable"
if action == 'buy' \
and not self.check_if_i_own_stock(stock) \
and (stock['tendency'] == 'up'
or stock['tendency'] == 'up fast'
or stock['tendency'] == 'up slow'
or stock['tendency'] == 'stale'):
self.buy_stock_evaluation(10, stock)
took_action = True
elif action == 'sell' \
and self.check_if_i_own_stock(stock) \
and (stock['tendency'] == 'down'
or stock['tendency'] == 'down fast'
or stock['tendency'] == 'down slow'):
self.sell_stock_evaluation(stock)
took_action = True
else:
took_action = False
elif self.behaviour == 'passive':
# takes action in 20 % of cases
if take_action_odds < 20:
# spend max 10% of my money on stock but rather pass buy all kinds of stocks"
if action == 'buy' and not self.check_if_i_own_stock(stock):
self.buy_stock_evaluation(40, stock)
took_action = True
elif action == 'sell' and self.check_if_i_own_stock(stock):
self.sell_stock_evaluation(stock)
took_action = True
else:
took_action = False
if not took_action:
print '\nAgent:%s\tNo action' % self.name
self.print_money_status()
self.evaluation_done()
def buy_stock_evaluation(self, max_percentage, stock):
if stock['numberOfStocks'] > 0:
budget_percentage = (random.randint(1, max_percentage)) / float(100)
money_to_spend = self.budget * budget_percentage
number_of_stocks = money_to_spend / stock['price']
if int(number_of_stocks) > 0:
print "\nAgent:%s\tTrying to buy %d of %s for %d$" % (
self.name, number_of_stocks, stock['name'], money_to_spend)
self.buy_stock(stock, int(number_of_stocks))
def sell_stock_evaluation(self, stock):
if stock['numberOfStocks'] > 0:
for s in self.myStocks:
if s['id'] == stock['id']:
print "\nAgent %s trying to sell %s" % (self.name, stock['name'])
self.sell_stock(stock, s['number'])
def check_if_i_own_stock(self, stock):
if len(self.myStocks) == 0:
return False
for myStock in self.myStocks:
if myStock['id'] == stock['id']:
return True
return False
def check_if_double_transaction(self, transaction_id):
for myStock in self.myStocks:
if myStock['transaction'] == transaction_id:
return True
return False
def add_to_my_stocks(self, data):
if not self.check_if_double_transaction(data['transactionsId']):
self.myStocks.append({
'id': data['id'],
'transaction': data['transactionsId'],
'ip': data['origin'],
'price': data['price'],
'pricePerShare': data['price'] / float(data['amount']),
'number': data['amount'],
})
self.budget -= float(data['price'])
helper.print_red("\nAgent %s bought %d stock of %s for %d$" % (
self.name, data['amount'], data['name'], data['price']))
def remove_from_my_stocks(self, data):
clean = []
for stock in self.myStocks:
if stock['id'] != data['id']:
clean.append(stock)
self.myStocks = clean
helper.print_green("Agent:%s\t+%d$ to budget" % (self.name, float(data['price'])))
self.budget += float(data['price'])
self.print_money_status()
def print_money_status(self):
helper.print_yellow("Agent:%s\tTotal:%d$" % (self.name, self.budget))
def get_bank_account(self):
total_money = float(self.budget)
if len(self.myStocks):
for stock in self.myStocks:
total_money += stock['number'] * stock['pricePerShare']
return total_money
def adjust_stock_prices(self, data):
for stock in self.myStocks:
if stock['id'] == data['id']:
stock['pricePerShare'] = data['price']
stock['price'] = stock['number'] * stock['pricePerShare']
def send_message_to_stock(self, content):
stock_address = '[email protected]'
agent = spade.AID.aid(name=stock_address, addresses=["xmpp://%s" % stock_address])
self.msg = ACLMessage()
self.msg.setPerformative("inform")
self.msg.setOntology("stock")
self.msg.setLanguage("eng")
self.msg.addReceiver(agent)
self.msg.setContent(content)
self.myAgent.send(self.msg)
# print '\nMessage %s sent to %s' % (content, stock_address)
def _setup(self):
stock_template = ACLTemplate()
stock_template.setOntology('stock')
mt = MessageTemplate(stock_template)
settings = self.Speculate()
self.addBehaviour(settings, mt)
brokers = [
'broker1',
'broker2',
'broker3',
'broker4',
'broker5',
]
stared_brokers = []
def start_broker(broker_name):
ip = '%[email protected]' % broker_name
agent = BrokerAgent(ip, broker_name)
agent.start()
if __name__ == '__main__':
for broker in brokers:
threading.Thread(target=start_broker, args=[broker]).start()
time.sleep(1.5)