### Examples Update Source: https://app1.directatrading.com/trading-api-directa/index.html Update to the examples provided. ```text 16/10/2014 Aggiornamento esempi ``` -------------------------------- ### Port Allocation Example with Three User Accounts Source: https://app1.directatrading.com/trading-api-directa/index.html This example illustrates how ports are allocated when three user accounts (A, B, and C) are active. Each user gets a consecutive block of four ports. ```text utenza A 10001,10002,10003,10004 utenza B 10005,10006,10007,10008 utenza C 10009,10010,10011,10012 ``` -------------------------------- ### Historical Calls Code Examples Source: https://app1.directatrading.com/trading-api-directa/index.html Update to the tutorial with code examples for historical data calls. ```text 05/02/2018 Aggiornamento Tutorial - Esempi di codice (codice per chiamate storiche) ``` -------------------------------- ### Bid/Ask Formula Example: PX_BID Source: https://app1.directatrading.com/trading-api-directa/excel.html Example of how to get the best bid price for a specific ticker (STLA). ```formula TICKER | RISULTATO Esempio per formula la =PX_BID("STLA"): STLA | 6,205 ``` -------------------------------- ### AVAILABILITY Message Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of an AVAILABILITY message showing various liquidity figures. ```text AVAILABILITY;14:47:04;1000;5000;0;0;5000 ``` -------------------------------- ### Example: Querying and Setting After-Hours Volume Detail Source: https://app1.directatrading.com/trading-api-directa/index.html This example demonstrates a client sending a command to query the after-hours volume setting and receiving the default response. It also shows a subsequent command to change the setting and the confirmation response. ```text 17:58:50 TX Connection socket localhost port:100003 17:58:52 RX DARWIN_STATUS;CONN_OK;TRUE;Release 1.2.1 build 01/08/2020 14:10:00 more info... 18:00:11 TX VOLUMEAFTERHOURS 18:00:12 RX VOLUME_AFTERHOURS CNT+AH 18:00:23 TX CANDLE STLAM 1 86400 18:00:23 RX BEGIN CANDLES ``` -------------------------------- ### INFOACCOUNT Message Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of an INFOACCOUNT message showing account details like liquidity, gain, and equity. ```text INFOACCOUNT;12:49:11;40000;150000;1200;430;2 ``` -------------------------------- ### Index Data Subscription Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of PRICE messages received after subscribing to an index (FMIB). Shows real-time price updates for the index. ```text PRICE;fMIB;10:23:21;23827.42;0;0;0;23814.62;23893.72 ``` ```text PRICE;fMIB;10:23:33;23827.6;0;0;0;23814.62;23893.72 ``` -------------------------------- ### Order Placed Record Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of a message indicating a successful order placement for buying 10 STLAM shares at 4.75. ```text TRADOK;STLAM;ORD001;3000;ACQAZ;10;4.75,0.0 ``` -------------------------------- ### Example Order Placement with POINTUPDATEORDER Source: https://app1.directatrading.com/trading-api-directa/index.html Demonstrates placing an order and receiving the initial automatic update packet when POINTUPDATEORDER is enabled. ```text ACQAZ ORD1,STLAM,1,5.75 TRADOK;STLAM;ORD1;3000;ACQAZ;1;5.75;0.0;0.0;0;0;S4216521807924 **BEGIN UPDATEORDER UORDER;STLAM;16:52:18;ORD1;ACQAZ;5.75;0.0;1;2002;0.0;0.0;0;S4216521807924 USTOCK;STLAM;16:52:18;0;0;1;0.0; UAVAILABILITY;16:52:18;45.09;45.09;0.0;0.0;50.84 UINFOACCOUNT;16:52:18;47511;50.84;0;0.0 END UPDATEORDER** ``` -------------------------------- ### Example Trading Flow with PRICEEXE Enabled Source: https://app1.directatrading.com/trading-api-directa/index.html Illustrates a trading sequence when PRICEEXE is enabled, showing order placement and subsequent updates. ```text ACQAZ ORD121916,STLAM,1,4.75 TRADOK;STLAM;ORD121916;3000;ACQAZ;1;4.75;0.0;**ACQAZ ORD121916,STLAM,1,4.75** REVORD ORD121916 TRADOK;STLAM;ORD121916;3002;ACQAZ;1;4.75;0.0;**REVORD ORD121916** ``` -------------------------------- ### English Guide Update Source: https://app1.directatrading.com/trading-api-directa/index.html Introduction and update of the guide in English. ```text 26/12/2014 Introduzione ed aggiornarmento della guida in inglese ``` -------------------------------- ### Log Analysis Example Source: https://app1.directatrading.com/trading-api-directa/index.html This example demonstrates the format of log entries, distinguishing between transmitted (TX) and received (RX) data, connection status, and command details. Lines in blue indicate sent commands, black lines are socket responses, and red lines signal errors. ```text 17:02:11 TX Connection socket localhost port:10003 17:02:12 RX DARWIN_STATUS;CONN_OK;TRUE;Release 1.2.1 build 01/08/2020... 17:02:33 TX CANDLE STLAM 1 3600 17:02:39 RX BEGIN CANDLES 17:02:39 RX CANDLE;STLAM;20150707;09:00:00;13.00000;12.77000;13.04000;12.94000;3574235 17:02:39 RX CANDLE;STLAM;20150707;10:00:00;12.99000;12.88000;13.00000;13.00000;1445758 17:02:39 RX CANDLE;STLAM;20150707;11:00:00;12.92000;12.91000;13.00000;12.98000;924531 17:02:39 RX CANDLE;STLAM;20150707;12:00:00;12.81000;12.79000;12.93000;12.92000;1012106 17:02:39 RX CANDLE;STLAM;20150707;13:00:00;12.78000;12.74000;12.86000;12.81000;644852 17:02:39 RX CANDLE;STLAM;20150707;14:00:00;12.75000;12.74000;12.85000;12.78000;571338 17:02:39 RX CANDLE;STLAM;20150707;15:00:00;12.75000;12.67000;12.82000;12.74000;1457200 17:02:39 RX CANDLE;STLAM;20150707;16:00:00;12.60000;12.44000;12.81000;12.76000;2255510 17:02:39 RX CANDLE;STLAM;20150707;17:00:00;12.57000;12.57000;12.59000;12.59000;70532 17:02:39 RX END CANDLES Close Socket port:10003 ``` -------------------------------- ### Price Formula Example: PX_LAST Source: https://app1.directatrading.com/trading-api-directa/excel.html Example of how to get the last traded price for a specific ticker (STLA). ```formula TICKER | RISULTATO Esempio per formula la =PX_LAST("STLA"): STLA | 6,255 ``` -------------------------------- ### Order Management Examples Source: https://app1.directatrading.com/trading-api-directa/index.html Examples of order placement, modification, and finalization within the trading stream. These commands are used to interact with the trading system for specific orders. ```text ORDER;STLAM;10:49:00;ORD1;ACQAZ;6.165;0.0;1;2004 ORDER;STLAM;10:36:11;ORD2;ACQAZ;6.15;0.0;1;2004 ORDER;STLAM;10:36:45;ORD3;ACQAZ;6.145;0.0;1;2004 ORDER;STLAM;10:47:49;ORD4;ACQAZ;6.145;0.0;1;2004 ORDER;STLAM;10:49:05;ORD5;ACQAZ;6.16;0.0;1;2004 ACQAZ ORD1,STLAM,1,4.75 TRADOK;STLAM;ORD1;3000;ACQAZ;1;4.75;0.0 MODORD ORD1,4.85 TRADOK;STLAM;ORD1;3000;ACQAZ;1;4.85;0.0 REVORD ORD1 TRADOK;STLAM;ORD1;3002;ACQAZ;1;4.85;0.0 ``` -------------------------------- ### TABLELIST Command Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of sending a TABLELIST command to retrieve available table names on the account. The response includes table codes and names, with a note on potential duplicate names but distinct codes. ```text TABLELIST ``` -------------------------------- ### PRICE Message Example (Daily Progressivo) Source: https://app1.directatrading.com/trading-api-directa/index.html Examples of PRICE messages for STLAM to show daily progressive actions and contracts. ```text PRICE;STLAM;15:53:53;15.74;127; 29119600;23825;15.67;16.29 ``` ```text PRICE;STLAM;15:53:53;15.74;500; 29120100;23826;15.67;16.29 ``` ```text PRICE;STLAM;15:53:53;15.74;1873; 29121973;23827;15.67;16.29 ``` -------------------------------- ### Example InfoAvailability Response Source: https://app1.directatrading.com/trading-api-directa/excel.html Illustrates the response format for the =InfoAvailability() command, detailing available amounts for stocks and derivatives. ```Text 11:50:22 | 52,15 | 52,15 | 0 | 0 | 52,15 ``` -------------------------------- ### Get Stock Information Source: https://app1.directatrading.com/trading-api-directa/index.html Use this command to get information about stocks in your portfolio and those being traded. No additional parameters are needed. ```text INFOSTOCKS ``` -------------------------------- ### DARWIN_STATUS Message Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of a DARWIN_STATUS message indicating connection status, datafeed enablement, and release version. ```text DARWIN_STATUS;CONN_OK;TRUE;Release 1.2.1 build 01/08/2020 14:10:00 more info at http://app1.directatrading.com/trading-api-directa/index.html ``` -------------------------------- ### Example InfoAccount Response Source: https://app1.directatrading.com/trading-api-directa/excel.html Demonstrates the response format for the =InfoAccount() command, presenting account metrics like liquidity, gain, and performance. ```Text 11:48:17 | 47511 | 52,15 | 0 | 0 | -0,02 ``` -------------------------------- ### TickByTick (TBT) Command Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of a TBT command to retrieve tick-by-tick data for a specific ticker and date, and its corresponding server response. ```text TBT REY 1 (REY 1giorno) no delta... 11 TBT;REY;20140618;09:09:21;57.55000;11 TBT;REY;20140618;09:09:21;57.55000;12 ........ TBT;REY;20140618;13:42:16;57.05000;11966 END TBT ``` -------------------------------- ### Candle Command Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of a CANDLE command to retrieve aggregated candle data for a ticker, date, and time interval, along with the server response. ```text CANDLE REY 1 3600 spiegazione:(REY 1giorno 1ora,ovvero 3600 secondi) CANDLE;REY;20140618;09:00:00;57.65000;57.35000;58.10000;57.55000;1115 ........ CANDLE;REY;20140618;13:00:00;57.05000;57.00000;57.70000;57.45000;11966 ``` -------------------------------- ### C Example: Connect to DataFeed and Subscribe Source: https://app1.directatrading.com/trading-api-directa/index.html This C code demonstrates how to establish a socket connection to the DataFeed, send a subscription command for a specific instrument (STLAM), and read a limited number of messages from the server. It includes error handling for socket operations. ```c #include #include #include #include #include #include #include #include //Metodo per la gestione errori,non fondamentale ai fini della connessione void error(const char *msg) { perror(msg); exit(0); } //La classe main int main(int argc, char *argv[]) { int sockfd, portno, n; struct sockaddr_in serv_addr; struct hostent *server; int i=0; char buffer[256]; char command[256]; int nb; int nLine=100; printf("Connessione al DATAFEED\n\n"); char host[20]; sprintf(host,"localhost"); //variabile contente il numero della porta portno=10001; //apertura del socket sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); //variabile per settare l'host in questo caso localhost ovvero 127.0.0.1 server=gethostbyname(host); if (server == NULL) { fprintf(stderr,"ERROR, no such host\n"); exit(0); } //gestione della connessione al socket bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); //gestione per eventuali errori nella connessione al socket if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR connecting"); bzero(buffer,256); n = write(sockfd, command, strlen(command)); if (n < 0) error("ERROR writing to socket"); bzero(buffer,256); n = read(sockfd, buffer, 255); if (n < 0) error("ERROR reading from socket"); //Stampa di avvenuta connessione printf("CONNESSIONE AVVENUTA sulla porta %d\n",portno); printf("%s\n", buffer); //send del client del comando in questo caso esempio di sottoscrizione di STLAM nb=sprintf(buffer,"SUB STLAM\n"); write(sockfd,buffer,nb); while(i<=nLine){ //lettura e stampa del buffer ovvero la risposta del server //qui stampa le 100 prime righe,poi esce dal ciclo nb=read(sockfd,buffer,256); buffer[nb]=0; printf("%d messaggio da server: %s\n",i,buffer); i++; } //chiusura della connessione al socket. printf("Chiusura della connessione\n"); close(sockfd); return 0; }//end main ``` -------------------------------- ### ORDERLIST with FLOWPOINT Enabled Source: https://app1.directatrading.com/trading-api-directa/index.html Example of receiving ORDERLIST data with the FLOWPOINT command enabled, showing BEGIN and END markers. ```text ORDERLIST **BEGIN ORDERLIST** ORDER;A2A;09:46:11;ORD1;ACQAZ;1.075;0.0;1;2004 ORDER;A2A;09:59:46;ORD2;ACQAZ;1.5;0.0;1;2003 ORDER;A2A;09:57:12;ORD3;ACQAZ;1.052;0.0;1;2004 ORDER;ENEL;10:04:42;ORD9;VENAZ;3.8;0.0;1;2003 **END ORDERLIST** ``` -------------------------------- ### Candle Range Command Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of a CANDLERANGE command to retrieve candle data within a specified date and time range, and its response. ```text CANDLERANGE REY 20140617090000 20140618130000 3600 spiegazione: (REY data_ora_iniziale:17/06/2014 09:00:00) CANDLE;REY;20140617;09:00:00;57.90000;57.75000;58.25000;58.25000;1089 ........ CANDLE;REY;20140618;13:00:00;57.05000;57.00000;57.70000;57.45000;11966 ``` -------------------------------- ### TABLE Command Usage Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of how to use the TABLE command to retrieve tickers and descriptions from a specific table. It's essential to call TABLELIST first to initialize table information. ```text TABLE A1;PRIMA ``` -------------------------------- ### Example Trading Flow with LOGCMD Enabled Source: https://app1.directatrading.com/trading-api-directa/index.html Demonstrates a typical trading sequence with the LOGCMD command enabled, showing both sent and received packets with the added command information. ```text ACQAZ ORD121835,STLAM,1,4.75 TRADOK;STLAM;ORD121835;3000;ACQAZ;1;4.75;0.0;0.0;0;0;S1112184397605;**ACQAZ ORD121835,STLAM,1,4.75** REVORD ORD121835 TRADOK;STLAM;ORD121835;3002;ACQAZ;1;4.75;0.0;0.0;0;0;S1112184397605;**REVORD ORD121835** ``` -------------------------------- ### Order Executed Record Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of a message indicating a successful order execution for buying 10 STLAM shares at 4.75. ```text TRADOK;STLAM;ORD001;3001;ACQAZ;10;4.75,0.0 ``` -------------------------------- ### Python Example: Connect to DataFeed and Subscribe Source: https://app1.directatrading.com/trading-api-directa/index.html This Python code demonstrates establishing a socket connection to the DataFeed on localhost and port 10001. It sends a subscription command for 'UCG' and reads a specified number of messages. Error handling for socket creation and connection is included. ```python # API Directa - Esempio DataFeed # Python 3.9.13 (main, Aug 25 2022, 18:29:29) # [Clang 12.0.0 ] # DIRECTA API Documentation # http://app1.directatrading.com/trading-api-directa/index.html # Libreria python per gestione socket # https://docs.python.org/3/library/socket.html import socket # Funzione per printare il messaggio di errore def errore(messaggio): print(messaggio) exit(0) # Funzione per la connessione e la ricezione del feed def datafeed(): sfeed = "" porta = 10001 buffersize = 256 nfeed = 100 comando = "SUBPRZ UCG\n" host = "127.0.0.1" # Socket try: sfeed = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error as err: errore(f"errore nel creare il socket: {err}") # Connessione al socket try: sfeed.connect((host, porta)) except socket.error as err: errore(f"errore di connessione: {err}") # Invio comando try: sfeed.sendall(comando.encode('utf-8')) ``` -------------------------------- ### Example Orderlist Response Source: https://app1.directatrading.com/trading-api-directa/excel.html Shows the typical response format for the =OrderList() command, detailing each order's parameters including status, type, and quantities. ```Text 17:11:45 | STLA | EXC0 | CANCELLED | BUY | 3,5 | 0 | 1 | 0 | 0 | 0 | S0717114518837 17:20:31 | STLA | EXC1 | CANCELLED | BUY | 3,8 | 0 | 1 | 0 | 0 | 0 | S0717203119654 17:25:50 | STLA | EXC2 | PENDING | BUY | 3,5 | 0 | 1 | 0 | 0 | 0 | S0717255020209 ``` -------------------------------- ### Order Confirmation Request Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of a message requesting client confirmation for order ORD001, specifying the purchase of 10 STLAM shares at a price of 1.00. ```text TRADCONFIRM;STLAM;ORD001;3003;ACQAZ;10;1;VI TRASMETTO L'ORDINE DI ACQUISTO DI 10 STLAM AL PREZZO DI 1,0000 EURO PER UN VALORE DI 10 EURO. ``` -------------------------------- ### STOCK Message Example (STLAM - Order in Progress) Source: https://app1.directatrading.com/trading-api-directa/index.html Example of a STOCK message for STLAM showing an order being processed by Directa. ```text STOCK;STLAM;09:54:38;0;1;1 >;0.0;; ``` -------------------------------- ### STOCK Message Example (STLAM - Order at Exchange) Source: https://app1.directatrading.com/trading-api-directa/index.html Example of a STOCK message for STLAM showing an order processed by the exchange. ```text STOCK;STLAM;09:54:41;0;0;1;0.0;; ``` -------------------------------- ### INFOSTOCKS with FLOWPOINT Enabled Source: https://app1.directatrading.com/trading-api-directa/index.html Example of receiving INFOSTOCKS data with the FLOWPOINT command enabled, showing BEGIN and END markers. ```text INFOSTOCKS **BEGIN STOCKLIST** STOCK;AGL;16:41:49;47;0;;7.7036;20 STOCK;A2A;16:41:49;82;70;70> -70;1.1326;-4 STOCK;BMPS;16:41:49;1;0;;2.18;-1 STOCK;LX.EURUSD;16:41:49;144;0;;1.122389;43 STOCK;.FB;16:41:49;14;0;;83.1958;77 STOCK;.GOOG;16:41:49;10;0;;641.7701;-362 STOCK;.KO;16:41:49;4;0;;43.4792;-14 **END STOCKLIST** ``` -------------------------------- ### Port Allocation After Disconnecting and Adding a User Source: https://app1.directatrading.com/trading-api-directa/index.html This example demonstrates port allocation after user A is disconnected and a new user D is added. User D will be assigned the first available port block. ```text utenza D 10001,10002,10003,10004 utenza B 10005,10006,10007,10008 utenza C 10009,10010,10011,10012 ``` -------------------------------- ### Order Cancelled Record Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of a message indicating a successful order cancellation for buying 10 STLAM shares at 4.75. ```text TRADOK;STLAM;ORD001;3002;ACQAZ;10;4.75,0.0 ``` -------------------------------- ### TABLE Command Response Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example response for the TABLE command when requesting 'A1;PRIMA'. It lists tickers and their descriptions within the specified table, indicating the total number of items. ```text BEGIN LIST A1;PRIMA (9) AGL;AUTOGRILL SPA AZM;AZIMUT A2A;A2A SpA BMPS;B.MONTE PASCHI SI BPE;BPER BANCA BZU;BUZZI UNICEM END LIST ``` -------------------------------- ### BIDASK Message Format Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of a BIDASK (bid/ask) message record for the STLAM ticker. Note that the number of proposals may not be available. ```text BIDASK;STLAM;16:41:21;14381; 0;6.795;5458;0;6.805 ``` -------------------------------- ### TickByTick Range (TBTRANGE) Command Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of a TBTRANGE command to retrieve tick-by-tick data within a specified date and time range, and its response. ```text TBTR REY 20140617090000 20140618140000 no delta... 0 TBT;REY;20140617;09:12:23;57.90000;56 TBT;REY;20140617;09:12:23;57.90000;114 ........ TBT;REY;20140618;13:42:16;57.05000;11966 END TBT ``` -------------------------------- ### STOCK Message Example (STLAM - Multiple Orders at Exchange) Source: https://app1.directatrading.com/trading-api-directa/index.html Example of a STOCK message for STLAM showing multiple orders at the exchange. ```text STOCK;STLAM;10:03:18;0;0;2;0.0;; ``` -------------------------------- ### Example Trading Error with PRICEEXE Enabled Source: https://app1.directatrading.com/trading-api-directa/index.html Shows an example of a trading error where an order cannot be placed due to a significant price deviation from market values. ```text ACQAZ ORD124431,STLAM,1,1.75 TRADERR;STLAM;ORD124431;1012;ACQAZ;1;1.7500;L‘ORDINE NON PUO‘ ESSERE INOLTRATO PER SCOSTAMENTO DI PREZZO TROPPO ELEVATO RISPETTO AI VALORI DI MERCATO;**ACQAZ ORD124431,STLAM,1,1.7500** ``` -------------------------------- ### Order Message Format Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of an ORDER record for a specific stock, indicating its trading status. The timestamp reflects the exact order placement time. ```text ORDER;STLAM;16:20:40;ORD1;ACQAZ;4.75;0.0;10;2000 ``` -------------------------------- ### Java DataFeed Connection and Subscription Example Source: https://app1.directatrading.com/trading-api-directa/downfile.php?id=2 This Java class connects to the DataFeed on a specified host and port. It allows sending commands, subscribing to financial instrument data for a set duration, and handling connection closure. Use this for real-time data retrieval. ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; /** *Classe esempio per la connessione al DataFeed porta 10001. *Effetuata la connessione viene chiesto un comando in input, *dato questo comando partirà l'informativa del titolo/i richiesto/i per 60 secondi. *Passato il minuto verrà sottoscritto il titolo/i e chiusa la connessione. * *Ovviamente se viene inserito un comando sbagliato ci sarà codice errore e chiusura. */ public class ConnectDataFeed{ Socket s; //il socket che utilizziamo per la connessione PrintWriter pW; //fornisce i metodi print e println, che permettono di scrivere qualunque dato Java, convertendolo automaticamente in stringa. BufferedReader bfr; //usa un buffer (memoria tampone) per memorizzare temporaneamente i caratteri da leggere/scrivere int porta; //porta sul quale fare l'accesso String host; //host sul quale fare l'accesso //variabili per sviluppo del codice static String tick; static boolean verifica=true; /** *Costruttore,in questo caso inizializziamo l'host e la porta per la connessiona */ public ConnectDataFeed(int porta,String host){ this.porta=porta; this.host=host; } /** * Connessione al socket. * creo il socket il printwriter e il buffer. */ private void Connessione(){ try { s = new Socket(host, porta); pW = new PrintWriter(s.getOutputStream(), true); bfr = new BufferedReader(new InputStreamReader(s.getInputStream())); System.out.println("Connessione avvenuta"); System.out.println(RLine()); } catch (Exception e) { System.err.println("Unable to connect to the DataFeed: " + e ); } } /** * Metodo per la chiusura della connessione. */ private void closeConnection(){ try { System.out.println("Chiusura in corso."); pW.close(); bfr.close(); s.close(); System.out.println("Chiusura effettuata!"); } catch (Exception e){ System.err.println("Error disconnecting from the DataFeed: " + e); } } /** * Metodo per fare la send del comando dato in input * @param cmd il comando */ private void sendCommand(String cmd){ pW.println(cmd); } /** * Metodo per stampare il contenuto del buffer. * @return stringa contente la stringa del buffer */ private String RLine(){ String line = null; try { line = bfr.readLine(); } catch (IOException e) { e.printStackTrace(); } return line; } /** * metodo utilizzato per la stampa del buffer per un numero di secondi preso in input */ private void sott_nsec() { //Scanner input=new Scanner(System.in); //System.out.println("Inserire per quanto tempo effetturare le sottoscrizioni(in secondi):"); //int timer=input.nextInt(); int timer=120;//secondi boolean continua=true; String line=""; long start= System.currentTimeMillis();//variabile per il temporizzatore System.out.println("Stampati per -->"+timer+"<-- secondi le sottoscrizioni per "+tick); while(continua){ line=RLine();//prende il messaggio dal buffer if(line.startsWith("ERR")){ continua=false; verifica=false; } System.out.println(line);//stampa delle risposta long now= System.currentTimeMillis();//gestione del temporizzatore long tot= (now-start)/1000; //System.out.println("verifica tempo:"+tot); if(tot>timer) continua=false; }//test per il temporizzatore se oltre il limite via dal ciclo } /** * Metodo utilizzato per ricavare il ticker del titolo dal comando in input * @param cmd comando da input * @return il ticker */ private String formatTick(String cmd){ String formats=cmd.replace(" ", "\t\t\t\t\t\t\t\t"); String tick=formats.substring(formats.length()-8,formats.length()).trim(); return tick; } public static void main(String args[]){ System.out.println("TEST DATAFEED"); ConnectDataFeed t=new ConnectDataFeed(10001,"localhost");//creazione dell'oggetto t.Connessione();//connessione Scanner scanner = new Scanner(System.in); System.out.print("Digitare il comando:"); String cmd = scanner.nextLine();//input del comando t.sendCommand(cmd);//invio il comando //richiamo della stampa del buffer,con dei controlli if(cmd.startsWith("SUB")){ tick=t.formatTick(cmd);//prendo il ticker t.sott_nsec();//metodo per la sottoscrzione per n secondi if(verifica==true){ System.out.println("\ndesottoscrizione del titolo---> UNS "+tick); //t.sendCommand("UNS"+tick);//mandiamo la desottoscrizione del titolo } } else System.out.println(t.RLine()); t.closeConnection();//chiusura della connessione } } ``` -------------------------------- ### Java Trading API Connection and Order Handling Source: https://app1.directatrading.com/trading-api-directa/index.html Example of connecting to the trading API on port 10002, printing portfolio status and order list, and sending a dummy trading command. Includes error handling for connection issues and response processing. ```java import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.Socket;\nimport java.util.Vector;\n\n/**\n * Classe d'esempio per la connessione al Trading tramite la porta 10002.\n * Questo esempio si connette e stampa la situazione portafoglio e l'elenco degli ordini.\n * Poi fa un esempio di send di un comando trading,per sicurezza è stato inserito un comando che non fa NULLA.\n * Dopo aver mandato il comando si otterrà la risposta a video e si chiuderà la connessione e terminerà il programma.\n * \n * NB:avendo messo un comando NULLO ovviamente la risposta sarà NULLA,a video si visualizzerà un H(HeartBeat),\n * \u00a0\u00a0ma questa non è la risposta ma quello che passa in quel momento,cioè NULLA.\n * / \n\n public class TradingConnect{\n \u00a0Socket s; //il socket che utilizziamo per la connessione\n \u00a0PrintWriter pW; //fornisce i metodi print e println, che permettono di scrivere qualunque dato Java, convertendolo automaticamente in stringa.\n \u00a0BufferedReader bfr; //usa un buffer (memoria tampone) per memorizzare temporaneamente i caratteri da leggere/scrivere\n \u00a0int porta; //porta sul quale fare l'accesso\n \u00a0String host; //host sul quale fare l'accesso\n \u00a0Vector ordini=new Vector();\n\n \u00a0TradingConnect(int porta,String host){\n \u00a0\u00a0this.porta=porta;\n \u00a0\u00a0this.host=host;\n \u00a0}\n\n \u00a0/**\n \u00a0 * Connessione al socket.\n \u00a0 * creo il socket il printwriter e il buffer. \n \u00a0 /*\n \u00a0 private void Connessione(){\n \u00a0\u00a0try {\n \u00a0\u00a0\u00a0s = new Socket(host, porta);\n \u00a0\u00a0\u00a0pW = new PrintWriter(s.getOutputStream(), true);\n \u00a0\u00a0\u00a0bfr = new BufferedReader(new InputStreamReader(s.getInputStream()));\n \u00a0\u00a0\u00a0System.out.println("Connessione avvenuta");\n \u00a0\u00a0\u00a System.out.println(RLine());\n \u00a0\u00a0\u00a System.out.println(RLine());\n \u00a boolean state=true;\n \u00a System.out.println("Lista ordini");\n \u00a System.out.print("Caricamento");\n \u00a while(state){\n \u00a \u00aString line=RLine();\n \u00a \u00aif(line.startsWith("ORDER")){\n \u00a \u00a\u00aSystem.out.print(".");\n \u00a \u00a\u00aordini.add(line);\n \u00a \u00a}\n \u00a \u00a else if(line.startsWith("ERR")){\n \u00a \u00a\u00aSystem.out.println(line);\n \u00a \u00a\u00astate=false;\n \u00a \u00a}\n \u00a \u00a else\n \u00a \u00a state=false;\n \u00a }\n \u00a System.out.println(".");\n \u00a int i=0;\n \u00a while(i \n \u00a \u00a System.out.println(ordini.get(i));\n \u00a \u00a i++;\n \u00a }\n\n \u00a System.out.println("end Lista");\n \u00a } catch (Exception e) {\n \u00a System.err.println("Unable to connect to the DataFeed: " + e );\n \u00a }\n \u00a }\n\n \u00a /**\n \u00a * Metodo per la chiusura della connessione.\n \u00a */\n \u00a private void closeConnection(){\n \u00a try {\n \u00a System.out.println("Chiusura in corso.");\n \u00a pW.close();\n ``` -------------------------------- ### Index Subscription Command Source: https://app1.directatrading.com/trading-api-directa/index.html Example of a subscription command for an index ticker (FMIB). This is a basic command to receive real-time index data. ```text SUB FMIB ``` -------------------------------- ### BOOK_5 Message Format Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of a BOOK_5 message record for the STLAM ticker, showing the first 5 levels of the order book. ```text BOOK_5;STLAM;16:26:09;17743;6;6.755;31230;6;6.75;36723;11;6.745;48250;14;6.74;56771;11;6.735;7600; 3;6.765;18795;8;6.77;15358;8;6.775;21212;10;6.78;12522;5;6.785 ``` -------------------------------- ### STOCK Message Example (STLAM - Mixed Order Status) Source: https://app1.directatrading.com/trading-api-directa/index.html Example of a STOCK message for STLAM showing a mix of orders at Directa and the exchange. ```text STOCK;STLAM;10:03:16;0;1;1 > 1;0.0;; ``` -------------------------------- ### Example Infostock Response Source: https://app1.directatrading.com/trading-api-directa/excel.html Illustrates the format of the response data returned by the =Infostock() command, showing ticker, time, and quantity details for each holding. ```Text STLA | 17:25:53 | 0 | 0 | 1 | 0 ``` -------------------------------- ### Order Entry Error Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of an error message for a buy order of 10 STLAM shares at 200, indicating the order cannot be placed due to excessive price deviation. ```text TRADERR;STLAM;ORD001;1012;ACQAZ;10;200;L'ORDINE NON PUO' ESSERE INOLTRATO PER SCOSTAMENTO DI PREZZO TROPPO ELEVATO RISPETTO AI VALORI DI MERCATO ``` -------------------------------- ### BOOK_20 Message Format Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of a BOOK_20 message record for the STLAM ticker, offering the most extensive order book data with the highest number of price levels. ```text BOOK_20;STLAM;11:35:42;1766;3;18.47;1901;2;18.468;982;2;18.466;1291;2;18.464;4062;4;18.462; 16008;4;18.534;2040;3;18.536;1241;2;18.538;765;2;18.54;1285;2;18.542 ``` -------------------------------- ### BOOK_15 Message Format Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of a BOOK_15 message record for the STLAM ticker, providing a deeper view of the order book with more price levels than BOOK_10. ```text BOOK_15;STLAM;11:35:32;3172;5;18.48;1906;3;18.478;3993;5;18.476;34141;4;18.474;1901;2;18.472; 1506;2;18.524;651;1;18.526;5651;2;18.528;5851;3;18.53;7599;5;18.532 ``` -------------------------------- ### Example Order Modification with POINTUPDATEORDER Source: https://app1.directatrading.com/trading-api-directa/index.html Shows modifying an existing order and receiving the subsequent automatic update packet, reflecting the change in order details. ```text MODORD ORD1,5.65 TRADOK;STLAM;ORD1;3000;ACQAZ;1;5.65;0.0;0.0;0;0;S4216523407947 **BEGIN UPDATEORDER UORDER;STLAM;16:52:34;ORD1;ACQAZ;5.65;0.0;1;`2006`;0.0;0.0;0;S4216523407947 USTOCK;STLAM;16:52:34;0;0;1;0.0; UAVAILABILITY;16:52:34;45.19;45.19;0.0;0.0;50.84 UINFOACCOUNT;16:52:34;47511;50.84;0;0.0 END UPDATEORDER** ``` -------------------------------- ### BOOK_10 Message Format Example Source: https://app1.directatrading.com/trading-api-directa/index.html Example of a BOOK_10 message record for the STLAM ticker, detailing buy and sell order book information across multiple price levels. ```text BOOK_10;STLAM;11:31:14;1445;2;18.456;3635;5;18.454;1045;2;18.452;2500;10;18.45;645;1;18.448; 2908;4;18.482;3215;4;18.484;2015;3;18.486;2839;3;18.488;4450;6;18.49 ``` -------------------------------- ### Order Submission with UPDATEORDER Enabled Source: https://app1.directatrading.com/trading-api-directa/index.html Example of submitting a purchase order with the UPDATEORDER command enabled, triggering order confirmation and related updates. ```text ACQAZ ORD172001,LX.EURUSD,10,1.11941 ``` -------------------------------- ### Example Order Revocation with POINTUPDATEORDER Source: https://app1.directatrading.com/trading-api-directa/index.html Illustrates revoking an order and receiving the final automatic update packet, reflecting the order's status after revocation. ```text REVORD ORD1 TRADOK;STLAM;ORD1;3002;ACQAZ;1;5.65;0.0;0.0;0;0;S4216523407947 **BEGIN UPDATEORDER UORDER;STLAM;16:52:34;ORD1;ACQAZ;5.65;0.0;1;2004;0.0;0.0;0;S4216523407947 USTOCK;STLAM;16:52:59;0;0;;0.0; UAVAILABILITY;16:52:59;50.84;50.84;0.0;0.0;50.84 UINFOACCOUNT;16:52:59;47511;50.84;0;0.0 END UPDATEORDER** ```