/
newserver.go
419 lines (378 loc) · 12.2 KB
/
newserver.go
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
// newserver.go
package main
import (
"fmt"
"log"
"strings"
"strconv"
"net"
"net/http"
"net/rpc"
"net/rpc/jsonrpc"
"io/ioutil"
"encoding/json"
)
/*
* Structure for the Arguments for Portfolio coming from the Client
*/
type Tid struct {
TradeId int
}
/*
* Structure for the Arguments for Trade coming from the Client
*/
type Args struct {
StockSymbolAndPercentage string
Budget float32
}
/*
* Structure to send back the portfolio result to the client
*/
type PortfolioResult struct {
Stocks string
CurrentMarketValue float32
UnvestedAmount float32
}
/*
* Structure to send back the trade result to the client
*/
type StockResult struct {
TradeId int
Stocks string
UnvestedAmount float32
}
/*
* Collection of trade results to store
*/
type StockResults struct {
Items []StockResult
}
/*
* Helper function to add Items to the trade results
*/
func (query *StockResults) AddItem(item *StockResult) []StockResult {
query.Items = append(query.Items, *item)
return query.Items
}
/*
* Global variable to store list of trade results to refer from the portfolio
*/
var Result StockResults
/*
* The JSON Structure of YAHOO Finance JSON API
*/
type StockData struct {
List struct{
Meta struct{
Count int `json:"count"`
Start int `json:"start"`
Type string `json:"type"`
} `json:"meta"`
Resources []struct{
Resource struct{
Classname string `json:"classname"`
Fields struct{
Name string `json:"name"`
Price string `json:"price"`
Symbol string `json:"symbol"`
Ts string `json:"ts"`
Type string `json:"type"`
UTCtime string `json:"utctime"`
Volume string `json:"volume"`
}`json:"fields"`
}`json:"resource"`
}`json:"resources"`
}`json:"list"`
}
/*
* Structure for storing each stock query items during trade
*/
type StockQueryItem struct {
StockName string
StockPercentage float64
StockBudget float64
}
/*
* Structure to store the information of stocks during trade
*/
type StockValue struct {
StockName string
StockValue float64
StockQuantity int
}
/*
* Collection of stocks during trading
*/
type StockValues struct {
Items []StockValue
}
/*
* Collection of query which the user has asked
*/
type StockQuery struct {
Items []StockQueryItem
}
/*
* Helper function to add Items to the []structure
*/
func (query *StockValues) AddItem(item StockValue) []StockValue {
query.Items = append(query.Items, item)
return query.Items
}
/*
* Structure for the stock RPC
*/
type Stocks struct{}
/*
* Helper function to add Items to the stockQuery structure
*/
func (query *StockQuery) AddItem(item StockQueryItem) []StockQueryItem {
query.Items = append(query.Items, item)
return query.Items
}
/*
* This gets called when RPC is invoked by Stocks.Portfolio
*/
func (t *Stocks) Portfolio(args *Tid, reply *PortfolioResult) error {
tradeid := args.TradeId
stockdata := &StockData{}
// Checking if the tradeId exists or not
if !check_tradeid_exist(tradeid) {
return nil
}
stocks := Result.Items[tradeid - 1].Stocks // See logic of generating tradeid
symbols := get_portfolio_symbols(stocks) // gets the symbols in terms of GOOGL,APPL
var err = json.Unmarshal(fetch_stock_yahoo(symbols), stockdata) // Fill in the structure of the YAHOO Finance Webservice API
if err != nil {
fmt.Errorf("Stocks can not be parsed from Yahoo API")
}
reply.Stocks = format_reply_portfoliostocks(stocks, stockdata)
reply.CurrentMarketValue = format_reply_currentmarketvalue(stocks, stockdata)
reply.UnvestedAmount = Result.Items[tradeid - 1].UnvestedAmount
// DEBUG Println
fmt.Println(Result.Items[tradeid - 1])
return nil
}
/*
* Function to format the reply of the PortFolio Stocks
* @params stocks: String which holds values like `GOOGL:0:$656.99,APPL:5:$96.11`
* @params stockdata: Stucture of the YAHOO API
* @return: Formatted string like 'GOOGL:0:+$656.99','APPL:5:+$96.11'
*/
func format_reply_portfoliostocks(stocks string, stockdata *StockData) string {
var value string
stock := strings.Split(stocks, ",")
for i :=0; i < len(stockdata.List.Resources); i++ {
StockName := stockdata.List.Resources[i].Resource.Fields.Symbol
for j :=0; j < len(stock); j++ {
if !strings.EqualFold(StockName, strings.Split(stock[j], ":")[0]) {
continue
}
CurrentMarketValue, _ := strconv.ParseFloat(stockdata.List.Resources[i].Resource.Fields.Price, 64)
StockPrice, _ := strconv.ParseFloat(strings.Split(stock[j], ":")[2], 64)
quantity:= strings.Split(stock[j], ":")[1]
value = value + ",'"+ StockName + ":" + quantity
if CurrentMarketValue > StockPrice {
value = value + ":+$"
} else if CurrentMarketValue < StockPrice {
value = value + ":-$"
} else {
value = value + ":$"
}
value = value + strconv.FormatFloat(CurrentMarketValue, 'f', 2, 64) + "'"
}
}
return strings.Trim(value, ",")
}
/*
* Function to format the reply of the PortFolio currentmarketvalue
* @params stocks: String which holds values like `GOOGL:0:$656.99,APPL:5:$96.11`
* @params stockdata: Stucture of the YAHOO API
* @return: Formatted float32 of the currentmarketvalue which is the sum of all the stock prices * the quantity
*/
func format_reply_currentmarketvalue(stocks string, stockdata *StockData) float32 {
var value float64
stock := strings.Split(stocks, ",")
for i :=0; i < len(stockdata.List.Resources); i++ {
StockName := stockdata.List.Resources[i].Resource.Fields.Symbol
for j :=0; j < len(stock); j++ {
if !strings.EqualFold(StockName, strings.Split(stock[j], ":")[0]) {
continue
}
Price, _ := strconv.ParseFloat(stockdata.List.Resources[i].Resource.Fields.Price, 64)
quantity, _ := strconv.ParseFloat(strings.Split(stock[j], ":")[1], 64)
value = value + (Price * quantity)
}
}
return float32(value)
}
/*
* Function to check if the tradeid exists or not in the portfolio call
* @params TradeId: Integer
* @rtype Boolean
*/
func check_tradeid_exist(TradeId int) bool {
for _, each := range Result.Items {
if each.TradeId == TradeId {
return true
}
}
return false
}
/*
* Function to get all the symbols of the stocks from a stocks
* @params stocks: String which holds values like `GOOGL:0:$656.99,APPL:5:$96.11`
* @rtype: returns GOOGL,APPL
*/
func get_portfolio_symbols(stocks string) string {
var symbols string
for _, each := range strings.Split(stocks, ",") {
symbol := strings.Split(each, ":")[0]
symbols = symbols + "," + symbol
}
return strings.Trim(symbols, ",")
}
/*
* This gets called when RPC is invoked by Stocks.Trade
*/
func (t *Stocks) Trade(args *Args, reply *StockResult) error {
fmt.Println(args)
fmt.Println(args.StockSymbolAndPercentage)
var StockQueries StockQuery
StockQueries = get_stock_query(strings.TrimSpace(args.StockSymbolAndPercentage), args.Budget)
stockdata := &StockData{}
stocksymbol := get_stock_symbol(StockQueries)
var err = json.Unmarshal(fetch_stock_yahoo(stocksymbol), stockdata)
if err != nil {
fmt.Errorf("Stocks can not be parsed from Yahoo API")
}
if stockdata.List.Meta.Count != len(StockQueries.Items) {
panic("One of the symbols are wrong, please try again")
}
stockvalues := compute_buy_stocks(StockQueries, *stockdata)
TradeId := len(Result.Items) + 1
reply.TradeId = TradeId
reply.Stocks = format_reply_stocks(stockvalues)
reply.UnvestedAmount = args.Budget - format_reply_amount(stockvalues)
Result.AddItem(reply)
fmt.Println(stockvalues.Items)
return nil
}
/*
* Function to return a string formatted for reply during stock trading
* @params StockValues
* @rtype: Returns string like `GOOGL:0:$656.99,APPL:5:$96.11`
*/
func format_reply_stocks(stockvalues StockValues) string {
var stocks string
for _, each := range stockvalues.Items {
stocks = stocks + each.StockName + ":" + strconv.Itoa(each.StockQuantity) + ":$" + strconv.FormatFloat(each.StockValue, 'f', 2, 64) + ","
}
return strings.Trim(stocks, ",")
}
/*
* Function to return the total amount invested in stock during trading
*/
func format_reply_amount(stockvalues StockValues) float32 {
var stocks float32
for _, each := range stockvalues.Items {
stocks = stocks + float32(each.StockValue)
}
return stocks
}
/*
* Function to compute the purchase of stock properly and store it in reply struc
*/
func compute_buy_stocks(StockQueries StockQuery, stockdata StockData) StockValues {
stockvalues := StockValues{[]StockValue{}}
for i := 0; i < len(StockQueries.Items); i++ {
StockName := StockQueries.Items[i].StockName
StockBudget := StockQueries.Items[i].StockBudget
for j :=0; j < len(stockdata.List.Resources); j++ {
Price, _ := strconv.ParseFloat(stockdata.List.Resources[i].Resource.Fields.Price, 64)
Symbol := stockdata.List.Resources[i].Resource.Fields.Symbol
if !strings.EqualFold(StockName, Symbol) {
continue
}
quantity := int(StockBudget/Price)
stockvalue := StockValue{StockName: Symbol, StockValue: Price, StockQuantity: quantity}
stockvalues.AddItem(stockvalue)
break;
}
}
return stockvalues
}
/*
* Function to fetch the stock pricing and details from Yahoo
* @params: StockSymbol - a string of the required Stock symbols, ex: GOOGL,APPL
* @return: []byte of the JSON RAW Response
*/
func fetch_stock_yahoo(StockSymbol string) []byte {
url := fmt.Sprintf("http://finance.yahoo.com/webservice/v1/symbols/%s/quote?format=json", StockSymbol)
// Do a GET Request to get the JSON formatted file from the server
req, err := http.Get(url)
if err != nil {
panic(err.Error())
}
// Get the BODY of the Request
body, err := ioutil.ReadAll(req.Body)
if err != nil {
panic(err.Error())
}
defer req.Body.Close() // Wait for the request to be completed [Blocking Call]
return body
}
/*
* Function to return all the STOCK symbol in this manner APPL,GOOGL
*/
func get_stock_symbol(stockquery StockQuery) string {
var all_symbols, symbol string
for _, each := range stockquery.Items {
symbol = each.StockName
all_symbols = all_symbols + symbol + ","
}
return strings.Trim(all_symbols,",")
}
/*
* Function to compute/verify and to aggregate all the symbols of the companies
*/
func get_stock_query(StockSymbolAndPercentage string, Budget float32) StockQuery {
var Percent, _StockBudget float64
var _Percent string
items := []StockQueryItem{}
query := StockQuery{items}
for _, each := range strings.Split(StockSymbolAndPercentage, ",") {
var Name = strings.Split(each, ":")[0]
if len(Name) < 2 {
continue
}
_Percent = strings.Split(each, ":")[1]
Percent, _ = strconv.ParseFloat(strings.Trim(_Percent, "%"), 64)
_StockBudget = float64((Percent * float64(Budget)) / 100)
item := StockQueryItem{StockName: Name, StockPercentage: Percent, StockBudget: _StockBudget}
query.AddItem(item)
}
return query
}
/*
* Main Function
*/
func main() {
Result = StockResults{[]StockResult{}} //Initialize the Global Variable
stocks := new(Stocks)
server := rpc.NewServer()
server.Register(stocks)
server.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)
listener, e := net.Listen("tcp", ":1234")
if e != nil {
log.Fatal("listen error:", e)
}
for {
if conn, err := listener.Accept(); err != nil {
log.Fatal("accept error: " + err.Error())
} else {
log.Printf("new connection established\n")
go server.ServeCodec(jsonrpc.NewServerCodec(conn)) //Keep Serving the server
}
}
}