이것은 Selenium을 사용하는 Pyhton 기반 API이며 Trading212 플랫폼에서 정보를 얻도록 요청합니다. 나 자신 또는 Trading212는이 API의 사용과 관련된 결과에 대해 책임을집니다.
나는이 프로젝트를 계속 진행하고 모든 피드백을 필요로 할 것입니다.
PIP 설치 APIT212
이 API 사용을 시작하려면 먼저 APIT212를 사용하여 계정에 로그인해야합니다. 그러면 모든 기능을 사용하여 자신의 거래 봇을 만들거나 Trading212 플랫폼에서 데이터를 스카프로 사용할 수 있습니다.
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' ))
읽을 수있는 약간의 데이터가 있지만, 당신이 후에있는 열쇠는 Ticker 입니다. 이것은 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 개의 결과가 반환되지만 경우에 따라 여러 결과가 발생할 수 있으므로 리턴 된 문자열의 Len을 확인하는 것이 좋습니다.
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는 거래를 반환하여 거래 할 수있는 거래 212 플랫폼에서 거래
companies = cfd . get_companies ()
print ( companies )
[{ ' ticker ' : ' SIGTl_EQ ' , ' isin ' : ' GB0008769993 ' }, { ' ticker ' : ' PDYPY_US_EQ ' , ' isin ' : ' US3440441026 ' }...]
get_instruments_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 함수는 모든 통과 된 기기에 대한 마지막 Qouted 가격을 반환합니다.
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 함수를 사용하면 기존 위치에 stoploss 또는 takeprofit을 수정하거나 추가 할 수 있습니다 (이 기능을 수행하려면 위치가 필요합니다).
limits = cfd . set_limits ( position_id = 27361748 , TP = 10 , SL = 10 )
add_trailing_stop 함수는 기존 위치에 후행 정지를 추가합니다.
trailing = cfd . add_trailing_stop ( position_id = 27361748 , distance = 1 )
Close_Position 함수는 열린 위치를 닫는 데 사용됩니다. 현재 가격이 필요합니다.
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 ' : []}}}
Trailing_stop 함수를 사용하면 열린 위치에 후행 정지를 추가 할 수 있습니다.
trailing_stop = cfd . trailing_stop ( position_id = "***-****-***" , distance = 0.5 )
add_limits 함수를 사용하면 기존 위치에 STOPLOSS 및 TAKEPROFIT를 추가 할 수 있습니다.
update_limits = client . add_limits ( position_id = "***-****-***" , TP = 1 , SL = 1 )
새로운 정지 로스 또는 테이크 프 로프를 설정하려면 TP (Take Profit) 또는 SL (STOP LOSS) 매개 변수로의 거리를 전달하십시오. 함수는 현재 가격을 얻고 거리를 적용합니다.
all_position_hist 함수는 위치 기록을 반환합니다.
position_history = cfd . all_position_hist ()
All_order_hist 는 주문 데이터를 반환합니다
order_history = cfd . all_order_hist ()
get_instrument 함수는 기기에 대한 정보를 retun습니다.
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 함수는 마지막 Qouted 차트 가격을 플로트로 반환합니다.
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 ()
Close_Position 함수는 열린 위치를 취소하라는 요청을 제출합니다.
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 (베타) 그런 다음 새 키를 생성하여 apitkey (). Quity () 클래스로 전달합니다.
from apit212 import *
key = "20557******************************"
client = Apitkey ()
info = client . Equity ( api_key = key , mode = "live" )
다음은 Trading212 Api-Token을 사용하는 기능은 다음과 같습니다.
이것은 비공식 API이며 Trading212의 나 자신 이이 API의 사용을 담당합니다. 실제 돈으로 이동하기 전에 연습 계정을 사용하는 것이 좋습니다. APIT212는 거래 봇이 아닙니다