Giter VIP home page Giter VIP logo

shioaji's Introduction

Shioaji

shioaji-logosinopac-logo

Shioaji is sinopac provide the most pythonic api for trading the taiwan and global financial market. You can use your favorite Python packages such as numpy, scipy, pandas, pytorch or tensorflow to build your own trading model with intergrated the shioaji api on cross platform.

We are in early-release alpha. Expect some adventures and rough edges.

Installation

Binaries

simple using pip to install

pip install shioaji

Docker Image

simple run with interactive mode in docker

docker run -it shioaji:latest

Getting Started

from datetime import date, timedelta
import pandas as pd

Just import Our api like other popular python library to get start

import shioaji as sj

Use Shioaji object to setup setting and login

sj.Shioaji?
Init signature: sj.Shioaji(backend='http', simulation=True, proxies={}, currency='NTD')
Init docstring:
initialize Shioaji to start trading
backend: {http, socket}
    use http or socket as backend currently only support http, socket backend coming soon.
    - http: will support taiwan stock, future, and global stock
    - socket: will support taiwan stock, future and global future
simulation: bool
    - False: to trading on real market (just use your Sinopac account to start trading)
    - True: become simulation account(need to contract as to open simulation account)
proxies: dict
    specific the proxies of your https
    {'https': 'your-proxy-url'}
currency: {NTX, USX, NTD, USD, HKD, EUR, JPY, GBP}
    set the default currency for display 
api = sj.Shioaji(backend='http', simulation=False)
api.login?
Signature: api.login(person_id, passwd)
Docstring:
login to trading server
person_id: str
    Same as your eleader, ileader login id(usually your person ID)
passwd: str
    the password of your eleader login password(not ca password)
person_id = 'SCCEIEFAJA'
api.login(person_id=person_id, passwd='2222')
api.fut_account
{'account': '9104000',
 'username': '莊*芬',
 'datacount': 0,
 'accttype': 'F',
 'broker_id': 'F002000',
 'idno': 'SCCEIEFAJA'}

List all your account

api.list_accounts()
[{'account': '9104000',
  'username': '莊*芬',
  'datacount': 0,
  'accttype': 'F',
  'broker_id': 'F002000',
  'idno': 'SCCEIEFAJA'},
 {'account': '9802195',
  'username': '莊*芬',
  'datacount': 1,
  'accttype': 'S',
  'broker_id': '9A92',
  'idno': 'SCCEIEFAJA'},
 {'account': '09800762',
  'username': 'n*m',
  'datacount': 3,
  'accttype': 'H',
  'broker_id': '1300',
  'idno': 'QCCAHIFFDH'}]

Set your default trading account

api.set_default_account(api.fut_account)

Activate your cetifacation to start ordering

api.activate_ca?
Signature: api.activate_ca(ca_path, ca_passwd, person_id)
Docstring:
activate your ca for trading
ca_path: str
    the path of your ca, support both absloutely and relatively path, use same ca with eleader
ca_passwd: str
    password of your ca
person_id: str
    the ca belong which person ID
api.activate_ca(ca_path='../ca/Sinopac.pfx', ca_passwd='SCCEIEFAJA', person_id=person_id)
Ca Initial Done.
0

Making Order object to place order

api.Order?
Init signature: api.Order(product_id, product_type, opt_type, price, price_type, order_bs, order_type, octype, quantity, account)
Docstring: 
create order object
product_id: str 
    the product code
product_type: {'F', 'O'}
    - F: future
    - O: option
opt_type: {' ', 'C', 'P'}
    the option type Call or Put, leave blank if place future order
    - ' ': Future
    - 'C': Call
    - 'P': Put 
price: float or int
    order price
price_type: {LMT, MKT, MKP}
    - LMT: limit
    - MKT: market
    - MKP: market range
order_bs: {'B', 'S'}, 
    - 'B': buy
    - 'S': sell
order_type: {ROD, IOC, FOK}
    - ROD: Rest of Day
    - IOC: Immediate-or-Cancel
    - FOK: Fill-or-Kill
octype: {' ', '0', '1', '6'}, 
    - ' ': auto
    - '0': new position
    - '1': close position
    - '6': day trade
quantity: int

using tab to direct get all the Order properties with autocomplete

api.Order_props.
shioaji.backend.http.order.Order_props

using tab to direct get avaliable trading product with Contracts

api.Contracts.Future.TXF.TXF201903
Contract
    Code: TXFC9
    Detail:
        code: TXFC9
        deliverymonth: 201903
        poc: 
        eprice: 0.0
        ename: TXF
        category: TXF
        prod_kind: I
        csname: 台指期貨
        ostock: #001
        basic: 0001.000000
