Friday 10 November 2017

Matlab Trading Indicatori


MetaTrader 5 - Examples. MetaTrader 5 e MATLAB Interaction. My prima interazione articolo tra il MetaTrader 4 e MATLAB Virtual Engine MATLAB macchina è stato notato da MQL-comunità Alcuni lettori 1Q2W3E4R5T sono stati anche in grado di spostare il progetto da Borland per VS2008 Ma il tempo corre in avanti senza sosta e triste ma vero MetaTrader 4 sta scomparendo, lasciando il posto al suo successore MetaTrader 5 con MQL5, che ha introdotto puntatori e memory. Thanks dinamici a queste innovazioni, abbiamo la possibilità di scrivere una biblioteca universale di interazione con MATLAB Engine macchina virtuale, e direttamente librerie di collegamento, generati da MATLAB, con MetaTrader 5 questo articolo copre una tale funzionalità questo articolo continua logicamente precedente e copre il problema di interazione tra MetaTrader 5 e MATLAB. To rendere la portata di questo articolo più comprensibile ai lettori non preparati più a fondo, abbiamo dividerà in tre parti teoria, teoria di riferimento e la pratica riguarderà i tipi di dati utilizzati in MQL5 e MATLAB, così come la loro conversione reciproca in riferimento imparerete le strutture linguistiche e la sintassi delle funzioni, necessarie per creare una DLL e in pratica analizzeremo insidie ​​di questo interaction. Experienced lettori possono saltare Teoria e di riferimento, e iniziare con la pratica Altri sono invitati a leggere Teoria e di riferimento, e solo allora procedere alla pratica anche s vale la pena di leggere i libri citati nella letteratura section.1 1 tipi di dati in MATLAB e MQL5.1 1 1 semplice Types. First dati di tutto, abbiamo bisogno di fare la conoscenza con i mondi interiori di MQL5 e MATLAB dopo l'ispezione superficiale dei tipi di variabili, si può concludere che essi sono quasi identical. Table 1 dati tipi di MATLAB e MQL5.There è una grande differenza delle variabili in MQL5 possono essere semplici o complesse composito e in MATLAB tutte le variabili sono complessi multidimensionale - cioè matrice Si deve sempre ricordare su questo difference.1 1 2 complesso dati Types. In MQL5 ci sono 4 tipi complessi di matrici di dati, le stringhe, le strutture e le classi tipo di dati complesso è situato di diversi tipi di dati semplici, uniti in blocco di memoria di certa lunghezza Quando si tratta di tali dati è sempre necessario conoscere sia la dimensione del blocco di memoria in byte, o numero di elementi tranne le classi Siamo interessati solo a array e stringhe, perché la presentazione delle classi e strutture MQL5 a MATLAB non fa sense. When passaggio di array di qualsiasi tipo è necessario conoscere il tipo di dimensione e numero di elementi utilizzando la funzione di arraysize particolare attenzione dovrebbe essere dato l'indicizzazione in MetaTrader 5 - di solito è al contrario, vale a dire il primo elemento contiene dati più recenti rispetto al successivo controllo di questo si utilizza la funzione ArrayIsSeries e MATLAB è il seguente indicizzare il primo elemento contiene i dati più vecchi di quello successivo - quindi è necessario invertire il vostro array prima di inviarli al MATLAB, se ASSERIES bandiera TRUE sulla base di quanto sopra, lasciare s d'accordo con la seguente. array Reverse invisibile a MQL5 programmi, ad eccezione di array di tipo char e gli array a 2 dimensioni - lasciano loro unchanged. Reverse invisibilmente tutti gli array da MATLAB, e assegnare la bandiera ASSERIES con vera, fatta eccezione per gli array di tipo char e 2- matrici tridimensionali - li lasciano unchanged. In ogni matrice in MQL5 programma, creato in base alle all'indietro indicizzazione, la bandiera ASSERIES deve essere vero, tranne che per gli array di tipo char e gli array a 2 dimensioni - lasciarli unchanged. But questo non è il unica limitazione quando si lavora con gli array quando si lavora con array multidimensionali, o matrici per essere più corretti, in particolare da MATLAB, si introduce la restrizione per non più di 2 array bidimensionali Qui la bandiera ASSERIES non può essere vero, e pertanto tali matrici non siamo reversed. Don dimenticare che le stringhe in MQL5 non sono array di elementi di tipo char Così, quando passa stringhe arriva un piccolo problema in MQL5 stringhe codificate utilizzando Unicode, e MATLAB utilizza la codifica ANSI Quindi, prima si passa una stringa, deve essere convertito in serie di caratteri ANSI utilizzando la funzione e viceversa StringToCharArray, quando si ottiene un array di caratteri da MATLAB, convertirlo usando la funzione CharArrayToString vedi Tabella 2 Per evitare confusione, d'accordo memorizzare tutte le stringhe in MQL5 programmi utilizzando Unicode, non array di tipo char .1 2 Confronto di MQL5 e dell'ordine MATLAB dati Types. In per ridurre la quantità di funzioni e di semplificare l'algoritmo biblioteca, sarà possibile ridurre la quantità di tipi mediante conversione automatica, che non dovrebbe compromettere l'integrità dei dati la seguente tabella illustra la regola di conversione del tipo di dati da MQL5 in MATLAB. Con questo tipo di conversione vi è una perdita di precisione Noi non usarlo, ma è possibile utilizzare tale conversione in programs. Table 2 Confronto di MQL5 e MATLAB dati Types. Now si ha familiarità con i tipi di dati utilizzati in MQL5 e MATLAB È sai cosa insidie ​​attendono di passaggio di dati e su come aggirare loro competenza Hai ancora sapere MATLAB API del motore e familiarizzare con MATLAB Compiler 4.2 MATLAB Engine API Reference, MATLAB Compiler 4 Riferimento e C Input Output sezione Biblioteca Reference. This si presenta al le funzioni più importanti di MATLAB API del motore, caratteristiche di MATLAB Compiler 4 e numero di funzioni utili di libreria di output standard input C Allora, s begin.2 1 MATLAB API del motore e MCR Functions. MATLAB motore - è interfaccia esterna che consente di altri programmi a utilizzare MATLAB tavolo fornisce un lavoro completamente funzionale di tutti i pacchetti MATLAB senza restrictions. Although non è detto nella documentazione, ma in termini di programmatore di sistema - è solo una macchina virtuale, come PHP, MySQL, ecc che supporta una semplice e relativamente modo rapido per lo scambio di dati tra MetaTrader 4 5 e il metodo MATLAB. This di collegare programmi esterni con il pacchetto MATLAB è raccomandato dagli sviluppatori l'interfaccia è composta da sei functions. Engine Peng engOpen NULL questa funzione chiamate MATLAB desktop, il parametro è sempre NULL, restituisce un puntatore al descriptor. int scrivania exitCode engClose motore Peng questa funzione chiude desktop, restituisce il numero di restanti utenti di MATLAB desktop, puntatore where. Engine Peng al desktop descriptor. mxArray Mxvector mxCreateDoubleMatrix int m, int n, int ComplexFlag questa funzione crea una matrice variabile di MATLAB desktop, restituisce un puntatore alla matrice variabile, puntatore where. mxArray Mxvector a matrix numero variable. int m di rows. int numero n di columnsplexFlag tipo di numero complesso, per MetaTrader 4 5 mxREAL. void mxDestroyArray mxArray Mxvector questa funzione distrugge matrice MATLAB, è necessario per cancellare la memoria, where. mxArray Mxvector puntatore alla matrice variable. int engPutVariable motore Peng, nome char, mxArray Mxvector questa funzione invia variabile al desktop è necessario non solo creare variabili del tipo mxArray, ma inviarli anche a MATLAB, puntatore where. Engine Peng al desktop descriptor. char nome nome di variabile di tipo char puntatore MATLAB desktop. mxArray Mxvector alla matrice variable. mxArray Mxvector engGetVariable motore Peng, nome char questa funzione diventa variabile da tavolo - l'inverso della funzione precedente sono accettate solo le variabili di tipo mxArray, puntatore where. mxArray Mxvector alla matrice puntatore variable. Engine Peng al desktop descriptor. char nome nome di variabile di tipo char in MATLAB desktop. double p mxGetPr mxArray Mxvector questo la funzione ottiene puntatore a matrice di valori, viene utilizzato per copiare i dati insieme a memcpy vedere 2 3 C standard Input Output Biblioteca, puntatore p where. double alla gamma del doppio puntatore type. mxArray Mxvector alla matrice variable. int engEvalString motore Peng, char comando questa funzione invia i comandi a MATLAB desktop, puntatore where. Engine Peng al comando comando del desktop descriptor. char per MATLAB, stringa del char type. You probabilmente notato che l'API del motore MATLAB permette di creare la struttura mxArray solo per il doppio tipo ma questa restrizione non riguarda le vostre possibilità, ma interesserà l'algoritmo dell'istanza library. MCR MCR è la biblioteca speciale del pacchetto di MATLAB, che permette di eseguire le applicazioni standalone biblioteche pubbliche, generati da MATLAB su qualsiasi computer nota, che anche se si dispone di un pacchetto completo di MATLAB, è comunque necessario installare la libreria MCR da file si trova nella cartella Win32 compilatore implementare MATLAB Toolbox Così in esecuzione, prima di chiamare qualsiasi funzione biblioteca pubblica, creato da ambiente MATLAB, è necessario chiamare la funzione MCR di inizializzazione. bool mclInitializeApplication opzione const char, int count restituisce TRUE se inizio MCR ha avuto successo, altrimenti FALSE, where. const char stringa di opzione di opzioni, come in MCC - R di solito è stringa di opzioni di formato di conteggio NULL. int, tipicamente 0.On fine pubblico lavoro biblioteca è necessario chiamare bool mclTerminateApplication vuoto restituisce TRUE se MCR era successo closed.2 2 MATLAB Compiler 4.MATLAB Compiler consente di creare la seguente dalle applicazioni M-functions. Standalone che corrono, anche se non è MATLAB biblioteche condividono installed. CC, che può essere utilizzato senza MATLAB su systemspiler utente finale supporta la maggior parte dei comandi e pacchetti di MATLAB, ma non tutta la lista completa delle restrizioni si possono trovare sul sito web MATLAB Questo metodo consente di creare un software indipendente dal fascio di MetaTrader 5 e MATLAB, ma a differenza del motore di MATLAB, richiede un programmatore ben addestrato e profonda conoscenza del compilation. MATLAB compilatore richiede almeno uno dei seguenti CC compilers. Lcc C viene di solito con MATLAB e 's solo le versioni C compiler. Borland C 5 3, 5 4, 5 5, 5 6.Microsoft versioni CC visivi 6 0, 7 0, 7 1.MATLAB compilatore 4, in contrasto con i suoi predecessori, genera solo il codice involucro interfaccia, cioè non si traduce funzioni m in codice binario o CC , ma crea un file speciale basato sulla tecnologia dei componenti della tecnologia CTF File, che include integrazioni di vari pacchetti, necessari per supportare funzioni m MATLAB Compiler cifra anche questo file con unico irripetibile 1024 bit key. Now lasciare s considerano l'algoritmo di MATLAB Compiler 4 lavoro, dal momento che l'ignoranza di questo tema porterà a molti errori stupidi a analisi time. Dependencies compilazione in questa fase di determinare tutte le funzioni, MEX-files e P-files, che compilati m-funzioni dipendono archivio on. Creating - CTF-lima viene creato, è crittografato e compressed. Generating il codice oggetto di involucro in questa fase sono stati creati tutti i codici sorgente, necessaria per component. CC codice di interfaccia m-funzioni specificate nel file cponent NameFilemain riga di comando che contiene tutte le informazioni necessarie per eseguire il m-codice incluse le chiavi di crittografia e sentieri, memorizzati nella traduzione CTF-file. CC a questo fonte CC fase file di codice vengono compilate in oggetto files. Linking La fase finale del progetto building. Now, quando si ha familiarità con il comportamento algoritmo di MATLAB Compiler , devi imparare di più su i tasti in modo da avere un piano dettagliato di azioni, quando si utilizza il compilatore mcc. Table 4 Matlab mbuild versione Linker 4 keys. Table 4 elenca i tasti principali per ulteriori informazioni utilizzare i comandi di aiuto mbuild o doc mbuild. 2 3 C standard Input Output Library. Using l'Input Output standard libreria fornisce i dati corretti copiando il suo utilizzo vi salverà da errori stupidi che si presentano durante la fase di progettazione del programma per esempio, molti programmatori alle prime armi copiare solo puntatore al blocco di memoria invece di copiare l'intero dal blocco di memoria intera libreria Input Output siamo interessati solo in una function. void PIN memcpy vuoto Pin, Pout vuoto, int nSizeByte questa funzione copia cloni gamma variabile da Pout al pin con dimensioni di byte nSizeByte, where. void puntatore pin a matrice, dove copy. void puntatore Pout a matrice, da cui copia è made. int nSizeByte la dimensione dei dati copiati, non deve superare la dimensione della matrice PIN, altrimenti errore di accesso alla memoria occur. Now abbiamo finito con la teoria e possiamo procedere alla realizzazione di MetaTrader 5 MATLAB interaction. As probabilmente indovinato, questo sarà fatto in due modi: utilizzando MATLAB motore di macchina virtuale e utilizzando librerie generati da MATLAB Compiler in primo luogo, prendere in considerazione un modo semplice, veloce e versatile di interazione tramite MATLAB Engine. This parte di un articolo deve essere letto dall'inizio alla fine, come, nonostante la differenza apparente tra i metodi di interazione, hanno una filosofia e la sintassi familiare di costrutti del linguaggio, e per imparare qualcosa di nuovo è più facile con semplice examples.3 1 Sviluppare Biblioteca universale dei metodo MetaTrader 5 MATLAB motore Interaction. This di interazione può t essere chiamato elegante e veloce, ma è il più affidabile e copre l'intero pacchetto MATLAB Naturalmente, dobbiamo ricordare la velocità di sviluppo del modello finale l'essenza dello sviluppo è quello di scrivere un biblioteca universale-wrapper per MetaTrader 4 interazione del motore 5 MATLAB Dopo questo MetaTrader 4 5 copione indicatore esperto in grado di gestire MATLAB desktop virtuale e l'intero algoritmo matematico può essere memorizzata in MQL programma come stringhe, in modo da poter usare per proteggere la proprietà intellettuale per maggiori dettagli si veda il Yourselves Protect, articolo sviluppatori può anche essere memorizzato in m-funzioni o P-funzioni file separati in MetaTrader 5 MQL5 biblioteche aree folder. Possible di applicazione di tale interaction. To test o dimostrare modelli matematici idee senza dover scrivere programmi complessi tutela della proprietà intellettuale possono essere disposti come in MQL-programma e per mezzo di pacchetto MATLAB - utilizzando P-functions. To scrivere complessi modelli matematici che utilizzano tutte le funzioni di MATLAB. To tutti coloro che non stanno per distribuire i loro indicatori di script experts. Let s procedere Spero di aver letto le 1 1 tipi di dati in MATLAB e MQL5 1 2 Confronto di MQL5 e MATLAB tipi di dati 2 API del motore e MCR funzioni MATLAB 1 e 2 3 sezioni biblioteca Input Output C standard, come vedremo non mettere in pausa e analizzarli più leggere attentamente il seguente blocco-schema, che illustra l'algoritmo di futuro library. Figure 1 Block-schema di biblioteca Algorithm. As visto in figura 1, la biblioteca è costituito da tre blocchi principali considerare il loro blocco purposes. MQL5 , preparazione preliminare di Sent ricevuto data. Reverse arrays. Types conversion. Strings codifiche conversion. Converts matrice nella mxArray structure. Passes MATLAB motore commands. MATLAB calcoli blocco motore system. Now, lasciare s trattare con algoritmi Noi ll iniziamo con MQL5 blocco attento lettore ha già notato che si concentrerà sulla realizzazione di ciò che era scritto in quei tipi di dati nella sezione MATLAB e MQL5 Se abbia perso, è ll fatica a capire perché tutto questo è necessary. Algorithm delle funzioni tipoVariabile mlInput è lasciato quasi identico s discutere il proprio lavoro utilizzando la funzione di mlInputDouble che fornisce l'input di variabili della doppia tipo di MATLAB virtuale machine. bool mlInputDouble doppio array, int sizeArray, stringa NameArray where. array riferimento alla variabile o matrice del doppio type. sizeArray numero di dimensioni gamma di elementi, non stringa bytes. NameArray, contenenti unico nome di variabile per MATLAB nome della macchina virtuale devono corrispondere a stringa MATLAB requirements. Convert NameArray a char array utilizzando il StringToCharArray function. Check il tipo di indicizzazione utilizzando la funzione di ArrayIsSeries Se il tipo di indicizzazione è normale passare valore alla funzione di mlxInputDouble ELSE indicizzazione dei timeseries serie invertire array e passare il valore alla funzione mlxInputDouble function. End, passare il valore restituito al mlxInputDouble function. Algorithm delle funzioni tipoVariabile mlGet è anche quasi identico sia s discutere il suo lavoro con il funzione mlGetDouble, che restituisce variabile del tipo a doppio da MATLAB virtuale machine. int mlGetDouble doppio array, int sizeArray, stringa NameArray where. array riferimento alla variabile o matrice di numero doppio gamma type. sizeArray dimensione degli elementi, non stringa bytes. NameArray , contenente unico nome della variabile per MATLAB virtuale stringa machine. Convert NameArray a char array utilizzando il StringToCharArray function. Find la dimensione della matrice utilizzando la dimensione mlxGetSizeOfName function. If è superiore a zero allocare la matrice destinatario di dimensioni necessarie utilizzando la funzione di ArrayResize, ottenere dati dell'array mlxGetDouble ritorno dimensione size. if è pari a zero l'errore di ritorno, vale a dire nulla value. That è tutto Le funzioni mlGetInt e mlGetLogical producono conversione ombra di tipi doppie - int bool a tal fine queste funzioni creano un buffer di memoria temporanea nei loro corpi questo è una misura forzata, perché purtroppo MATLAB API non consente di creare strutture mxArray per tipi di dati diversi doppia Tuttavia, questo non significa che MATLAB opera esclusivamente il blocco doppia types. CC è molto più facile - dovrebbe fornire la traduzione dei dati dal tipo double nella struttura mxArray viene fatto usando il mxCreateDoubleMatrix mxGetPr e funzioni memcpy Quindi, utilizzando la funzione engPutVariable passa i dati di MATLAB macchina virtuale e per estrarre i dati che utilizza la funzione engGetVariable Anche in questo caso, prestare attenzione alle funzioni con prefissi Int e logico come si è visto nel blocco-schema, don t interagire direttamente con MATLAB, ma utilizzare il mlxInputDouble mlxGetDouble e mlxInputChar funzioni dell'azionamento Algoritmo del loro comportamento è semplice richiamo dei valori di uscita di ingresso funzione mlxInputDouble mlxGetDouble il doppio e inviare il comando ombra MATLAB per convertire il tipo di dati via il blocco motore mlxInputChar function. MATLAB è ancora più facile esso fornisce solo le funzioni matematiche il suo comportamento dipende dalla vostra comandi e la vostra m p-functions. Now, quando tutti i dettagli del progetto sono chiari, è ora di affrontare progetto building. Any come costruire inizia con la creazione di biblioteca principale nel nostro caso si tratta di blocco CC a tale scopo, in qualsiasi editor di blocco note ANSI-text, Bred, ecc creare un file con l'estensione DEF E 'auspicabile che il nome di questo file è costituito da Latina caratteri senza spazi e la punteggiatura, altrimenti si ascoltare molte parole lusinghiere per il vostro compilatore questo file fornisce la permanenza delle vostre funzioni Se questo file è assente, CC compilatore inventare il proprio nomi esotici di esportare file di funzioni. Questo contiene parola di controllo biblioteca, nome LibMlEngine della biblioteca, e le esportazioni seconda parola di controllo, poi vengono i nomi delle funzioni Come probabilmente si sapeva, i nomi delle funzioni di esportazione possono t avere spazi e la punteggiatura Ecco il testo del file da archive. LIBRARY LibMlEngine eSPORTAZIONI mlxClose mlxInputChar mlxInputDouble mlxInputInt mlxInputLogical mlxGetDouble mlxGetInt mlxGetLogical mlxGetSizeOfName mlxOpen. So, abbiamo il primo file di progetto Ora aprire Windows Explorer e passare al MATLAB Esterno includono cartella Copiare il file file di intestazione motore h di MATLAB macchina virtuale alla cartella, dove progetto è costruito se ha vinto t fare questo, sarà necessario specificare manualmente il percorso del file in fase di compilation. Now s tempo per creare blocco CC Noi non includere l'intero codice sorgente del programma in questo articolo, perché questo file può essere trovato in come ed è ben commentato nota che s meglio per creare funzioni utilizzando convenzione stdcall cioè parametri sono passati attraverso lo stack, e la funzione pulisce lo stack Questo standard è nativo per Win32 64 API. Consider come dichiarare un declspec dllexport function. extern C tipoVariabile stdcall tipo di funzione name. extern C declspec dllexport dice compilatore C che la funzione è external. variabletype tipo di variabile restituito, può essere vuoto, bool, int, tipi compositi doppi noti non solo per Dll, ma anche a chiamare il programma e pointers. stdcall dichiarazione circa il passaggio di parametri di funzionare e indietro, si sa standard per Win32 64 API. Funcion la funzione name. type tipo di nome e il nome della variabile di ingresso, numero massimo di variabili è 64.CC building block per questo è necessario includere l'uscita standard input biblioteca e aggiungere al progetto i seguenti file nel vostro compilatore Project - Aggiungere Project. In MATLAB Esterno cartella lib compilatore Win32 64, in cui la cartella principale MATLAB MATLAB Win32 cartella 64 o Win32 per 32 bit del sistema operativo, o Win64 a 64 bit del sistema operativo compilatore la cartella di Borland per Borland CC ver 5-6, la cartella di Microsoft per Microsoft Visual CA domanda comune come questo può verificarsi ho diversa versione di compilatore o tale un compilatore nella lista Molto raramente ci sono tali file Let s vedere come manualmente creare una biblioteca pubblica Noi prenderemo in considerazione come s fatto in Visual C e in Borland C. In FAR aperto MATLAB Bin Win32 64 cartelle, in cui la cartella principale MATLAB MATLAB Win32 64 o cartella Win32 per 32 bit del sistema operativo, o Win64 a 64 bit OS. For Borland C entrare IMPLIB lo stesso for. For Visual C entrare lib lo stesso for. If altro compilatore qualsiasi compilatore di qualsiasi linguaggio di programmazione deve avere questa utility - Library manager, di solito questo è un compilatore programma di console folder. By la strada, ho dimenticato di avvertirti - don t cercare di fare a 64 bit LIB per 32-bit compilatore in primo luogo, scoprire se c'è il supporto di indirizzamento a 64 bit in aiuto compilatore in caso contrario, sia alla ricerca di 32 bit MATLAB DLL o selezionarne un altro CC compilatore Scendendo alla compilazione, al termine del quale si ottiene una biblioteca, che dovrebbe essere inserito nella terminalfolder MQL5 biblioteche folder. Now Sia s iniziare con MQL blocco Run MetaEditor, fare clic su Nuovo e fare come il seguente figures. Figure 2 MQL5 guidata Creare biblioteca. figure 3 MQL5 guidata Proprietà generali di Library. Now, quando guidata MQL5 ha creato un modello, procedere alla sua editing. Note che MQL 5 è possibile passare puntatori in due ways. void NameArray Questo metodo di passare dalla serie permette solo di leggere i dati Tuttavia, se si tenta di utilizzare questo riferimento per modificarne il contenuto, si otterrà l'errore di accesso alla memoria nel migliore dei casi per voi, MetaTrader 5 sarà tranquillamente gestire l'errore nella SEH-frame, ma noi rifugio t scrivere un SEH-frame, in modo che possiamo anche perdere la ragione di NameArray error. void Questo metodo di passaggio consente di leggere e modificare i contenuti della matrice, ma è necessario conservare gamma funzione size. if doesn t accettare o doesn t passare parametri, specificare sempre il type.2 vuoto abbiamo vinto t descriviamo tutte le funzioni del blocco MQL, perché si possono trovare il codice sorgente in. Therefore, abbiamo ll consideriamo i dettagli della dichiarazione e definizione delle funzioni esterne in MQL5.As visto nell'esempio, la dichiarazione e la definizione della funzione sono combinati in questo caso, si dichiara una funzione denominata mlInputChar come l'esportazione esterno, che restituisce valore del tipo bool e accetta la stringa array come parametro Ora compile. Now che abbiamo completato l'ultimo blocco della biblioteca e compilato, è ora di testarlo in real conditions. To fare questo, scrivere uno script di test semplice o prendere dal codice file. Script è semplice e ben commented. As visto dallo script, stiamo entrando valori, e quindi ottenere valori Tuttavia, a differenza di MetaTrader 4, dove abbiamo bisogno di conoscere la dimensione del buffer in fase di progettazione, in MetaTrader 5 non s necessario, come si usa buffers. Now dinamica che si ve finalmente capito MATLAB macchina virtuale, è possibile iniziare a utilizzare DLL costruito in MATLAB environment.3 2 linee guida tecniche di costruzione utilizzando DLL generata da MATLAB Compiler 4.In sezione precedente si ve imparato a creare una libreria per l'interazione universale con il pacchetto MATLAB Tuttavia, questo metodo ha uno svantaggio - richiede il pacchetto MATLAB da utente finale questa restrizione crea un serie di difficoltà nella distribuzione di prodotti software finito che per questo pacchetto matematico MATLAB è un built-in del compilatore, che permette di creare applicazioni standalone indipendenti dal pacchetto MATLAB sia s un'occhiata a it. For esempio, si consideri un semplice indicatore - in movimento media SMA leggermente aggiornamento con l'aggiunta di una rete neurale filtro GRNN, che permette di lisciare rumore bianco esplosioni casuali un nome il nuovo indicatore di come NeoSMA e filtro come GRNNFilter. Thus abbiamo due funzioni m, di cui vogliamo creare una DLL, che può essere chiamato da MetaTrader 5.Now ricordare che il MetaTrader 5 ricerche DLL fro in seguito folders. terminaldir MQL5 Libraries. Current folder. System SYSTEM32.Directories cartella windowsdir elencati nell'ambiente del sistema PATH. Therefore variabile, mettere in una di queste directory due m-funzioni NeoSMA m e GRNNFilter m, dove costruiremo DLL Vorrei attirare la vostra attenzione su questo fatto di posizionamento, come questo viene fatto non per lettore attento incidente già conosce la funzione compilatore MATLAB - conserva i percorsi durante la compilazione di vedere 2 2 MATLAB Compiler 4.Before si inizia a compilare progetto, è necessario configurare compilatore per fare questo, attenersi alla seguente riga di comando steps. In MATLAB entrare mbuild - setup. Press y per confermare la scoperta di compilatori compatibili CC installati nel vostro standard system. Choose Lcc - win32 C compiler. Press Y per confermare selezionato compiler. Figure 4 Compilare il project. Now siamo pronti per passare al m-funzioni compilazione process. mcc - N - W lib NeoSMA - T collegamento lib NeoSMA m GRNNFilter m. Explain le chiavi .-N per saltare tutti i percorsi necessari - W lib NeoSMA racconta compilatore che NeoSMA è il nome della libreria di collegamento - T lib dice compilatore per creare una biblioteca pubblica con il collegamento NeoSMA m e GRNNFilter m m-funzioni names. Now, lasciate s vedere cosa compilatore ha creato. log-file contenente la versione compilatori actions. NeoSMA c C della biblioteca contiene - Code di involucro. il file CTF vedere 2 2 MATLAB Compiler file di intestazione h 4 section. NeoSMA contiene dichiarazioni di biblioteche, funzioni, costanti. file sorgente file oggetto contenente macchina e pseudo codice. funzioni esportate nomi. DLL per ulteriori collegamenti. Dll da utilizzare in CC projects. NeoSMAmcccomponentdata versione c C sulla componente utilizzato per la conformità con CTF file, contiene i percorsi, ecc versione oggetto del file sorgente componente che contiene la macchina e pseudo code. So lasciare s Maneggiare con DLL, proprio con la sua struttura interna Si compone di funzioni di base unica funzione from. Main di qualsiasi DLL - BOOL WINAPI DllMain che in base alle specifiche Microsoft gestisce gli eventi che si verificano in DLL caricamento della DLL nello spazio di indirizzi del processo, la creazione di un nuovo flusso, eliminando il flusso e scaricare DLL da memory. Service sono necessarie funzioni di inizializzazione DLL deinizializzazione BOOL NameLib inizializzazione void void NameLib Termina vuoto per iniziare a scaricare ambiente Math lavoro prima di utilizzare le funzioni di libreria e alla fine della loro use. Exported funzioni m vuoto MLF NameMfile int numberofreturnvalues, returnvalues ​​mxArray, inputvalues ​​mxArray, dove. numberofreturnvalues ​​numero di variabili rispose don t confondere con la dimensione dell'array, etc. mxArray returnvalues ​​indirizzo della struttura mxArray in cui i risultati del lavoro m-funzione sarà returned. mxArray puntatore alla struttura inputvalues ​​mxArray di ingresso m-funzione variable. As si può vedere , esportati funzioni m contengono indirizzi e puntatori alla struttura mxArray, e si può t direttamente chiamare queste funzioni da MetaTrader 5, in quanto non comprendere questo tipo di dati abbiamo vinto t descriviamo struttura mxArray in MetaTrader 5, perché gli sviluppatori di MATLAB non garantiamo che non cambia nel tempo, anche all'interno della stessa versione del prodotto, quindi è necessario scrivere un semplice blocco-schema DLL-adapter. Its è mostrato below. Figure 5 DLL adattatore Block-Scheme. It è molto simile a sul lato destro della DLL per MATLAB motore, così abbiamo vinto t parsing il suo algoritmo e procedere direttamente al codice per fare questo, creare due file di piccole dimensioni in CC compiler. LIBRARY nnSMA ESPORTAZIONI IsStartSMA nSMA. Build il progetto nel vostro compilatore CC per questo è necessario includere libreria di output standard input e aggiungere al progetto i seguenti file nel vostro compilatore Project - Aggiungere Project. In MATLAB Esterno lib win32 64 cartella compilatore, in cui la cartella principale MATLAB MATLAB Win32 64 o cartella Win32 per 32 bit del sistema operativo, o Win64 per il compilatore OS a 64 bit nella cartella di Borland per Borland CC ver 5-6, la cartella di Microsoft per Microsoft Visual CI hanno file per la versione 6. Creare vedere manualmente 3 1 Sviluppare Biblioteca universale dei MetaTrader 5 MATLAB motore interaction. The scorso, quello che ho voglio dirvi in ​​questa sezione, è di circa file necessari durante lo spostamento del progetto su un altro computer, dove non c'è MATLAB installed. Here è un elenco di file e percorsi sul computer di destinazione. ogni installatore MCR cartella. qualsiasi cartella per installatore MCR. qualsiasi cartella per installatore MCR. qualsiasi cartella per installatore MCR. terminaldir MQL5 biblioteche. terminaldir MQL5 biblioteche. terminaldir MQL5 Libraries. Many avanzata programmatori hanno già indovinato, che si consiglia di utilizzare un programma di installazione SETUP Ci sono molti di loro su Internet, tra cui products. Now gratuito dobbiamo verificare questa DLL in MetaTrader 5 Per fare questo scriveremo un semplice script da the. So, si sa come creare una biblioteca universale per MetaTrader 5 interazione MATLAB, e come collegare DLL costruito in ambiente MATLAB ma ancora ci sono interfacce di interazione MetaTrader 5 MATLAB per essere descritte, ma questo è al di là del scopo di questo articolo L'argomento di questo articolo è coperto in dettaglio io ho scelto i modi più efficaci di interazione, che non richiedono un particolare tipo di adattatori Anche se si può andare in un altro modo, come ad esempio la tecnologia - come esportare citazioni da MetaTrader 5 per le applicazioni utilizzando lettori WCF Services. Many può avere una domanda quale metodo per scegliere la risposta è semplice - sia, perché durante la messa a punto di progettazione del modello matematico la velocità non è necessaria, ma che sarà necessario tutta la potenza di MATLAB, senza i costi di produzione speciali per MATLAB di programmazione motore aiuterà qui, naturalmente Tuttavia, quando il modello matematico è debug e pronto per l'uso, è ll bisogno di velocità, multitasking lavoro di indicatore e o sistema commerciale in diversi grafici dei prezzi - qui senza dubbio si ll bisogno di una DLL, costruita nel MATLAB environment. But tutto ciò non obbliga a seguire lo Ognuno darà la risposta a questa domanda se stesso, basandosi principalmente sulla percentuale dei costi di programmazione alla scala del numero di progetto di indicatori e o del sistema del commercio utenti del sito e non ha senso creare DLL in ambiente MATLAB per uno o due utenti che s più facile da installare MATLAB su due lettori computers. Many, che non hanno familiarità con MATLAB, probabilmente una domanda perché tutto questo MQL5 ha funzioni già matematiche la risposta è che l'uso di MATLAB vi permette di implementare facilmente le vostre idee matematiche, qui è solo un elenco parziale di algoritmo possibilities. dynamic della logica fuzzy nel indicatore e commercio o meccanico system. dynamic algoritmo genetico nella strategia dinamica algoritmo rete neurale tester. dynamic sistema commerciale meccanico nell'indicatore e commercio o meccanico system. three indicators. simulation dimensionale di gestione non lineare systems. So, tutto nelle vostre mani, e non dimenticare la matematica è sempre stata la regina delle scienze, e il pacchetto MATLAB è la vostra calculator. Translated scientifica da Russo, MetaQuotes Software Corp originale article. Bitfinex ha annunciato oggi l'avvio di contratti minerari come un prodotto di trading sulla loro piattaforma in totale 100 THS terahashes al secondo con una scadenza a 3 mesi sono stati resi disponibili per la negoziazione con il nome di TH1BTC le 100 THS sono parte di un più ampio pool of 3500 THS so more mining contracts might become available in the future Interestingly, this marks the first time that it is possible to short a mining contract. Shorting a mining contract means to receive an amount of Bitcoin now the price we sell it at and subsequently paying dividends in Bitcoin over the following 3 month until the contract expires in the middle of December A profit is made if the sum of all the dividends paid out plus the interest we paid to short the contract is less than what we received at the beginning when we sold the contract to someone else obviously. This means the price of TH1BTC should depend on 3 variables in decreasing order of importance. The change of the mining difficulty until 15 December. The time remaining until 15 December. The interest rate swap rate. If difficulty increases dividend payments become smaller because 1 THS represents a smaller fraction of the whole network hashing power Therefore the price of one contract should decrease if difficulty increases The closer we get to expiration the fever Bitcoins can be mind with 1 THS in total Therefore the price of one contract should decrease the closer we get to expiration and reach a price of 0 at expiration. The higher the interest rate the more costly it is to enter and keep the contract over the full length of 3 month Bitfinex does not offer 90 days swaps, therefore entering a contract with the goal to hold it until the end contains quite a bit of interest rate risk because at some point a new swap has to be taken out at a potentially unfavorable interest rate This is less of a problem when going long Bitcoin rates are typically low than when going short there is only a maximum of 100 contracts available in total, no naked shorting To compensate for the risk prices should increase when swap rates are increasing. The big unknown is of course the change in the mining difficulty over the next 90 days In the following figure we see how difficulty changed over the previous 6 month. The data is from Tradeblock and it shows not only a graphical representation of past changes in the difficulty difficulty changes every 14 days depending on past hash rate More info can be found in the wiki but also some basic summary statistics On average difficulty has increased 27 over the last 30 days and 77 over the last 60 days. To estimate the fair price of one TH1BTC we will assume that difficulty will increase on average 15 per month over the next 3 month Currently the price of buying one contract worth 1 THS is 2 BTC The pool fee is 3 and we will ignore interest rates Filling in all the information we get the following results. Hence if we go long one contract based on our assumptions we would make a loss of about 0 39 Bitcoin a bit more in reality since we will start mining in the middle of September until the middle of December because the expected dividends monthly revenue is not going to cover our initial costs of 2 BTC before the contract expires. On the other hand, going short at a price of 2 Bitcoin would have generated a profit of about 0 39 Bitcoin per contract Keep in mind that we didn t include swap costs which are currently at around 1 per day. There are two ways to look at the results Either we could say prices for TH1BTC are currently overvalued and should be closer to around 1 5 BTC If we assume difficulty will increase more than 15 per month then prices should be even lower than that Or we could say that the market is efficient and prices are correct, which would imply that the market is expecting difficulty to decrease on average about 2 per month over the next 90 days Either way, results will be known with certainty in 90 days. Struggling to recover from the most recent Bitcoin flash crash which originated on Bitfinex only four days go Bitcoin prices took another dive today as margin traders got their positions liquidated on BTC-e. The event started at 1 36 PM UTC 1 when large sell orders began to show up on the third largest western Bitcoin exchange BTC-e Downwards momentum increased steadily as the orderbook became increasingly thin, crashing prices to a low of USD 309 per Bitcoin at 1 43 PM In the following minutes prices rebounded swiftly on thin volume back to around USD 442 as arbitrage traders started to take advantage of the discount relative to other exchanges. BTC-e is one of the few large exchanges that offer margin trading to their clients via the MetaTrader platform since November 2013, but the details of who excactly provides the funds necessary for margin trading have remained unclear The shape and especially timing of the crash points towards margin traders being liquidated or stop orders being executed , similar to what happened on Bitfinex a couple of days ago However, unlike Bitfinex which is transparent about open swap positions BTC-e does not provide important data which would be needed to provide a more thorough analysis and so this last statement can only be considered a good guess. Unlike Bitfinex, which relies on a hidden algorithm in an effort to control the order flow BTC-e seems to have no special safeguards in place to mitigate such events The fall below 400 was mainly due to a lack of bids in the orderbook and not because the market believed that the true value was below 400, as the rebound back to over 440 only minutes later basically proved Hence, halting trading during extreme downwards volatility could have easily averted the bloodshed among margin traders by giving other market participants more time to thicken the orderbook. Update 4 58PM UTC 1 BrCapoeira posted on Reddit an interesting graph based on data from the Metatrader platform. This graph implies that a single large order was the cause of this event Whether this order was created due to a margin call, a simple mistake, to manipulate the market, or to open a large short position remains unclear Common sense would suggest that it was probably the result of a margin call of a single large trader. My previous post on this topic has been brought up during discussions in the aftermath of the most recent Bitcoin flash crash Coindesk was one of the first to pick it up and since then various posts about transparency and the possible responsibilty of exchanges to actively manage order execution started to appear As a result of those events Josh Rossi, Vice President of Business Development at Bitfinex, went on Reddit to openly address some of the issues brought up against the exchange. The facts we know for sure are that there were some large sell orders shortly before the crash started, for example a 500 sell order on Bitstamp at 9 49am UTC 1 , about 6 minutes before a large sell order on Bitfinex triggered the crash However, the data does not tell us whether it was insider trading, some form of market manipulation or a simple mistake. Fact is that after the Bitcoin flash crash open swap positions decreased from around 28m to 24m which indicates about 8400 margin long positions were closed assuming an average of 475 in one way margin call or another stop order hit The data does not tell us what the ratio is but according to Josh only about 650 Bitcoins were sold as the result of margin calls. As correctly pointed out by Jonathan Levin fact is that starting about 24 hours before the bitcoin flash crash until the crash itself an additional 1000 Bitcoins were taken out in short positions and about 2500 shorts were subsequently closed during the crash Whether those shorts were opened to hedge existing positions, as a malicious attempt to trigger a margin call, or a way to front-run the market using private information cannot be determined from the available data it does look oddly suspicious though. What was unexpected. Personally, the interesting point is not that Bitcoin flash crashed Sudden price fluctuations happened in the past and will happen in the future, especially in illiquid markets such as Bitcoin The interesting point is the involvement of Bitfinex and how they actively managed order execution without informing market participants in advance. The Bitfinex matching engine was not halted during the whole crash though it did slow down but nowhere as bad as the infamous 70 minute order lag on the now defunct MtGox exchange during the crash in 2012 However, what Bitfinex did was they introduced something they now refer to as speed bumps What it means is that they essentially flag orders they deem as invalid or potentially dangerous and slow them down intentionally. At first sight this might seem like a nice idea Who doesn t want a filter to remove or slow down malicious orders However, as so often with those kind of things the devil is in the detail. The problem is that Bitfinex has not and possibly never will make public how exactly they categorize an order as bad and slow it down If a market participant decides to put up a large sell order against a thin orderbook then that s his decision Whether his action was intended or not is not up to the exchange to decide It might be that this market participant was simply the first person to react to a major event and is entirely willing to bear the additional costs of the resulting slippage in anticipation of a major price move There simply does not exist a way to accurately classify orders a priori as good or bad since that would automatically assume knowledge of all immediate future events. What can be improved. Mistakes fat finger , algorithm going havoc happen, margins get called and people try to game the system in every possible way Logically there have to be safeguards in place to protect markets and its participants Bitfinex was definitely aware of potential toxic order flow and prepared counter measures The only thing they forgot was to inform their clients about the hidden safety features. Hiding those safeguards from the public adds uncertainty to the market especially now that we know they exist and sometimes do something and essentially puts every traders trust into the hands of Bitfinex At this point a trader can only hope that Bitfinex will always act in the best intentions of their clients This hope might be futile though, since Bitfinex makes money from trading fees, independently whether a trader actually makes any money One does not have to think for long to realize the hidden potential for abuse in such a system. The main reason brought up by Josh why Bitfinex does not intend to publicise their algorithm is to avoid giving traders the possibility to exploit it is bogus and the following shows why. Those are the official market wide circuit breakers used by NASDAQ, posted online and entirely transparent for every market participant Those rules are certainly not perfect but they are simple, transparent, and work for one of the largest stock markets in the world Now, I have great respect for the people working on the Bitfinex platform, but I doubt that they managed to come up with an algorithm which protects market participants better than the ones used by a major exchange trading more than 900 million shares per day on average And if they did, now is the chance for Bitfinex to prove it to the world and possibly write history by teaching the big boys how to properly run an exchange. When it comes to public exchanges transparency is a must, not just for Bitfinex but for any exchange Market participants have to know exactly what happens when they place an order and should under no circumstances have to rely on good faith alone Safeguards are important because accidents happen and markets crash but it is not up to the exchange to engage in secret order discrimination There are different ways to safeguard financial markets and none of them is perfect Adding complexity usually increases the chance for unintended side effects and therefore a simple, transparent approach seems more appropriate than a hidden, complex one. Two days ago BitMEX reduced their trading fees to 0 and celebrated it by releasing a basic market making bot on Github. BitMEX is currently running a trading challenge until August 29, 2014 to promote their new platform Releasing a market marking bot is probably an interesting and effective way to increase API traffic and stress test the platform a bit Of course I couldn t resist and had a look. Market-maker is a forked off Liquidbot which was original designed to run on the now obsolet MtGox exchange There were some minor changes new api class to connect to BitMEX, some additional prints to console, changes to adapt for futures contracts, and a huge and unnecessary print to console when starting up but no significant changes to the trade logic. The algorithm uses REST and only checks for changes every 60 seconds This already disqualifies the bot as it is essential too slow to react to ongoing changes in the orderbook BitMEX limits requests to the REST API to 150 per 5 minutes so you can try reducing the 60 seconds to something like 3 but it won t change the fact that as soon as markets start to move you will hit the limit and be stuck with open positions To be fair, BitMEX provides the bot more as a marketing stunt and explicitly states that switching to WebSocket will be highly beneficial as it allows real time updates. Overall, the algorithm is solidly written, technically works and is easy to setup, but it won t make you any money in the long run If someone seriously considers to employ this bot I would recommend the following small changes to make the code more usable.1 Change to Websocket.2 Exit position on close.3 Build orders starting from the midpoint. In addition I would advise to measure volatility in some way and adapt the distance between orders dynamically as well as the size. During my testing the API was always responsive and accurate Volume on the exchange is still low but the fundamentals of the platform look promising This bot is a fun tool to introduce users into the world of market making and algorithmic trading but it won t stand a chance against established algorithms. Note If you consider using this algorithm keep in mind that market making is a full time job Anything less than complete dedication, fast reaction time, and 100 uptime will cause you to lose money. Edit Follow up on the aftermath here. Today Bitcoin prices took a dive as margin traders on one of the largest exchange Bitfinex got their orders liquidated For many close market observers and more sophisticated traders this did not come as a surprise In fact, long positions have been building up continuously over the last couple of months in anticipation of a new bubble in Bitcoin prices and reached as high as 30m in outstanding swap positions on Bitfinex. Now, this wouldn t be a problem all by itself as long as there is enough capital backing the loan Unfortunately, most of those long positions were entered around 600 640 USD BTC and the collateral was mostly provided in Bitcoins itself The following chart nicely shows the buildup of long positions, peaking around July 14 with close to 32m in swaps. Running some quick math based on the maintenance margin of Bitfinex of 13 and assuming Bitcoin as collateral we find that margin calls should start around the 520 540 USD BTC mark Yesterday, prices came close and today they finally jumped over the cliff. The problem is that once margin calls set in you have a cascading effect which rips through the order book, causing even more orders to reach the point of no return and increasing the downward momentum further These kind of events are not limited to Bitcoin exchanges but can also occur on major exchanges such as during the 2010 flash crash in the US The cause of such a flash crashe can vary and goes from fat finger mistakes to programming errors to cascading margin calls. It is interesting to see how the exchanges deal with these events In the US , Nasdaq implemented market wide circuit breakers which will cause trading to stop under such extreme circumstances Bitcoin markets are not yet as advanced and usually continue trading If we look at the order action on Bitfinex today we see something very peculiar. It seems and this is just a guess as there is no official comment from the exchange as if Bitfinex is running an algorithm to handle the margin calls The algorithm starts selling but limits itself to a 10 drop in prices within 1 minute If prices drop more than 10 in 1 minute it will stop selling and wait for buy orders to come in Once there are again a certain amount of buy orders in the orderbook the algorithm starts selling again until all margin calls are met Edit LeMogawai was the first to point this out in this post and it matches my personal observation at the time of the event. This seems to be an interesting way to deal with cascading margin calls but can also be considered as borderline market manipulation from the exchange side By spreading out the sell orders over time the downwards momentum is reduced, however traders end up trading against the exchange itself and not the market anymore The exchange has an informational advantage at that point and is therefore more likely to profit than the traders Fortunately, this only lasted for about 10 minutes after which control was given back to the market. Other exchanges which also offer margin trading such as BTC-e and OKcoin are now in a favorable position and can learn from todays events Implementing a system more closely resembling the circuit breakers of big exchanges such as Nasdaq might be a smart first move. Recently I am working to get my new trading platform going This new version is based on Python, uses MySQL to keep a database of all time series of different virtual currencies with automatic backfill from BitcoinCharts and integrates the 3 major exchanges MtGox, BTC-E and Bitstamp The platform will be used as way to backtest some strategies and engage in automatic trading. During the run-up to this I decided to pull some data of BTC against USD from BitcoinCharts and based on the ideas of a paper by Hashem and Timmermann 1995 implemented a simple trading strategy The idea is to forecast the sign of the t 1 period return based on a regression, which is estimated on an automatic selection of technical indicators during the last n period up until t Then, after t 1 happened, we refresh the model and try to predict t 2 using all the data available of the last n periods until t 1 and so on. For my Bachelor Thesis I examined four different technical trading rules in Forex markets It uses MCS and SPA test to search for valid models among different parameters that are not subject to data snooping Taking into account realistic transaction costs we find no evidence of excess returns, which is consistent with market efficiency. With this code you should be able to look for Bitcoin arbitrage opportunities within BTC-e It uses the idea of one price and applies triangular arbitrage, taking into account costs and spread The reason I post this here is despite that it works, chances are you will be too slow to compete with other investors doing the same. Possible improvements would be to take into account the order book depth and split the trades up dynamically, trying to undercut other traders doing the same Also setting everything up on a dedicated server close to the physical location of the BTC-e match engine should drastically reduce lag and give you a potential edge. Post navigation. Cointegration Indicator. Cointegration Indicator. Thanks 10 given, 66 received. I posted a cointegration indicator CADF in the Elite Downloads area It plots the output statistic of an Augmented Dickey Fuller cointegrating regression of 2 instruments It sa C translation of MATLAB code developed by James P LeSage and posted at Econometrics Toolbox for MATLAB I used some mathematical routines from ALGLIB ALGLIB which are included, and wrote a lot of helper routines to accomplish the MATLAB functions Even if you re not interested in cointegration, you might find it useful as an example programming with quantitative methods for NinjaTrader. I haven t seen a cointegration indicator for a trading platform posted publicly before, only MATLAB or R code So I thought I would be the first I posted it for formerly BMT Elite members only, please don t share or distribute. This version is made using primarily static routines, which call new frequently This works fine for indicators or normal strategies, but it can fall apart by filling up memory if you try to run an extensive optimization on it The alternative is to implement the internal routines as classes which can be instantiated once and pre-allocate their storage once at the start I ve done that for strategies, and it helps optimizer performance quite a bit, but ALGLIB uses new in some places so I haven t been able to get rid of all uses of new. I also posted the latest ALGLIB 3 5 0 library, packaged as a NinjaTrader indicator , in the MATLAB downloads area But it s not needed for CADF, the required ALGLIB routines are included. I posted a cointegration indicator CADF in the Elite Downloads area It plots the output statistic of an Augmented Dickey Fuller cointegrating regression of 2 instruments It sa C translation of MATLAB code developed by James P LeSage and posted at Econometrics Toolbox for MATLAB I used some mathematical routines from ALGLIB ALGLIB which are included, and wrote a lot of helper routines to accomplish the MATLAB functions Even if you re not interested in cointegration, you might find it useful as an example programming with quantitative methods for NinjaTrader. I haven t seen a cointegration indicator for a trading platform posted publicly before, only MATLAB or R code So I thought I would be the first I posted it for formerly BMT Elite members only, please don t share or distribute. This version is made using primarily static routines, which call new frequently This works fine for indicators or normal strategies, but it can fall apart by filling up memory if you try to run an extensive optimization on it The alternative is to implement the internal routines as classes which can be instantiated once and pre-allocate their storage once at the start I ve done that for strategies, and it helps optimizer performance quite a bit, but ALGLIB uses new in some places so I haven t been able to get rid of all uses of new. I also posted the latest ALGLIB 3 5 0 library, packaged as a NinjaTrader indicator , in the MATLAB downloads area But it s not needed for CADF, the required ALGLIB routines are included. Thanks for your contribution, I never been exposed to this trade style and i am a completely ignorant about this, but for sure its an interest theme and style It will be good if you post some example on how to use this approach. May 24th, 2012, 03 43 PM. Futures Experience Beginner. Favorite Futures DAX, EUR USD. Posts 18 since Aug 2010.Thanks 16 given, 2 received. kevind, about some examples I would be pleased too I experimented with this approach in Matlab before a while and tried to translate this to C but failed The same problem with R Thank you for your code I will take a look. It should work fine with futures, or futures paired with stocks You need to enter a symbol in the proper form, the symbol must exist in the instrument manager, and the data has to exist for the period specified Cointegration is typically tested on daily data over longer periods, so continuous futures data is probably your best bet. Proper symbol form is ie ES - for continuous futures, or ES 06-12 for a specific contract. Thanks for the reply I have the ES and 6E loaded on a Ninja chart for max days daily chart Also tried 1440 minute chart because I know some indicators only report on 1440 minute charts on Ninja Still nothing with the CADF The parameters list Symbol 2 , which I assume is the second symbol, Nlag ste to 1, P set to 0 , and Period set to 250 Should any of these be adjusted Thanks.

No comments:

Post a Comment