Il s'agit d'une API basée sur Pyhton utilisant le sélénium et des demandes pour obtenir des informations sur la plate-forme Trading212, veuillez noter que moi-même ou le trading212 assume la responsabilité des résultats liés à l'utilisation de cette API.
Je continuerai à travailler sur ce projet et je vais apprécier tout commentaire.
pip install apit212
Pour commencer à utiliser cette API, vous devrez d'abord vous connecter au compte en utilisant APIT212, vous pourrez alors utiliser toutes les fonctions et créer votre propre bot de trading ou l'utiliser pour les données scarpe à partir de la plate-forme 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" )
Il est bon à configurer un fichier Env pour enregistrer des informations sensibles comme votre nom d'utilisateur ou votre mot de passe. Voici un lien utile .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" )
Cette API est inutile sans le bon symbole de ticker, j'ai donc une solution.
from apit212 import Tickers
ticker = Tickers ()
print ( ticker . fetch_symbols ( symbol = 'META' ))
print ( ticker . find_by_name ( full_name = 'tesla' ))
Il y a pas mal de données à lire, mais la clé que vous recherchez est Ticker, cela renverra le symbole utilisé par la plate-forme 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' ])
Trouver un ticker en utilisant le ticker largement utilisé renverra souvent 1 résultat, mais à certaines occasions, vous pouvez obtenir plusieurs résultats, donc sa bonne pratique pour vérifier le len de la chaîne est retournée.
1
FB
Pour échanger des CFD, appelez simplement la classe CFD
from apit212 import *
api = Apit212 ()
api . setup ( username = "[email protected]" , password = "pass******" , mode = "demo" )
cfd = CFD ( cred = api )
Pour négocier les actions, appelez simplement la classe d'actions.
from apit212 import *
client = Apit212 ( username = "[email protected]" , password = "pass******" , mode = "live" )
equity = Equity ()
La fonction AUTH_VALIDAD renverra l'ID de compte et le type de commerce.
validate = cfd . auth_validate ()
print ( validate )
{ ' id ' : ' *******-****-****-****-************ ' , ' accountId ' : ******** , ' customerId ' : ********* , ' tradingType ' : ' CFD ' , ' customerUuid ' : ' ********-****-****-****-************ ' , ' frontend ' : ' WC4 ' , ' readyToTrade ' : True, ' deviceUuid ' : ' ' }
La fonction get_account renverra les détails de votre compte.
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}]}
La fonction get_funds renvoie les fonds de comptes.
funds = cfd . get_funds ()
print ( funds )
{ ' ******* ' : { ' accountId ' : ******** , ' tradingType ' : ' CFD ' , ' currency ' : ' GBP ' ,
' freeForWithdraw ' : 486.83, ' freeForCfdTransfer ' : 0, ' total ' : 486.83,
' lockedCash ' : { ' totalLockedCash ' : 0, ' lockedCash ' : []}}}
Le get_summary renvoie un résumé de votre compte.
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 ' }]}
Les instruments Get_Companies sont avalimes pour négocier sur la plate-forme Trading212
companies = cfd . get_companies ()
print ( companies )
[{ ' ticker ' : ' SIGTl_EQ ' , ' isin ' : ' GB0008769993 ' }, { ' ticker ' : ' PDYPY_US_EQ ' , ' isin ' : ' US3440441026 ' }...]
Le get_instruments_info renverra des informations sur un instrument.
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 ' }
Le get_order_info
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 ' }}]
Le Get_Position renvoie l'intérêt pour un identifiant de position donné, ces identifiants peuvent être extraits de la fonction 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 ' }]
La fonction get_all_result renverra une liste de tous vos résultats de trading. Vous devrez demander chaque page. Vous devrez peut-être également passer votre fuseau horaire.
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}
Le Fast_Price retrans le prix des instruments en tant que flotteur. Si la demande échoue, aucune n'est retournée
price = cfd . fast_price ( instrument = "TSLA" )
print ( price )
253.49
Le chart_data renvoie un dictionnaire avec la date de la bougie OHLC (ouvert, haut, bas, ferme) la période demandée. qui est défini sur 1Minute par défaut.
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]
La fonction Multi_price renverra le dernier prix QOted pour tous les instruments passés.
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}]
La fonction Market_Order soumet une commande de marché et nécessite le prix actuel de l'instrument.
targetPrice = cfd . fast_price ( instrument = "TSLA" )
marketOrder = cfd . market_order ( instrument = "TSLA" , target_price = targePrice ,
quantity = 1.5 , take_profit = 10 , stop_loss = 10 )
La fonction limite_order soumet un ordre limite
marketOrder = cfd . limit_order ( instrument = "TSLA" , target_price = 127 ,
quantity = 1.5 , take_profit = 10 , stop_loss = 10 )
La fonction set_limimits vous permet de modifier ou d'ajouter un stoploss ou un apport à prendre à une position existante (le positionID est nécessaire pour remplir cette fonction)
limits = cfd . set_limits ( position_id = 27361748 , TP = 10 , SL = 10 )
La fonction add_trailing_stop ajoute un arrêt de fin à une position existante
trailing = cfd . add_trailing_stop ( position_id = 27361748 , distance = 1 )
La fonction close_position est utilisée pour fermer une position ouverte. Cela nécessitera le prix actuel.
currentPrice = cfd . fast_price ( instrument = "TSLA" )
close = cfd . close_position ( position_id = 23948174 , current_price = currentPrice )
cancelAll = cfd . cancel_all_orders ()
La fonction Cancel_Order est utilisée pour annuler une commande limite.
cancel = cfd . cancel_order ( order_id = ** ** ** ** ** )
La fonction get_live renverra le prix actuel d'un ticker
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 ' }}]
La fonction GET_FUNDS renverra vos fonds de comptes.
funds = cfd . get_funds ()
print ( funds )
{ ' 20434246 ' : { ' accountId ' : ******** , ' tradingType ' : ' CFD ' , ' currency ' : ' GBP ' ,
' freeForWithdraw ' : 486.83, ' freeForCfdTransfer ' : 0, ' total ' : 486.83,
' lockedCash ' : { ' totalLockedCash ' : 0, ' lockedCash ' : []}}}
La fonction de parole_stop vous permet d'ajouter un arrêt de fuite à une position ouverte.
trailing_stop = cfd . trailing_stop ( position_id = "***-****-***" , distance = 0.5 )
La fonction add_limimits vous permet d'ajouter un stoploss et unprofit à une position existante.
update_limits = client . add_limits ( position_id = "***-****-***" , TP = 1 , SL = 1 )
Pour définir un nouveau Stoploss ou Takeprofit, passez la distance aux paramètres TP (Take Profit) ou SL (Stop Loss). La fonction obtiendra le prix actuel et appliquera la distance.
La fonction ALL_POSITION_HIST renverra l'historique de position.
position_history = cfd . all_position_hist ()
Le All_Order_Hist renvoie les données des commandes
order_history = cfd . all_order_hist ()
La fonction GET_INSTRUMENT réduira les informations sur l'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 ' }
La fonction Get_Position renverra des informations pour le QOTED 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 ' }]
La fonction get_summary renverra le résumé du compte. Cette fonction peut également être utilisée pour obtenir des identifiants de commande et des personnes actuelles
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 ' }]}
La fonction live_price renverra le prix de demande actuel de l'instrument passé.
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}]
La fonction FAST_PRICE renverra le dernier prix du graphique QUEST comme un flotteur
price = cfd . fast_price ( instrument = "TSLA" )
print ( price )
253.49
La fonction chart_data renverra les dernières données de graphique pour l'instrument passé
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]
La fonction get_deviations retournera les écarts de prix
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 ' }}]
La fonction GET_COMPANIES renverra les sociétés actuellement répertoriées sur T212 et leur ID ID respectif.
companies = cfd . get_companies ()
print ( companies )
[{ ' ticker ' : ' SIGTl_EQ ' , ' isin ' : ' GB0008769993 ' }, { ' ticker ' : ' PDYPY_US_EQ ' , ' isin ' : ' US3440441026 ' }...]
La fonction LIMIT_ORDER soumet un ordre limite et prend la quantité, 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' ...
La fonction Market_Order soumet une commande de marché et prend la quantité, 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 )
La fonction Cancel_Order annulera une commande en attente, il nécessite un OrderId.
cancel_order = cfd . cancel_order ( order_id )
Vous pouvez également utiliser les annul_all_orders pour annuler toutes les commandes de limites en attente.
cancel_all = cfd . cancel_all_orders ()
La fonction close_position soumettra une demande pour annuler une position ouverte.
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
Lorsque vous réalisez un métier, vous pourriez rencontrer des problèmes et il est toujours bon d'avoir des protocoles en place pour faire face à ces problèmes lorsqu'ils surviennent.
Vous trouverez ci-dessous une liste de quelques exceptions que vous pourriez rencontrer lors de la réalisation d'un métier.
Arrêtez simplement de faire la demande si vous obtenez cette réponse
Cela ne fonctionne actuellement qu'avec des comptes d'actions et vous ne pouvez soumettre que des transactions sur votre compte de démonstration. Veuillez lire la documentation officielle pour obtenir une meilleure compréhension et des limites de l'API.
Afin d'utiliser l'API officielle, vous devrez générer une clé à l'aide de l'application Trading212. / Paramètres / API (Beta) Générez ensuite simplement une nouvelle clé et passez-la à la classe APITKEY (). Equity () .
from apit212 import *
key = "20557******************************"
client = Apitkey ()
info = client . Equity ( api_key = key , mode = "live" )
Voici les fonctions disponibles à l'aide de l'API-token Trading212.
Il s'agit d'une API non officielle et moi-même de Trading212 est responsable de l'utilisation de cette API. Il est fortement conseillé d'utiliser un compte de pratique avant de passer à de l'argent réel. APIT212 n'est pas un bot de trading