這是一種基於Pyhton的API,使用Selenium,並要求從Trading212平台獲取信息,請注意,我本人或Trading212對與此API的使用有關的結果負責。
我將繼續從事這個項目,並將對任何反饋進行加註。
PIP安裝APIT212
要開始使用此API,您首先需要使用APIT212登錄到帳戶,然後您可以使用所有功能並創建自己的交易機器人或將其用於Trading212平台的Scarpe數據。
from apit212 import *
api = Apit212 ()
api . setup ( username = "[email protected]" , password = "pass******" , mode = "demo" )
from apit212 import *
api = Apit212 ()
api . setup ( username = "[email protected]" , password = "pass******" , mode = "live" )
最好設置一個ENV文件來保存敏感信息,例如您的用戶名或密碼。這是一個有用的鏈接.env
USER = [email protected]
PASS = password123
from dotenv import load_dotenv
from apit212 import *
import os
load_dotenv ( '.env' )
username : str = os . getenv ( 'USER' )
password : str = os . getenv ( 'PASS' )
api = Apit212 ()
api . setup ( username = "[email protected]" , password = "pass******" , mode = "demo" )
沒有正確的股票符號,此API是沒有用的,因此我有一個解決方案。
from apit212 import Tickers
ticker = Tickers ()
print ( ticker . fetch_symbols ( symbol = 'META' ))
print ( ticker . find_by_name ( full_name = 'tesla' ))
有很多數據需要閱讀,但是您追求的關鍵是tricker,這將返回Trading212平台使用的符號。
[{ ' ticker ' : ' FB ' , ' type ' : ' STOCK ' , ' currency ' : ' USD ' , ' shortName ' : ' META ' , ' fullName ' : ' Meta Platforms ' , ' description ' : ' Meta Platforms Inc ' , ' minTrade ' : 0.1, ' digitsPrecision ' : 2, ' exchangeId ' : 68, ' tradable ' : True, ' underlyingInstrumentTicker ' : ' FB_US_EQ ' , ' underlyingLeverageCoefficient ' : 1.0, ' dealerExclusions ' : [], ' maxOpenLong ' : 1121, ' leverage ' : ' 1:5 ' , ' insignificantDigits ' : 0, ' baseTicker ' : nan, ' expiryDate ' : nan, ' minTradeSizeCoefficient ' : 10.0, ' isin ' : ' US30303M1027 ' , ' countryOfOrigin ' : ' US ' , ' quantityPrecision ' : 1.0, ' priorityIndex ' : 25.0, ' maxTrade ' : nan, ' conditionalVisibility ' : nan, ' suspended ' : nan}]
[{ ' ticker ' : ' TSLA ' , ' type ' : ' STOCK ' , ' currency ' : ' USD ' , ' shortName ' : ' TSLA ' , ' fullName ' : ' Tesla ' , ' description ' : ' Tesla, Inc. ' , ' minTrade ' : 0.1, ' digitsPrecision ' : 2, ' exchangeId ' : 68, ' tradable ' : True, ' underlyingInstrumentTicker ' : ' TSLA_US_EQ ' , ' underlyingLeverageCoefficient ' : 1.0, ' dealerExclusions ' : [], ' maxOpenLong ' : 1405, ' leverage ' : ' 1:5 ' , ' insignificantDigits ' : 0, ' baseTicker ' : nan, ' expiryDate ' : nan, ' minTradeSizeCoefficient ' : 10.0, ' isin ' : ' US88160R1014 ' , ' countryOfOrigin ' : ' US ' , ' quantityPrecision ' : 1.0, ' priorityIndex ' : 100.0, ' maxTrade ' : nan, ' conditionalVisibility ' : nan, ' suspended ' : nan}]
from apit212 import Tickers
ticker = Tickers ()
meta = ticker . fetch_symbols ( symbol = 'META' )
print ( len ( meta ))
print ( meta [ 0 ][ 'ticker' ])
使用廣泛使用的股票程序查找股票通常會返回1個結果,但是在某些情況下,您可能會得到多個結果,因此可以檢查返回的字符串的好習慣。
1
FB
交易CFD簡單地稱為CFD類
from apit212 import *
api = Apit212 ()
api . setup ( username = "[email protected]" , password = "pass******" , mode = "demo" )
cfd = CFD ( cred = api )
交易權益簡單地稱呼股權類。
from apit212 import *
client = Apit212 ( username = "[email protected]" , password = "pass******" , mode = "live" )
equity = Equity ()
auth_validate函數將返回帳戶ID和交易類型。
validate = cfd . auth_validate ()
print ( validate )
{ ' id ' : ' *******-****-****-****-************ ' , ' accountId ' : ******** , ' customerId ' : ********* , ' tradingType ' : ' CFD ' , ' customerUuid ' : ' ********-****-****-****-************ ' , ' frontend ' : ' WC4 ' , ' readyToTrade ' : True, ' deviceUuid ' : ' ' }
get_account功能將返回您的帳戶詳細信息。
account = cfd . get_account ()
print ( account )
{ ' demoAccounts ' : [{ ' id ' : ******** , ' type ' : ' DEMO ' , ' tradingType ' : ' CFD ' , ' customerId ' : ******** ,
' createdDate ' : ' 2023-01-17T03:20:48.000+00:00 ' , ' status ' : ' ACTIVE ' , ' registerSource ' : ' WC4 ' ,
' currencyCode ' : ' GBP ' , ' readyToTrade ' : True}], ' liveAccounts ' : [{ ' id ' : ******** , ' type ' : ' LIVE ' ,
' tradingType ' : ' CFD ' , ' customerId ' : ******** , ' createdDate ' : ' 2023-01-17T03:20:32.000+00:00 ' ,
' status ' : ' PENDING_ACTIVATION ' , ' registerSource ' : ' WC4 ' , ' currencyCode ' : ' GBP ' , ' readyToTrade ' : False}]}
get_funds功能將返回帳戶資金。
funds = cfd . get_funds ()
print ( funds )
{ ' ******* ' : { ' accountId ' : ******** , ' tradingType ' : ' CFD ' , ' currency ' : ' GBP ' ,
' freeForWithdraw ' : 486.83, ' freeForCfdTransfer ' : 0, ' total ' : 486.83,
' lockedCash ' : { ' totalLockedCash ' : 0, ' lockedCash ' : []}}}
get_summary返回您帳戶的摘要。
summary = cfd . get_summary ()
print ( summary )
' open ' : { ' unfilteredCount ' : 1, ' items ' : [{ ' positionId ' : ' ********-****-****-****-************ ' , ' humanId ' : ' ******** ' ,
' created ' : ' 2023-07-03T18:17:46.563+03:00 ' , ' averagePrice ' : 192.25, ' averagePriceConverted ' : 150.73025341182984,
' currentPrice ' : 192.2, ' value ' : 1054.82, ' investment ' : 1055.11, ' code ' : ' AAPL ' , ' margin ' : 212.02, ' ppl ' : -0.28,
' quantity ' : 7, ' maxBuy ' : 9.0, ' maxSell ' : 7, ' maxOpenBuy ' : 2033.0, ' maxOpenSell ' : 2040.0, ' swap ' : -1.06, ' frontend ' : ' WC4 ' }]}
GET_COMPANIES返回可以在Trading212平台上進行交易的工具
companies = cfd . get_companies ()
print ( companies )
[{ ' ticker ' : ' SIGTl_EQ ' , ' isin ' : ' GB0008769993 ' }, { ' ticker ' : ' PDYPY_US_EQ ' , ' isin ' : ' US3440441026 ' }...]
GET_INSTROMENT_INFO將返回有關儀器的信息。
info = cfd . get_instruments_info ( instrument = "TSLA" )
print ( info )
{ ' code ' : ' TSLA ' , ' type ' : ' STOCK ' , ' margin ' : 0.2, ' shortPositionSwap ' : -0.07030593058663,
' longPositionSwap ' : -0.27928156941337, ' tsSwapCharges ' : ' 1970-01-01T23:00:00.000+02:00 ' ,
' marginPercent ' : ' 20 ' , ' leverage ' : ' 1:5 ' }
GET_ORDER_INFO GET
orderInfo = cfd . get_order_info ( instrument = "TSLA" , quamtity = 1.5 )
print ( orderInfo )
{ ' buyMargin ' : 40.18, ' sellMargin ' : 40.18, ' buySwap ' : -0.2, ' sellSwap ' : -0.05}
tickers = [ "TSLA" , "AAPL" ]
deviation = cfd . get_deviations ( instruments = tickers )
print ( deviation )
[{ ' request ' : { ' ticker ' : ' TSLA ' , ' useAskPrice ' : False}, ' response ' : { ' timestamp ' : 1694073610000, ' price ' : 250.68, ' period ' : ' d1 ' }}, { ' request ' : { ' ticker ' : ' AAPL ' , ' useAskPrice ' : False}, ' response ' : { ' timestamp ' : 1694073610000, ' price ' : 178.18, ' period ' : ' d1 ' }}]
get_position返回給定位置ID的信息,該ID可以從get_summary函數中刪除
position = cfd . get_position ( position_id = 274187113 )
print ( position )
[{ ' eventType ' : { ' action ' : ' opened ' , ' source ' : ' MARKET_ORDER ' },
' eventNumber ' : { ' name ' : ' MO3053019640 ' , ' id ' : ' 274187113 ' , ' frontend ' : ' WC4 ' }, ' time ' : ' 2023-08-02T22:42:54.000+03:00 ' ,
' direction ' : ' sell ' , ' quantity ' : 1.0, ' price ' : ' 105.29 ' , ' avgQuantity ' : 1.0, ' avgPrice ' : ' 105.2900 ' , ' modifiedDirection ' :
' sell ' }]
GET_ALL_RESULT功能將返回您所有交易結果的列表。您需要要求每個頁面。您可能還需要通過時區。
results = cfd . get_all_results ()
print ( results )
{ ' data ' : [{ ' direction ' : ' buy ' , ' code ' : ' AAPL ' , ' quantity ' : 0.1, ' orderNumber ' : { ' name ' : ' P************ ' , ' link ' : ' positionHistory/********-****-****-****-************ ' , ' id ' : ' ********-****-****-****-************ ' , ' frontend ' : ' WC4 ' }, ' price ' : ' 176.6700 ' , ' closePrice ' : ' 181.98 ' , ' result ' : ' 0.42 ' , ' eventNumber ' : { ' name ' : ' PO3062546222 ' , ' id ' : ' ********-****-****-****-************ ' }, ' eventType ' : ' closed ' , ' time ' : ' 2023-08-29T17:15:55.000+03:00 ' , ' openingTime ' : ' 2023-08-25T11:51:15.000+03:00 ' }, ...], ' nextPage ' : ' result?perPage=20&onlyFullyClosed=false&page=2 ' , ' currentPage ' : ' result?perPage=20&onlyFullyClosed=false&page=1 ' , ' totalSize ' : 133}
orderHist = cfd . get_order_hist ( page_number = 1 )
print ( orderHist )
{ ' data ' : [], ' currentPage ' : ' order?filter=all&perPage=20&from=2023-09-06T02:00:00.000+03:00&to=2023-09-08T01:59:59.173+03:00&page=1 ' , ' totalSize ' : 0}
positionHist = cfd . get_posistion_hist ( page_number = 1 )
print ( positionHist )
{ ' data ' : [], ' currentPage ' : ' position?perPage=20&from=2023-09-06T02:00:00.000+03:00&to=2023-09-08T01:59:59.173+03:00&page=1 ' , ' totalSize ' : 0}
Fast_price將儀器價格作為浮點部重新啟動。如果請求失敗,則沒有返回
price = cfd . fast_price ( instrument = "TSLA" )
print ( price )
253.49
Chart_data返回了帶有蠟燭日期OHLC(開放,高,低,關閉)的字典。默認設置為1分鐘。
charts = cfd . chart_data ( instrument = "TSLA" , period = "ONE_MINUTE" )
print ( charts )
[{ ' request ' : { ' ticker ' : ' TSLA ' , ' period ' : ' ONE_MINUTE ' , ' size ' : 500, ' useAskPrice ' : False}, ' response ' : { ' candles ' : [[1691152740000, 259.6, 259.97, 259.43, 259.49, 47], [1691152800000, 259.38, 259.94, 259.17, 259.56, 58], [1691152860000, 259.62, 260.34, 259.62, 260.19, 42]
Multi_price函數將返回所有通過的儀器的最後一個QOUT價格。
tickers = [ "TSLA" , "AAPL" , "GOOG" ]
multiprice = cfd . multi_price ( instruments = tickers )
print ( multiprice )
[{ ' ticker ' : ' TSLA ' , ' price ' : 251.34}, { ' ticker ' : ' AAPL ' , ' price ' : 181.96}, { ' ticker ' : ' GOOG ' , ' price ' : 135.18}]
Market_order功能提交市場訂單,需要該工具的當前價格。
targetPrice = cfd . fast_price ( instrument = "TSLA" )
marketOrder = cfd . market_order ( instrument = "TSLA" , target_price = targePrice ,
quantity = 1.5 , take_profit = 10 , stop_loss = 10 )
limit_order函數提交限制順序
marketOrder = cfd . limit_order ( instrument = "TSLA" , target_price = 127 ,
quantity = 1.5 , take_profit = 10 , stop_loss = 10 )
set_limits函數允許您修改或添加ofeross或takeprofit到現有郵局(需要positionID才能執行此功能)
limits = cfd . set_limits ( position_id = 27361748 , TP = 10 , SL = 10 )
add_trailing_stop函數在現有位置添加了一個尾聲
trailing = cfd . add_trailing_stop ( position_id = 27361748 , distance = 1 )
CLOSS_POINTION函數用於關閉打開位置。它需要當前價格。
currentPrice = cfd . fast_price ( instrument = "TSLA" )
close = cfd . close_position ( position_id = 23948174 , current_price = currentPrice )
cancelAll = cfd . cancel_all_orders ()
CANCEL_ORDER函數用於取消限制順序。
cancel = cfd . cancel_order ( order_id = ** ** ** ** ** )
get_live功能將返回股票的當前價格
tickers = [ "TSLA" , "AAPL" ]
prices = cfd . live_price ( instruments = tickers )
print ( prices )
[{ ' request ' : { ' ticker ' : ' TSLA ' , ' useAskPrice ' : False}, ' response ' : { ' timestamp ' : 1690531210000, ' price ' : 255.8, ' period ' : ' d1 ' }}, { ' request ' : { ' ticker ' : ' AAPL ' , ' useAskPrice ' : False}, ' response ' : { ' timestamp ' : 1690531210000, ' price ' : 193.29, ' period ' : ' d1 ' }}]
get_funds功能將返回您的帳戶資金。
funds = cfd . get_funds ()
print ( funds )
{ ' 20434246 ' : { ' accountId ' : ******** , ' tradingType ' : ' CFD ' , ' currency ' : ' GBP ' ,
' freeForWithdraw ' : 486.83, ' freeForCfdTransfer ' : 0, ' total ' : 486.83,
' lockedCash ' : { ' totalLockedCash ' : 0, ' lockedCash ' : []}}}
Taxing_Stop功能允許您在開放位置中添加一個尾聲。
trailing_stop = cfd . trailing_stop ( position_id = "***-****-***" , distance = 0.5 )
ADD_LIMITS功能允許您將Sotloss和TakeProfit添加到現有位置。
update_limits = client . add_limits ( position_id = "***-****-***" , TP = 1 , SL = 1 )
要設置新的止動或TakeProfit,只需將距離傳遞到TP(獲利)或SL(停止損失)參數。該功能將獲得當前價格並應用距離。
all_position_hist函數將返回位置歷史記錄。
position_history = cfd . all_position_hist ()
all_order_hist返回訂單數據
order_history = cfd . all_order_hist ()
get_instrument函數將重新編寫有關儀器的信息。
tsla_info = cfd . get_instruments_info ( instrument = 'TSLA' )
print ( tsla_info )
{ ' code ' : ' TSLA ' , ' type ' : ' STOCK ' , ' margin ' : 0.2, ' shortPositionSwap ' : -0.07030593058663,
' longPositionSwap ' : -0.27928156941337, ' tsSwapCharges ' : ' 1970-01-01T23:00:00.000+02:00 ' ,
' marginPercent ' : ' 20 ' , ' leverage ' : ' 1:5 ' }
get_position函數將返回qouted positionID的信息。
position = cfd . get_position ( position_id = "***-****-***" )
print ( position )
[{ ' eventType ' : { ' action ' : ' opened ' , ' source ' : ' MARKET_ORDER ' },
' eventNumber ' : { ' name ' : ' MO3053019640 ' , ' id ' : ' 274187113 ' , ' frontend ' : ' WC4 ' }, ' time ' : ' 2023-08-02T22:42:54.000+03:00 ' ,
' direction ' : ' sell ' , ' quantity ' : 1.0, ' price ' : ' 105.29 ' , ' avgQuantity ' : 1.0, ' avgPrice ' : ' 105.2900 ' , ' modifiedDirection ' :
' sell ' }]
get_summary函數將返回帳戶摘要。此功能也可以用於獲取訂單ID,並且當前有ppl
summary = cfd . get_summary ()
print ( summary )
' open ' : { ' unfilteredCount ' : 1, ' items ' : [{ ' positionId ' : ' ********-****-****-****-************ ' , ' humanId ' : ' ******** ' ,
' created ' : ' 2023-07-03T18:17:46.563+03:00 ' , ' averagePrice ' : 192.25, ' averagePriceConverted ' : 150.73025341182984,
' currentPrice ' : 192.2, ' value ' : 1054.82, ' investment ' : 1055.11, ' code ' : ' AAPL ' , ' margin ' : 212.02, ' ppl ' : -0.28,
' quantity ' : 7, ' maxBuy ' : 9.0, ' maxSell ' : 7, ' maxOpenBuy ' : 2033.0, ' maxOpenSell ' : 2040.0, ' swap ' : -1.06, ' frontend ' : ' WC4 ' }]}
LIVE_PRICE功能將返回通過儀器的當前詢問價格。
ticker = [ "TSLA" , "AAPL" , "GOOG" ]
live_price = cfd . live_price ( instruments = ticker )
print ( live_price )
[{ ' ticker ' : ' TSLA ' , ' price ' : 253.49}, { ' ticker ' : ' AAPL ' , ' price ' : 182.08}, { ' ticker ' : ' GOOG ' , ' price ' : 128.44}]
fast_price函數將返回最後一個Qout的圖表價格作為浮點
price = cfd . fast_price ( instrument = "TSLA" )
print ( price )
253.49
Chart_data功能將返回傳遞儀器的最後圖表數據
chart = cfd . chart_data ( instrument = "TSLA" )
print ( chart )
[{ ' request ' : { ' ticker ' : ' TSLA ' , ' period ' : ' ONE_MINUTE ' , ' size ' : 500, ' useAskPrice ' : False}, ' response ' : { ' candles ' : [[1691152740000, 259.6, 259.97, 259.43, 259.49, 47], [1691152800000, 259.38, 259.94, 259.17, 259.56, 58], [1691152860000, 259.62, 260.34, 259.62, 260.19, 42]
get_deviations功能將返回價格偏差
ticker = [ "TSLA" , "AAPL" , "GOOG" ]
deviations = cfd . get_deviations ( instruments = ticker )
print ( deviations )
[{ ' request ' : { ' ticker ' : ' TSLA ' , ' useAskPrice ' : False}, ' response ' : { ' timestamp ' : 1691136010000, ' price ' : 259.38, ' period ' : ' d1 ' }}, { ' request ' : { ' ticker ' : ' AAPL ' , ' useAskPrice ' : False}, ' response ' : { ' timestamp ' : 1691136010000, ' price ' : 188.99, ' period ' : ' d1 ' }}, { ' request ' : { ' ticker ' : ' GOOG ' , ' useAskPrice ' : False}, ' response ' : { ' timestamp ' : 1691136010000, ' price ' : 129.05, ' period ' : ' d1 ' }}]
GET_COMPANIES功能將返回當前在T212及其各自ISIN ID上列出的公司。
companies = cfd . get_companies ()
print ( companies )
[{ ' ticker ' : ' SIGTl_EQ ' , ' isin ' : ' GB0008769993 ' }, { ' ticker ' : ' PDYPY_US_EQ ' , ' isin ' : ' US3440441026 ' }...]
limit_order函數提交限制順序,並獲取數量,target_price,take_profit&stop_loss parms。
limit_order = cfd . limit_order ( instrument = "TSLA" ,
quantity = 5 , target_price = 129 , take_profit = 130 , stop_loss = 128 )
{'account': {'dealer': 'AVUSUK', 'positions': [{'positionId': '********-****-****-****-************',
'humanId': '**********', 'created': '2023-07-03T18:17:46.563+03:00' ...
Market_order功能提交市場訂單,並採用數量,target_price,take_profit&stop_loss parms。
market_order = cfd . market_order ( instrument = "TSLA" ,
quantity = 5 , target_price = 129 , take_profit = 130 , stop_loss = 128 )
CANCEL_ORDER功能將取消需要訂購的待處理訂單。
cancel_order = cfd . cancel_order ( order_id )
您還可以使用cancel_all_orders取消所有待定限制訂單。
cancel_all = cfd . cancel_all_orders ()
CLOSS_POINTION功能將提交請求以取消打開位置。
close_position = cfd . close_position ( position_id = 'ordexxxxx' , current_price = current_price )
username = "[email protected]"
password = "password132"
api = Apit212 ()
api . setup ( username = username , password = password , mode = "demo" )
cfd = CFD ( cred = api )
target_price = 128
while True :
sleep ( 60 )
price = cfd . fast_price ( "TSLA" )
if price <= target_price :
marketOrder = cfd . market_order ( instrument = "TSLA" , target_price = price , quantity = 1 , take_profit = 10 ,
stop_loss = 10 )
break
在進行交易時,您可能會遇到問題,並且在出現這些問題的情況下制定協議總是很好。
以下是您在進行交易時可能會遇到的一些例外列表。
如果您得到此回复,請停止提出請求
目前,這僅使用股票帳戶,您只能在演示帳戶上提交交易。請閱讀正式文檔,以更好地了解API。
為了使用官方API,您需要使用Trading212應用程序生成密鑰。 /settings/api(beta)然後簡單地生成一個新鍵,然後將其傳遞給apitkey()。equity()類。
from apit212 import *
key = "20557******************************"
client = Apitkey ()
info = client . Equity ( api_key = key , mode = "live" )
這是使用Trading212 API-Token可用的功能。
這是一個非正式的API,交易本人要么是負責使用此API的API。強烈建議您在轉移到真錢之前使用練習帳戶。 APIT212不是交易機器人