-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstock_exchange_agent.py
365 lines (301 loc) · 13.5 KB
/
stock_exchange_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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# coding=utf-8
# !/usr/bin/env python
import json
import random
import string
import sys
import time
import uuid
import spade
from spade.ACLMessage import ACLMessage
from spade.Agent import Agent
from spade.Behaviour import Behaviour, ACLTemplate
import helper
class StockExchange(Agent):
class OpenStockExchange(Behaviour):
ip = None
msg = None
brokers = 0
brokers_total = 5
round = 0
evaluation = 0
stocks = []
def initialize(self):
self.ip = self.getName().split(" ")[0]
self.stocks = self.stock_generate()
helper.print_yellow("Generated %d stocks...\n" % len(self.stocks))
for stock in self.stocks:
print 'ID: %d' % stock['id']
print 'Name: %s' % stock['name']
print 'Price per stock: %d' % stock['price']
helper.print_yellow("============================================")
# Sends signal that stock exchange is opened for business
def open_stock_exchange(self):
msg_sign_in_to_stock_exchange = json.dumps(
{
'uuid': str(uuid.uuid4()),
'request_type': 'stock_open',
'data': None,
'origin': self.ip
}
)
self.broadcast_message(msg_sign_in_to_stock_exchange)
# Sends stock exchange state to brokers
def send_stock_exchange_report(self, origin_ip):
msg_sign_in_to_stock_exchange = json.dumps(
{
'uuid': str(uuid.uuid4()),
'request_type': 'stock_report_data',
'data': json.dumps(self.stocks),
'origin': self.ip
}
)
self.send_message(msg_sign_in_to_stock_exchange, origin_ip)
# Sends stock exchange state to brokers
def broadcast_stock_exchange_report(self):
msg_sign_in_to_stock_exchange = json.dumps(
{
'uuid': str(uuid.uuid4()),
'request_type': 'stock_report_data',
'data': json.dumps(self.stocks),
'origin': self.ip
}
)
self.broadcast_message(msg_sign_in_to_stock_exchange)
# Informs owner that his stock has changed price
def inform_owner_change(self, stock, origin_ip):
msg_owner_share_change = json.dumps(
{
'uuid': str(uuid.uuid4()),
'id': stock['id'],
'price': stock['price'],
'request_type': 'stock_share_change',
'data': json.dumps(stock),
'origin': self.ip
}
)
self.send_message(msg_owner_share_change, origin_ip)
def send_buy_confirmation(self, stock, origin_ip, price, amount, transaction):
msg_owner_buy_confirm = json.dumps(
{
'uuid': str(uuid.uuid4()),
'id': stock['id'],
'name': stock['name'],
'request_type': 'stock_bought',
'data': json.dumps(stock),
'origin': self.ip,
'price': price,
'amount': amount,
'transactionsId': transaction
}
)
self.send_message(msg_owner_buy_confirm, origin_ip)
def send_sell_confirmation(self, stock, origin_ip, price):
msg_owner_sell_confirm = json.dumps(
{
'uuid': str(uuid.uuid4()),
'request_type': 'stock_sold',
'data': json.dumps(stock),
'origin': self.ip,
'price': price,
'id': stock['id']
}
)
self.send_message(msg_owner_sell_confirm, origin_ip)
# Closes stock exchange, we have our winner
def send_close_stock_exchange(self):
msg_sign_in_to_stock_exchange = json.dumps(
{
'uuid': str(uuid.uuid4()),
'request_type': 'stock_close',
'data': None,
'origin': self.ip
}
)
self.broadcast_message(msg_sign_in_to_stock_exchange)
self.kill()
def _process(self):
self.msg = self._receive(True)
if self.msg:
request = json.loads(self.msg.content)
# Registering brokers to start stock exchange
if request['request_type'] == 'stock_sign_in':
self.brokers += 1
print "Broker %s signed in %d/%d" % (request['origin'], self.brokers, self.brokers_total)
# All brokers are registrated
if self.brokers == self.brokers_total:
self.initialize()
helper.print_green("Opening stock exchange...")
self.open_stock_exchange()
# Collect round status from agents
if request['request_type'] == 'evaluation_done':
self.evaluation += 1
print "Broker %s done with move round %d status: %d/%d" % (
request['origin'], self.round + 1, self.evaluation, self.brokers_total)
if self.evaluation == self.brokers_total:
# Round is over, send new report
self.round += 1
self.evaluation = 0
self.stock_speculate()
# Get stock report
if request['request_type'] == 'stock_report':
self.send_stock_exchange_report(request['origin'])
# Buy stock
if request['request_type'] == 'stock_buy':
self.buy_stock(request)
# Sell stock
if request['request_type'] == 'stock_sell':
self.sell_stock(request)
# Declare winner and close the stock exchange
if request['request_type'] == 'stock_win':
helper.print_green("Broker %s got rich. Closing stock exchange..." % request['origin'])
self.send_close_stock_exchange()
# Initialize stocks
@staticmethod
def stock_generate():
result = []
number_of_stocks = random.randint(5, 10)
for i in range(0, number_of_stocks):
price = random.randint(10, 1000)
result.append(
{
'id': i + 1,
'name': ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(3)),
'price': price,
'numberOfStocks': 10000,
'totalValue': 10000 * price,
'tendency': random.choice(
['up', 'down', 'stale', 'up fast', 'up slow', 'down fast', 'down slow']),
'owners': []
}
)
return result
# Method that allows trading certain amounts of stocks
def buy_stock(self, data):
price = data['stocksToBuy'] * data['data']['price']
self.stock_add_owner(data['data'], price, data['stocksToBuy'], data['origin'])
helper.print_green("Agent %s bought %d shares of:%s for %d$" % (
data['origin'], data['stocksToBuy'], data['data']['name'], price))
def sell_stock(self, data):
price = data['stocksToSell'] * data['data']['price']
self.stock_remove_owner(data['data'], data['origin'])
print "%s sold %d shares %s for %d" % (data['origin'], data['stocksToSell'], data['data']['name'], price)
# Method that changes prices of generated stocks according with tendency
def stock_speculate(self):
for stock in self.stocks:
delta = 0
if stock['tendency'] == 'up':
# % of change
change_percentage = random.randint(1, 5) / float(100)
delta = stock['price'] * change_percentage
stock['price'] += delta
if stock['tendency'] == 'down':
# % of change
change_percentage = random.randint(1, 5) / float(100)
delta = stock['price'] * change_percentage
stock['price'] -= delta
if stock['tendency'] == 'stale':
# % of change
change_percentage = random.randint(1, 1) / float(100)
delta = stock['price'] * change_percentage
stock['price'] += delta
if stock['tendency'] == 'up slow':
# % of change
change_percentage = random.randint(5, 10) / float(100)
delta = stock['price'] * change_percentage
stock['price'] += delta
if stock['tendency'] == 'up fast':
# % of change
change_percentage = random.randint(10, 50) / float(100)
delta = stock['price'] * change_percentage
stock['price'] += delta
if stock['tendency'] == 'down slow':
# % of change
change_percentage = random.randint(10, 50) / float(100)
delta = stock['price'] * change_percentage
stock['price'] -= delta
if stock['tendency'] == 'down fast':
# % of change
change_percentage = random.randint(10, 50) / float(100)
delta = stock['price'] * change_percentage
stock['price'] -= delta
stock['totalValue'] = stock['numberOfStocks'] * stock['price']
self.increase_owner_shares(stock, delta)
helper.print_yellow("Starting new round of trading...")
time.sleep(0.5)
self.broadcast_stock_exchange_report()
def increase_owner_shares(self, stock, delta):
if len(stock) > 0:
for owner in stock['owners']:
owner['price'] = float(owner['price']) + float(delta)
self.inform_owner_change(stock, owner['ip'])
def stock_add_owner(self, stock, total_price, shares, ip):
for old_stock in self.stocks:
if old_stock['id'] == stock['id']:
old_stock['numberOfStocks'] -= shares
owners = old_stock['owners']
transaction = random.randint(1, 100000)
owners.append({
'id': stock['id'],
'name': stock['name'],
'transactionId': transaction,
'ip': ip,
'price': total_price,
'shares': shares,
})
old_stock['owners'] = owners
self.send_buy_confirmation(old_stock, ip, total_price, shares, transaction)
return transaction
def stock_remove_owner(self, stock, ip):
for old_stock in self.stocks:
if old_stock['id'] == stock['id']:
owners = old_stock['owners']
new = []
for o in owners:
if o['ip'] != ip:
new.append(o)
else:
# add to total shares count
old_stock['numberOfStocks'] += o['shares']
self.send_sell_confirmation(stock, ip, o['price'])
old_stock['owners'] = new
def broadcast_message(self, message):
for broker in brokers:
address = "%[email protected]" % broker
agent = spade.AID.aid(name=address, addresses=["xmpp://%s" % address])
self.msg = ACLMessage()
self.msg.setPerformative("inform")
self.msg.setOntology("stock")
self.msg.setLanguage("eng")
self.msg.addReceiver(agent)
self.msg.setContent(message)
self.myAgent.send(self.msg)
# print '\nMessage %s sent to %s' % (message, address)
def send_message(self, message, address):
agent = spade.AID.aid(name=address, addresses=["xmpp://%s" % address])
self.msg = ACLMessage()
self.msg.setPerformative("inform")
self.msg.setOntology("stock")
self.msg.setLanguage("eng")
self.msg.addReceiver(agent)
self.msg.setContent(message)
self.myAgent.send(self.msg)
# print '\nMessage %s sent to %s' % (message, address)
def _setup(self):
helper.print_green("\nVAS Stock exchange\t%s\tis up" % self.getAID().getAddresses())
template = ACLTemplate()
template.setOntology('stock')
behaviour = spade.Behaviour.MessageTemplate(template)
self.addBehaviour(self.OpenStockExchange(), behaviour)
brokers = [
'broker1',
'broker2',
'broker3',
'broker4',
'broker5',
]
if __name__ == "__main__":
try:
StockExchange('[email protected]', 'stock').start()
except (KeyboardInterrupt, SystemExit):
sys.exit()