Skip to content

Instantly share code, notes, and snippets.

@Kingkha
Created June 2, 2021 14:03
Show Gist options
  • Save Kingkha/0fef4306652e84e5d00812815e485f79 to your computer and use it in GitHub Desktop.
Save Kingkha/0fef4306652e84e5d00812815e485f79 to your computer and use it in GitHub Desktop.
import json
from datetime import datetime
import requests
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
# The ID and range of a sample spreadsheet.
INFO_SPREADSHEET_ID = '1moRVE-Hs7O4CEpFDHXqVPibTcS4EuxlcxBntrEHxfXs'
TICKER_RANGE_NAME = 'data!A2:A2000'
def main(prices):
"""Shows basic usage of the Sheets API.
Prints values from a sample spreadsheet.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('sheets', 'v4', credentials=creds)
# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=INFO_SPREADSHEET_ID,
range=TICKER_RANGE_NAME).execute()
values = result.get('values', [])
price_values = []
updated_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
if not values:
print('No data found.')
else:
for row in values:
price_values.append([prices[row[0]][0], prices[row[0]][1], prices[row[0]][2] , updated_time] if row[0] in prices else ['-', '-', '-', updated_time])
# update
data = [
{
'majorDimension': 'ROWS',
'range': 'data!B2:E{}'.format(len(price_values) + 1),
'values': price_values
}
]
body = {
'valueInputOption': 'RAW',
'data': data
}
result = service.spreadsheets().values().batchUpdate(
spreadsheetId=INFO_SPREADSHEET_ID, body=body).execute()
print('{0} cells updated.'.format(result.get('totalUpdatedCells')))
def get_price():
res = []
for exchange in ['hose', 'hnx', 'upcom']:
data = {
"operationName": "stockRealtimes",
"variables": {
"exchange": "{}".format(exchange)
},
"query": "query stockRealtimes($exchange: String) {\n stockRealtimes(exchange: $exchange) {\n stockNo\n ceiling\n floor\n refPrice\n stockSymbol\n stockType\n exchange\n matchedPrice\n matchedVolume\n priceChange\n priceChangePercent\n highest\n avgPrice\n lowest\n nmTotalTradedQty\n best1Bid\n best1BidVol\n best2Bid\n best2BidVol\n best3Bid\n best3BidVol\n best4Bid\n best4BidVol\n best5Bid\n best5BidVol\n best6Bid\n best6BidVol\n best7Bid\n best7BidVol\n best8Bid\n best8BidVol\n best9Bid\n best9BidVol\n best10Bid\n best10BidVol\n best1Offer\n best1OfferVol\n best2Offer\n best2OfferVol\n best3Offer\n best3OfferVol\n best4Offer\n best4OfferVol\n best5Offer\n best5OfferVol\n best6Offer\n best6OfferVol\n best7Offer\n best7OfferVol\n best8Offer\n best8OfferVol\n best9Offer\n best9OfferVol\n best10Offer\n best10OfferVol\n buyForeignQtty\n buyForeignValue\n sellForeignQtty\n sellForeignValue\n caStatus\n tradingStatus\n currentBidQty\n currentOfferQty\n remainForeignQtty\n session\n __typename\n }\n}\n"
}
response = requests.post(
url='https://iboard.ssi.com.vn/gateway/graphql',
data=json.dumps(data),
headers={'Content-type': 'application/json', 'Accept': 'text/plain'}
)
res.extend(json.loads(response.text)['data']['stockRealtimes'])
return res
if __name__ == '__main__':
prices = get_price()
res = {}
for price in prices:
res[price['stockSymbol']] = [price['matchedPrice'], price['priceChange'], price['matchedVolume']]
main(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment