Пример #1
0
    def ServerConnectLogin(self,
                           simulte: bool = False,
                           user: str = "chris",
                           ca: str = None) -> sj.Shioaji:
        self.api = sj.Shioaji(simulation=simulte)
        if simulte == False:
            idpwd_Dict = config(
                self.acct_file).getValueByConfigFile(key=self.key_login)
            self.id = idpwd_Dict.get(user.lower())[0]
            self.pwd = idpwd_Dict.get(user.lower())[1]
            env_name = "Actural"
        else:
            env_name = "Simulation"

        try:
            self.api.login(person_id=self.id,
                           passwd=self.pwd,
                           contracts_timeout=0)

            print(f"Login {env_name} Environment Success!!({self.id})")
            if env_name == "Actural" and ca:
                self.ca_acct = ca
                self.SetTreadAccount()
                self.InsertCAFile()
            return self.api
        except Exception as exc:
            return print(
                f"user: {self.id}, pwd: {self.pwd}, Login Fail!...{exc}")
Пример #2
0
    def connect(self, setting: dict):
        simulation = True if setting["環境"] == "模擬" else False
        self.write_log(f"使用永豐金證券 {setting['環境']} 平台")
        if self.api:
            self.api.logout()
        self.api = sj.Shioaji(simulation=simulation)
        userid = setting["身份證字號"]
        password = setting["密碼"]
        try:
            self.api.login(userid, password, contracts_cb=self.query_contract)
        except Exception as exc:
            self.write_log(f"登入失败. [{exc}]")
            return
        self.write_log(f"登入成功. [{userid}]")
        self.select_default_account(setting.get("預設現貨帳號", 0), setting.get("預設期貨帳號", 0))
        self.query_position()
        self.write_log("庫存部位查詢")

        if not simulation and setting["憑證檔案路徑"] != "":
            self.api.activate_ca(setting["憑證檔案路徑"], setting["憑證密碼"], setting["身份證字號"])
            self.write_log(f"{setting['身份證字號']} 憑證 已啟用.")
        self.api.quote.set_callback(self.cb_quote)
        self.api.set_order_callback(self.cb_pushorder)
        self.write_log("交易行情 - 連線成功")
        self.thread.start()
Пример #3
0
def main(person_id, passwd):
    api = sj.Shioaji()
    api.login(
        person_id=person_id,
        passwd=passwd,
        contracts_cb=lambda security_type: print(
            f"{repr(security_type)} fetch done."),
    )

    code_table = stock_code()
    code_table = code_table[code_table.industry != ""]
    today = datetime.now().strftime("%Y-%m-%d")
    up_date = api.Contracts.Futures.TXF[next(
        i for i in api.Contracts.Futures.TXF.keys())].update_date.replace(
            "/", "-")
    if today != up_date:
        print("off-day")
        return "off-day"
    files = glob.glob("{}/*.csv".format(
        os.path.join(os.getenv("HOME"), "shioaji_history")))
    exist_code = []
    for i in files:
        exist_code.append(i.split("/")[-1].split(".")[0])
    for i in code_table.code.values:
        try:
            kbars = api.kbars(api.Contracts.Stocks[str(i)],
                              start=today,
                              end=today)
            data_frame = pd.DataFrame({**kbars})
            data_frame.ts = pd.to_datetime(data_frame.ts)
            dates = []
            times = []
            for t_s in data_frame.ts.values:
                dates.append(str(t_s).split("T")[0])
                times.append(str(t_s).split("T")[1].split(".")[0])
            data_frame["Date"] = dates
            data_frame["Time"] = times
            data_frame = data_frame[[
                "Date", "Time", "Open", "High", "Low", "Close", "Volume"
            ]]
            file_path = os.path.join(os.getenv("HOME"), "shioaji_history",
                                     "{}.csv".format(i))
            if len(set([i]) - set(exist_code)) > 0:
                data_frame.to_csv(file_path, index=False)
            else:
                data_frame.to_csv(file_path,
                                  index=False,
                                  mode="a",
                                  header=False)
        except:
            print(i)
        time.sleep(10)
    api.logout()
Пример #4
0
    def __init__(self, event_engine):
        """Constructor"""
        super(SinopacGateway, self).__init__(event_engine, "Sinopac")

        self.subscribed = set()
        self.userid = ""
        self.password = ""
        self.ticks = {}
        self.code2contract = {}

        self.trades = set()

        self.count = 0
        self.interval = 20

        self.thread = Thread(target=self.query_data)
        self.query_funcs = [self.query_position, self.query_trade]
        self.api = sj.Shioaji()
Пример #5
0
 def __init__(self, parent=None):
     super(mainUI, self).__init__(parent)
     self.setupUi(self)
     self.trade = trade_widget(self)
     self.quote_report = quote_report_widget(self)
     self.trade.login = self.login
     self.grid_layout.addWidget(self.trade, 0, 0)
     self.grid_layout.addWidget(self.logo(), 0, 1)
     self.grid_layout.addWidget(self.quote_report, 1, 0, 1, 2)
     self.setWindowIcon(QtGui.QIcon("img/shioaji.png"))
     # event
     self.rtUpdate = RTUpdate()
     self.rtUpdate.caller.connect(self.rt_worker)
     self.rtUpdate.placeorder.connect(self.placeorder_worker)
     url = "https://service.sinotrade.com.tw/api/v1/codeList/stock_code"
     result = requests.get(url).json()
     stock = result["result"]
     self.stock_list = {item["code"]: item for item in stock}
     self.api = sj.Shioaji()
Пример #6
0
def main(person_id, passwd):
    api = sj.Shioaji()
    api.login(
        person_id=person_id,
        passwd=passwd,
        contracts_cb=lambda security_type: print(f"{repr(security_type)} fetch done."),
    )

    code_table = stock_code()
    code_table = code_table[code_table.industry != ""]
    today = datetime.now().strftime("%Y-%m-%d")
    for i in code_table.code.values:
        try:
            kbars = api.kbars(
                api.Contracts.Stocks[str(i)], start="2011-01-02", end=today
            )
            data_frame = pd.DataFrame({**kbars})
            data_frame.ts = pd.to_datetime(data_frame.ts)
            dates = []
            times = []
            for t_s in data_frame.ts.values:
                dates.append(str(t_s).split("T")[0])
                times.append(str(t_s).split("T")[1].split(".")[0])
            data_frame["Date"] = dates
            data_frame["Time"] = times
            data_frame = data_frame[
                ["Date", "Time", "Open", "High", "Low", "Close", "Volume"]
            ]
            file_path = os.path.join(
                os.getenv("HOME"), "shioaji_history", "{}.csv".format(i)
            )
            data_frame.to_csv(file_path, index=False)
        except:
            print(i)
        time.sleep(10)
    api.logout()
Пример #7
0
# 登入
import shioaji as sj
import datetime
import pandas as pd
import requests
api = sj.Shioaji()
accounts = api.login("身分證字號", "密碼")
ca = api.activate_ca(
    ca_path="C:/ekey/551/身分證字號/S/Sinopac.pfx",
    ca_passwd="身分證字號",
    person_id="身分證字號",
)

# 所有股票合約清單
AllStocks = api.Contracts.Stocks['TSE']
StockList = []

# 抓出代碼是4位的所有股票
for stock in AllStocks:
    if len(stock.code) == 4:
        #         print(stock)
        StockList.append(dict(stock))

stockDf = pd.DataFrame(StockList)  # 股票清單 Df
stockList = stockDf.code.tolist()  # 股票清單 List
stockDf.to_csv('台股股票清單.csv', encoding='utf-8')
print(stockDf.code)
Пример #8
0
 def setup_adapter(cls, *args, **kwargs):
     account = kwargs['account']
     adapter = sj.Shioaji()
     adapter.login(account['user'], account['password'])
     cls._adapter = adapter
Пример #9
0
 async def asyncSetUp(self):
     self.api = sj.Shioaji()
Пример #10
0
import shioaji as sj
import sys
import logging
import json
import base64
import logging_utility
from flask import Flask, request, jsonify, abort, make_response, g

APP = Flask(__name__)
logging_utility.basicConfig(
    filename='server.log',
    format='%(levelname)-8s %(asctime)s %(name)s:%(lineno)d| %(message)s',
    level=logging.INFO,
)

sj_api = sj.Shioaji(backend='http', simulation=False)


@APP.route('/accountinfo/<auth_token>', methods=['GET'])
def get_server_info(auth_token=None):

    if auth_token is None:
        logging.error('Missing Auth Token')
        abort(make_response('Missing Auth Token', 404))

    person_id, person_pass = auth_decode(auth_token)
    sj_api.login(person_id=person_id, passwd=person_pass)
    accounts = sj_api.list_accounts()

    account_list = []
    for acc in accounts: