-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
294 lines (239 loc) · 7.75 KB
/
main.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
import logging
import os
import sys
from logging import DEBUG
from os import curdir, getenv, path
from sys import exit
import requests as re
from flask import (Flask, abort, flash, jsonify, redirect, render_template,
request, session)
from flask_cors import CORS
from kiteconnect import KiteConnect
from kiteconnect.exceptions import NetworkException
from config import KITE_API_KEY, KITE_REQUEST_TOKEN, KITE_SECRET
from scaffold import *
import subprocess
app = Flask(__name__)
CORS(app)
NODE_DIR="/Users/ninjapython/Work/hack-project/gnosis-dev-kit/sampleDApp/"
app.logger.addHandler(logging.StreamHandler(sys.stdout))
app.logger.setLevel(logging.ERROR)
app.secret_key = 'secret'
log.setLevel(DEBUG)
# xe.com
xe_account_id = 'student926567212'
xe_api_key = 'a77skb1r13cnrhjg5j8953nuvj'
def initialize_kite():
"""
Helper function to initialize Kite.
"""
kite = KiteConnect(api_key=KITE_API_KEY)
try:
with open('token.ini', 'r') as the_file:
access_token = the_file.readline()
try:
kite.set_access_token(access_token)
except Exception as e:
log.error("Authentication failed {}".format(str(e)))
raise
except FileNotFoundError:
try:
user = kite.request_access_token(
request_token=KITE_REQUEST_TOKEN, secret=KITE_SECRET)
except Exception as e:
log.error("{}".format(str(e)))
exit()
with open ('token.ini', 'w') as the_file:
the_file.write(user['access_token'])
try:
kite.set_access_token(user["access_token"])
except Exception as e:
log.error("Authentication failed {}".format(str(e)))
raise
return kite
@app.route('/')
def index():
return "Hello World"
@app.route('/place_order/<symbol>/<tr_type>/', methods=['GET'])
def place_order(symbol, tr_type):
if request.method == 'GET':
kite_instance = initialize_kite()
log.info(request.args)
log.info(kite_instance)
# Place an order
try:
order_id = kite_instance.order_place(tradingsymbol=symbol,
exchange="NSE",
transaction_type=tr_type,
quantity=1,
order_type="MARKET",
product="CNC")
log.info("Order placed. ID is {}".format(order_id))
except NetworkException:
log.debug("SUCCESS")
return jsonify({"result":200})
return order_id
@app.route('/convert_rr/<val>/<_from>/<_to>', methods=['GET'])
def convert_real_to_real(val, _from, _to):
if request.method == 'GET':
params = (
('from', _from),
('to', _to),
('amount', val),
)
resp = re.get('https://xecdapi.xe.com/v1/convert_from.json/', params=params, auth=(xe_account_id, xe_api_key))
result = {"result": resp.json()["to"][0]["mid"], 'status': 'OK'}
return jsonify(result)
@app.route('/create_market/<stock>/')
def create_market(stock):
if request.method == 'GET':
file_contents = """
const Gnosis = require('@gnosis.pm/gnosisjs');
const Web3 = require('web3');
const resolutionDate = new Date();
resolutionDate.setDate(resolutionDate.getDate() + 1);
const options = {
ethereum: new Web3(new Web3.providers.HttpProvider('http://localhost:8545')).currentProvider,
ipfs: {
host: 'localhost',
port: 5001,
protocol: 'http'
}
};
const eventDescription = {
title: '"""+stock+"""',
description: 'Should we buy or sell this stock?',
resolutionDate: resolutionDate.toISOString(),
outcomes: ['Yes', 'No'],
};
let gnosisInstance;
let ipfsHash;
let oracle;
let categoricalEvent;
let market;
Gnosis.create(options)
.then(result => {
gnosisInstance = result;
console.info('[GnosisJS] > connection established');
console.info("[GnosisJS] > Creating event description...");
gnosisInstance.publishEventDescription(eventDescription)
.then(result => {
ipfsHash = result;
console.info("[GnosisJS] > Event description hash: " + ipfsHash);
console.info("[GnosisJS] > Creating Centralized Oracle...");
gnosisInstance.createCentralizedOracle(ipfsHash)
.then(result => {
oracle = result;
console.info("[GnosisJS] > Centralized Oracle was created");
console.info("[GnosisJS] > Creating Categorical Event...");
gnosisInstance.createCategoricalEvent({
collateralToken: gnosisInstance.etherToken,
oracle,
// Note the outcomeCount must match the length of the outcomes array published on IPFS
outcomeCount: 2,
})
.then(result => {
categoricalEvent = result;
console.info("[GnosisJS] > Categorical event was created");
console.info("[GnosisJS] > Creating market...");
// console.info(gnosisInstance);
gnosisInstance.createMarket({
event: categoricalEvent,
marketMaker: gnosisInstance.lmsrMarketMaker,
marketFactory: gnosisInstance.standardMarketFactory,
fee: 50000
})
.then(response => {
market = response;
console.info("[GnosisJS] > Market was created");
Promise.all([
gnosisInstance.etherToken.deposit({ value: 4e18 }),
gnosisInstance.etherToken.approve(market.address, 4e18),
market.fund(4e18)
])
.then(values => {
console.info("[GnosisJS] > All done!");
})
.catch(error => {
console.warn(error);
});
})
.catch(error => {
console.warn(error);
});
})
.catch(error => {
console.warn(error);
});
})
.catch(error => {
console.warn(error);
});
})
.catch(error => {
console.warn(error);
});
})
.catch(error => {
console.warn('Make sure that Gnosis Development kit is up and running');
});
"""
with open(NODE_DIR+"temp.js", "w") as f:
f.write(file_contents)
subprocess.run(["node", "temp.js"], check=True, cwd=NODE_DIR)
return jsonify({"result":200})
@app.route('/compute_order/<symbol>')
def compute_order(symbol):
if request.method == 'GET':
data = re.get("http://0.0.0.0:8000/api/markets/").json()
for i in data['results']:
if (i['event']['oracle']['eventDescription']['title']) == symbol and i['stage']==1:
if (i['marginalPrices'][0] == i['marginalPrices'][1]):
return jsonify({"result":420})
elif (i['marginalPrices'][0] > i['marginalPrices'][1]):
tr_type = "BUY"
else:
tr_type = "SELL"
place_order(symbol,tr_type)
return jsonify({"result":tr_type})
@app.route('/check_predictions/')
def check_predictions():
data = re.get("http://0.0.0.0:8000/api/markets/").json()
log.info(data)
if request.method == 'GET':
for i in data['results']:
if i['stage'] == 1:
compute_order(i['event']['oracle']['eventDescription']['title'])
return jsonify({"result":200})
@app.route('/convert_er/<val>/<_to>')
def convert_eth_to_real(val, _to):
if request.method == 'GET':
resp = re.get('https://api.coinbase.com/v2/exchange-rates?currency=ETH').json()
# rate of 1 eth to _from currency
rate = float(resp["data"]['rates'][_to])
value = float(val) * rate
result = {"result": str(value), 'status': 'OK'}
return str(value)
@app.route('/convert_re/<val>/<_from>')
def convert_real_to_eth(val, _from):
if request.method == 'GET':
resp = re.get('https://api.coinbase.com/v2/exchange-rates?currency=ETH').json()
# rate of 1 eth to _from currency
rate = float(resp["data"]['rates'][_from])
value = float(val) * (1/rate)
result = {"result": str(value), 'status': 'OK'}
return jsonify(result)
@app.route('/nav/<fa>/<fl>/<os>')
def calculate_nav(fa, fl, os):
if request.method == 'GET':
nav = (float(fa) - float(fl)) / float(os)
return str(nav)
@app.errorhandler(404)
def page_not_found(error):
return "Not Found"
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5050))
#if not check_for_tokens():
# exit()
#initialize_kite()
app.run(host='0.0.0.0', port=port, debug=True)