forked from erhosen/gas-tinkoff-trades
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCode-api-v2-old.gs
220 lines (181 loc) · 7.17 KB
/
Code-api-v2-old.gs
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
const scriptProperties = PropertiesService.getScriptProperties()
const CACHE = CacheService.getScriptCache()
const EXPIRATION_DEFAULT = 15 // 15 seconds
const EXPIRATION_MAX = 21600 // 6 hours
// https://github.com/Tinkoff/investAPI/issues/7#issuecomment-1008327025
// https://tinkoff.github.io/investAPI/faq_custom_types/#java_1
const NANO_FACTOR = 1000000000
const API_TOKEN = scriptProperties.getProperty('API_TOKEN')
const tAPI = new TinkoffApp({
token: API_TOKEN, // укажите здесь свой токен
logging: true // Опционально - показывать в логах запросы и ответы
})
/* ####################################################################################################### */
function _apiRequest(cache, apiMethod, methodArgs = []) {
let statusCacheKey
if (cache.length) {
var [cacheKey, cacheExpireTime] = cache
statusCacheKey = 'status_' + cacheKey
if (CACHE.get(statusCacheKey) === 'ready') {
const cached = CACHE.get(cacheKey)
if (cached != null) {
Logger.log(`cacheKey ${cacheKey} found: ${cached}`)
return JSON.parse(cached)
}
}
Logger.log(`cacheKey ${cacheKey} NOT found`)
while (CACHE.get(statusCacheKey) === 'in-progress') {
Utilities.sleep(500);
}
Logger.log(`Setting ${statusCacheKey} to IN-PROGRESS`)
CACHE.put(statusCacheKey, 'in-progress')
}
const [v1='', v2='', v3=''] = methodArgs
const result = tAPI[apiMethod](v1, v2, v3)
if (cache.length) {
CACHE.put(cacheKey, JSON.stringify(result), cacheExpireTime)
Logger.log(`Setting ${statusCacheKey} to READY`)
CACHE.put(statusCacheKey, 'ready', cacheExpireTime)
}
return result
}
/* ####################################################################################################### */
function _getPositions(accountId) {
return _apiRequest([accountId + '_positions', EXPIRATION_DEFAULT], 'OperationsGetPositions', [accountId])
}
function _getAllBonds(instrumentStatus) {
return _apiRequest([], 'InstrumentsBonds', [instrumentStatus])
}
function _getAllEtfs(instrumentStatus) {
return _apiRequest([], 'InstrumentsEtfs', [instrumentStatus])
}
function _getAllShares(instrumentStatus) {
return _apiRequest([], 'InstrumentsShares', [instrumentStatus])
}
function _getBondByFigi(figi) {
const idType = 1
const classCode = ''
return _apiRequest([figi + '_bond', EXPIRATION_MAX], 'InstrumentsBondBy', [idType, classCode, figi]).instrument
}
function _getAllInstruments() {
const bonds = _getAllBonds(1).instruments
const etfs = _getAllEtfs(1).instruments
const shares = _getAllShares(1).instruments
const all = bonds.concat(etfs,shares)
return all
}
function _getFigiByTicker(ticker) {
const cacheKey = ticker + '_figi'
const cached = CACHE.get(cacheKey)
if (cached != null) {
Logger.log(`cacheKey ${cacheKey} found: ${cached}`)
return cached
}
Logger.log(`cacheKey ${cacheKey} NOT found`)
const {figi} = _getAllInstruments().find(x => x.ticker === ticker)
CACHE.put(cacheKey, figi)
Logger.log(ticker + ' figi: ' + figi)
return figi
}
function _getInstrumentByFigi(figi) {
const idType = 1
const classCode = ''
return _apiRequest([figi + '_instrument', EXPIRATION_MAX], 'InstrumentsGetInstrumentBy', [idType, classCode, figi]).instrument
}
function _getinstrumentTypeByFigi(figi) {
return _getInstrumentByFigi(figi).instrumentType
}
function _getMyFigiList() {
const cacheKey = 'figiList'
const cached = CACHE.get(cacheKey)
if (cached != null) {
Logger.log(`cacheKey ${cacheKey} found: ${cached}`)
return JSON.parse(cached)
}
Logger.log(`cacheKey ${cacheKey} NOT found`)
const accounts = JSON.parse(getAccounts())
let figiSet = new Set()
for (const account of accounts) {
const {securities} = _getPositions(account.id)
for (const security of securities) {
figiSet.add(security.figi)
}
}
let figiList = Array.from(figiSet);
CACHE.put(cacheKey, JSON.stringify(figiList), EXPIRATION_DEFAULT)
Logger.log('figilist: ' + figiList)
return figiList
}
function _getPricesByFigiList(figiList) {
return _apiRequest(['figiList_prices', EXPIRATION_DEFAULT], 'MarketDataGetLastPrices', [figiList]).lastPrices
}
function _quotationToNumber(units, nano) {
return units + nano / NANO_FACTOR
}
/* ####################################################################################################### */
function getAccounts() {
return JSON.stringify(_apiRequest(['accounts', EXPIRATION_MAX], 'UsersGetAccounts').accounts)
}
// dummy attribute is used for auto-refreshing the value each time the sheet is updating.
// see https://stackoverflow.com/a/27656313
function getAccountBalanceByCurrency(accountId, currency, dummy) {
currency = currency.toLowerCase()
// const positions = _getPositions(accountId).money
const positions = _getPositions(accountId)
const money = positions.money
let blocked = positions.blocked || []
let blocked_currency = blocked.find(x => x.currency === currency)
if (blocked === [] || blocked_currency === undefined) {
let dummy_object = new Object()
dummy_object.currency = currency
dummy_object.units = 0
dummy_object.nano = 0
blocked.push(dummy_object)
} else {
}
const units = (Number(money.find(x => x.currency === currency).units) || 0) + (Number(blocked.find(x => x.currency === currency).units) || 0)
const nano = (money.find(x => x.currency === currency).nano || 0) + (blocked.find(x => x.currency === currency).nano || 0)
const result = _quotationToNumber(units, nano)
Logger.log(`Available balance of ${currency} on ${accountId} account is: ${result}`)
return result
}
function getAccountBalanceByTicker(accountId, ticker, dummy) {
const figi = _getFigiByTicker(ticker)
const positions = _getPositions(accountId).securities
return balance = positions.find(x => x.figi === figi).balance
}
function getCurrencyByTicker(ticker, dummy) {
const figi = _getFigiByTicker(ticker)
return _getInstrumentByFigi(figi).currency.toUpperCase()
}
function getNameByTicker(ticker, dummy) {
const figi = _getFigiByTicker(ticker)
return _getInstrumentByFigi(figi).name
}
function getPriceByTicker(ticker, dummy) {
const figi = _getFigiByTicker(ticker)
const figiList = _getMyFigiList()
let lastPrices
if (figiList.includes(figi)) {
lastPrices = _getPricesByFigiList(figiList)
} else {
lastPrices = _apiRequest([ticker + '_price', EXPIRATION_DEFAULT], 'MarketDataGetLastPrices', [[figi]]).lastPrices
}
const price = lastPrices.find(x => x.figi === figi).price
const units = Number(price.units) || 0
const nano = price.nano || 0
let resultPrice = _quotationToNumber(units, nano)
// Bonds prices are counted differently
// https://tinkoff.github.io/investAPI/faq_marketdata/#_4
if (_getinstrumentTypeByFigi(figi) === 'bond') {
const nominal = Number(_getBondByFigi(figi).nominal.units)
resultPrice = resultPrice / 100 * nominal
}
Logger.log(ticker + ' price : ' + resultPrice)
return resultPrice
}
/* ####################################################################################################### */
function onEdit(e) {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
sheet.getRange('Z1').setValue(Math.random())
}