sample_order = api.Order(product_id=api.Contracts.Future.TXF.TXF201903.code, 
                         product_type=api.Order_props.product_type.Future, 
                         opt_type=api.Order_props.opt_type.Future,
                         price=9600,
                         price_type=api.Order_props.price_type.LMT,
                         order_bs=api.Order_props.order_bs.Buy,
                         order_type=api.Order_props.order_type.ROD,
                         octype=api.Order_props.octype.auto,
                         quantity=5,
                         account=api.fut_account,
                        )

just pass Order object to place_order fuction to place order then will get the Trade object return

trade = api.place_order(sample_order)
trade
Trade
    status: order_sent
        status_code: 
        errmsg: 
        product_id: TXFC9
        ordno: 
        seqno: 702330
        ord_bs: B
        price: 9600
        quantity: 5
        price_type: LMT
        account: {'account': '9104000', 'username': '莊*芬', 'datacount': 0, 'accttype': 'F', 'broker_id': 'F002000', 'idno': 'SCCEIEFAJA'}
        msg:                                                             
        trade_type: 01
        octype:  
        mttype: 0
        composit: 00
        ord_date: 20181119
        preord_date: 20181119
        ord_time: 15:45:48
        ord_type: ROD
        product_type: F
        opt_type:  

Update the trade object status to get the trade information

trade.update_status(api.client)
trade
Trade
    status: order_sent
        status_code: 0000
        errmsg: 
        product_id: TXFC9
        ordno: kY012
        seqno: 702330
        ord_bs: B
        price: 9600.0
        quantity: 5
        price_type: LMT
        account: {'account': '9104000', 'username': '莊*芬', 'datacount': 0, 'accttype': 'F', 'broker_id': 'F002000', 'idno': 'SCCEIEFAJA'}
        msg:                                                             
        trade_type: 01
        octype:  
        mttype: 0
        composit: 00
        ord_date: 20181119
        preord_date: 20181119
        ord_time: 15:45:48
        ord_type: ROD
        product_type: F
        opt_type:  

Modify price or qty of trade

trade = api.update_order(trade, price=9800, qty=1)
trade
Trade
    status: order_sent
        status_code: 0000
        errmsg: 
        product_id: TXFC9
        ordno: kY012
        seqno: 702330
        ord_bs: B
        price: 9800.0
        quantity: 5
        price_type: LMT
        account: {'account': '9104000', 'username': '莊*芬', 'datacount': 0, 'accttype': 'F', 'broker_id': 'F002000', 'idno': 'SCCEIEFAJA'}
        msg:                                                             
        trade_type: 01
        octype:  
        mttype: 0
        composit: 00
        ord_date: 20181119
        preord_date: 20181119
        ord_time: 15:45:48
        ord_type: ROD
        product_type: F
        opt_type:  

Account Margin

api.get_account_margin?
Signature: api.get_account_margin(currency='NTD', margin_type='1', account={})
Docstring:
query margin    currency: {NTX, USX, NTD, USD, HKD, EUR, JPY, GBP}
the margin calculate in which currency
    - NTX: 約當台幣
    - USX: 約當美金
    - NTD: 新台幣
    - USD: 美元
    - HKD: 港幣
    - EUR: 歐元
    - JPY: 日幣
    - GBP: 英鎊
margin_type: {'1', '2'}
    query margin type
    - 1 : 即時
    - 2 : 風險
account_margin = api.get_account_margin()
account_margin
AccountMargin
    Currency: NTD
    Account: F0020009104000
    Detail:
        OrderPSecurity: 207000.0
        ProfitAccCount: 207000.0
        FProfit: 0.0
        FMissConProfit: 0.0
        OMissConProfit: 0.0
        OColse: 0.0
        OMarketPrice: 0.0
        OTodayDiff: 0.0
        HandCharge: 0.0
        TradeTax: 0.0
        Security: 0.0
        StartSecurity: 0.0
        UpKeepSecurity: 0.0
        Statistics: 99999.0
        Flow: 999.0
        orderBid: 0.0
        orderAsk: 0.0
        Conclusionbid: 0.0
        Conclusionask: 0.0
        YesterdayBalance: 207000.0
        PayMoney: 0.0
        Equity: 207000.0
        Ogain: 0.0
        exrate: 1.0
        xgdamt: 0.0
        agtamt: 0.0
        YesterdayEquity: 207000.0
        Munet: 0.0
        Cashamt: 207000.0
        Bapamt: 0.0
        Sapamt: 0.0
        Adps: 0.0
        Adamt: 0.0
        Ybaln: 207000.0

directly pass our AccountMargin object to pandas to using your model

df_margin = pd.DataFrame([{**account_margin}])
df_margin
Adamt Adps Bapamt Cashamt Conclusionask Conclusionbid Equity FMissConProfit FProfit Flow ... TradeTax UpKeepSecurity Ybaln YesterdayBalance YesterdayEquity agtamt exrate orderAsk orderBid xgdamt
0 0.0 0.0 0.0 207000.0 0.0 0.0 207000.0 0.0 0.0 999.0 ... 0.0 0.0 207000.0 207000.0 207000.0 0.0 1.0 0.0 0.0 0.0

1 rows × 34 columns

Get Open Position

api.get_account_openposition?
Signature: api.get_account_openposition(product_type='0', query_type='0', account={})
Docstring:
query open position
product_type: {0, 1, 2, 3}
    filter product type of open position
    - 0: all
    - 1: future
    - 2: option
    - 3: usd base
query_type: {0, 1}
    query return with detail or summary
    - 0: detail
    - 1: summary
positions = api.get_account_openposition(query_type='1', account=api.fut_account)
positions
AccountOpenPosition
df_positions = pd.DataFrame(positions.data())
df_positions
Account Code CodeName ContractAverPrice Currency Date FlowProfitLoss MTAMT OTAMT OrderBS OrderNum OrderType RealPrice SettlePrice SettleProfitLoss StartSecurity UpKeepSecurity Volume paddingByte
0 FF0020009104000 TXFA9 台指期貨 01 9508.4137 NTD 00000000 4795201.620000 6438000.000000 8352000.000000 B 9784.0 9784.00 4795201.620000 8352000.000000 6438000.000000 87.000000
1 FF0020009104000 XJFF9 日圓期貨 06 80.0000 JPY 00000000 31400.000000 47000.000000 61000.000000 B 0.0 81.57 31400.000000 61000.000000 47000.000000 1.000000
2 FF0020009104000 TXO08000L8 台指選擇權 8000 C 12 1870.0000 NTD 00000000 -14000.000000 0.000000 0.000000 B 1730.0 1810.00 -6000.000000 0.000000 0.000000 2.000000
3 FF0020009104000 TXO09200L8 台指選擇權 9200 C 12 720.0000 NTD 00000000 11250.000000 147000.000000 162000.000000 S 645.0 660.00 9000.000000 162000.000000 147000.000000 3.000000
4 FF0020009104000 TXO09400X8 台指選擇權 9400 P 12 199.0000 NTD 00000000 21200.000000 57600.000000 65600.000000 S 93.0 93.00 21200.000000 65600.000000 57600.000000 4.000000
5 FF0020009104000 TXO10200L8 台指選擇權 10200 C 12 111.0000 NTD 00000000 33550.000000 125950.000000 147950.000000 S 50.0 50.00 33550.000000 147950.000000 125950.000000 11.000000

Get Settle ProfitLoss

api.get_account_settle_profitloss?
Signature: api.get_account_settle_profitloss(product_type='0', summary='Y', start_date='', end_date='', currency='', account={})
Docstring:
query settlement profit loss
product_type: {0, 1, 2}
    filter product type of open position
    - 0: all
    - 1: future
    - 2: option
summary: {Y, N}
    query return with detail or summary
    - Y: summary
    - N: detail
start_date: str
    the start date of query range format with %Y%m%d
    ex: 20180101
end_date: str
    the end date of query range format with %Y%m%d
    ex: 20180201
currency: {NTD, USD, HKD, EUR, CAD, BAS}
    the profit loss calculate in which currency
    - NTD: 新台幣
    - USD: 美元
    - HKD: 港幣
    - EUR: 歐元
    - CAD: 加幣 
    - BAS: 基幣
st_date = (date.today() - timedelta(days=60)).strftime('%Y%m%d')
settle_profitloss = api.get_account_settle_profitloss(summary='Y', start_date=st_date)
settle_profitloss
AccountSettleProfitLoss
df_profitloss = pd.DataFrame(settle_profitloss.data())
df_profitloss
account averagePrice code codeName currency floatProfitLoss handCharge ord_bs ord_type ordno ordno_b settleAvgPrc settleDate settleVolume tFlag tdate tradeProfitLoss tradeTax unVolume volume
0 F0020009104000 9900.0 TXFK8 台指期貨 11 NTD 460.000000 60.000000 S 00 kY002 kY003 9897.0 20181022 1.000000 1 20181022 600.000000 80.000000 0.000000 1.000000

Communication

Releases and Contributing

The Team

shioaji's People

Contributors

yvictor avatar

Stargazers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.