Aprendizaje automático en el trading: teoría, práctica, operaciones y más - página 900

 
Alexander Ivanov:

¿tienes listo tu grial? con una IA))

pues eso... ya son oligarcas ))

Por supuesto, Maximko siempre logra su objetivo.

 
Maxim Dmitrievsky:

por supuesto, Maximko siempre hace el trabajo

)))

eso es todo... Abandonamos todos nuestros robots y nos ponemos a la cola del robot inteligente maravilloso.

 
Alexander Ivanov:

)))

eso es todo... dejamos todos nuestros robots, nos ponemos a la cola del robot inteligente maravilloso.

Ya estoy a mitad de camino del búnker suizo con guardias paramilitares, siguiendo a Alexander con sus polvorientas bolsas llenas de billetes, ¡ni hablar!

 
Maxim Dmitrievsky:

Alexander_K2 de otro hilo

Ahora estoy considerando la posibilidad de llamar al shell de python directamente a través de winapi y enviar comandos a python desde el bot, no sé si es posible. R y dll no los digiero y no se sabe como y no se quiere trabajar con ellos, aunque el python no es necesario (mirando artículos y trabajos de veteranos) cada vez menos ganas de meterse en el ajo - 500000 paquetes y la salida es la misma que del bot en 2 MA

Vincularse con un monstruo así sería útil para muchos, pero no para muchos bajo la fuerza.

Si quisiera utilizar 10 MAs con el paso 16 y hacer un predictor - para cada uno de los precios abiertos por encima / debajo de un MA y uno más - número de este MA mientras que la numeración de todos los MAs de la parte superior a la parte inferior, describiría el mercado?

 
Maxim Dmitrievsky:

Hice un pequeño experimento con la caída de modelos enteros (se dan 10 modelos en total). A partir de 2018.04.01

Sin abandono:

Además marcó con números cuántos modelos al azar se fueron, el resto cayó:

Bueno, algo de esto resulta ser el caso. Probablemente no sea muy revelador, ya que el modelo ha quedado bastante bien sin los abandonos. Y los modelos son demasiado parecidos entre sí, lo que es malo, hay que revisar el algoritmo de aprendizaje (la teoría de juegos puede ayudar). Pero todavía aparece cierta flexibilidad en las opciones.

¡Se ve bien! Parada en uno (1 modelo).

 
Aleksey Vyazmikin:

Enlazar con un monstruo así sería útil para muchos, pero no muchos pueden hacerlo.

Y en cuanto a las MAs, me estaba quedando dormido pensando, ¿qué pasa si tomamos 10 MAs con 16 pasos y hacemos un predictor - para cada uno - el precio abierto por encima/debajo de la MA y uno más - número de MA al numerar todas las MAs desde la parte superior a la inferior del gráfico, describirá tal modelo el mercado?

Esa no es la forma de plantear la pregunta. Experimentos, experimentos... ...porque nada en teoría es obvio. En seis meses he probado unas cien variantes diferentes de ST, y da miedo pensarlo.

El historial de la rama almacena mucha información sobre cómo no hacer (y a veces cómo hacer) bastante útil.

 
Aleksey Vyazmikin:

Enlazar con un monstruo así sería útil para muchos, pero no muchos pueden hacerlo.

Qué pasa con las MAs, estaba pensando mientras me quedaba dormido. ¿Qué pasa si tomo 10 flechas con 16 pasos y hago un predictor - para cada uno de los precios abiertos por encima/debajo de la MA y uno más - número de MA al numerar todas las MAs desde la parte superior del gráfico hasta la parte inferior, describirá tal modelo el mercado?

Hubo un artículo hace unos 10 años con dicho experimento con МА de 2 a 100.
 
elibrarius:
Hubo un artículo hace unos 10 años con un experimento de este tipo con MA de 2 a 100.

Y creo que se llama ventilador, si no me equivoco...

 

Parece que resuelve todos los problemas de comunicación de mql4 con diferentes idiomas. Hay incluso un código para R. Aquí está el esquema.



La descripción completa consta de tres partes:

https://blog.darwinex.com/zeromq-interface-python-r-metatrader4/

https://blog.darwinex.com/zeromq-trade-execution-metatrader-zmq2/

https://blog.darwinex.com/zeromq-transaction-reporting-metatrader-zmq3/

Aprobado:

¿Por qué ZeroMQ?

1. Permite alos programadores conectar cualquier código con cualquier otro código, de diversas maneras.

2.Elimina la dependencia del usuario deMetaTrader sólo de la tecnología soportada por MetaTrader (características, indicadores, construcciones de lenguaje, bibliotecas, etc.).

3.Los operadores pueden desarrollar indicadores y estrategias en C/C#/C++, Python, R y Java (por nombrar algunos), y desplegarlos en el mercado a través de MetaTrader 4.

Aproveche los conjuntos de herramientasde aprendizaje automático en Python y R para el análisis de datos complejos y el desarrollo de estrategias, a la vez que interactúa con MetaTrader 4 para la ejecución y gestión de operaciones.

5.ZeroMQ puede utilizarse como una capa de transporte de alto rendimiento en sistemas comerciales distribuidos y sofisticados que, de otro modo, serían difíciles de implementar en MQL.

6. Losdiferentes componentes de la estrategia pueden ser construidos en diferentes lenguajes si es necesario, y dialogar sin problemas entre sí a través de protocolos TCP, en proceso, interproceso o multidifusión.

7.Múltiples patrones de comunicación y funcionamiento desconectado.

Este es el código

/+------------------------------------------------------------------+
//|                                       ZeroMQ_MT4_EA_Template.mq4 |
//|                                    Copyright 2017, Darwinex Labs |
//|                                        https://www.darwinex.com/ |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, Darwinex Labs."
#property link      "https://www.darwinex.com/"
#property version   "1.00"
#property strict

// Required: MQL-ZMQ from https://github.com/dingmaotu/mql-zmq
#include <Zmq/Zmq.mqh>

extern string PROJECT_NAME = "DWX_ZeroMQ_Example";
extern string ZEROMQ_PROTOCOL = "tcp";
extern string HOSTNAME = "*";
extern int REP_PORT = 5555;
extern int PUSH_PORT = 5556;
extern int MILLISECOND_TIMER = 1;  // 1 millisecond

extern string t0 = "--- Trading Parameters ---";
extern int MagicNumber = 123456;
extern int MaximumOrders = 1;
extern double MaximumLotSize = 0.01;

// CREATE ZeroMQ Context
Context context(PROJECT_NAME);

// CREATE ZMQ_REP SOCKET
Socket repSocket(context,ZMQ_REP);

// CREATE ZMQ_PUSH SOCKET
Socket pushSocket(context,ZMQ_PUSH);

// VARIABLES FOR LATER
uchar data[];
ZmqMsg request;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---

   EventSetMillisecondTimer(MILLISECOND_TIMER);     // Set Millisecond Timer to get client socket input
   
   Print("[REP] Binding MT4 Server to Socket on Port " + REP_PORT + "..");   
   Print("[PUSH] Binding MT4 Server to Socket on Port " + PUSH_PORT + "..");
   
   repSocket.bind(StringFormat("%s://%s:%d", ZEROMQ_PROTOCOL, HOSTNAME, REP_PORT));
   pushSocket.bind(StringFormat("%s://%s:%d", ZEROMQ_PROTOCOL, HOSTNAME, PUSH_PORT));
   
   /*
       Maximum amount of time in milliseconds that the thread will try to send messages 
       after its socket has been closed (the default value of -1 means to linger forever):
   */
   
   repSocket.setLinger(1000);  // 1000 milliseconds
   
   /* 
      If we initiate socket.send() without having a corresponding socket draining the queue, 
      we'll eat up memory as the socket just keeps enqueueing messages.
      
      So how many messages do we want ZeroMQ to buffer in RAM before blocking the socket?
   */
   
   repSocket.setSendHighWaterMark(5);     // 5 messages only.
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
   Print("[REP] Unbinding MT4 Server from Socket on Port " + REP_PORT + "..");
   repSocket.unbind(StringFormat("%s://%s:%d", ZEROMQ_PROTOCOL, HOSTNAME, REP_PORT));
   
   Print("[PUSH] Unbinding MT4 Server from Socket on Port " + PUSH_PORT + "..");
   pushSocket.unbind(StringFormat("%s://%s:%d", ZEROMQ_PROTOCOL, HOSTNAME, PUSH_PORT));
   
}
//+------------------------------------------------------------------+
//| Expert timer function                                            |
//+------------------------------------------------------------------+
void OnTimer()
{
//---

   /*
      For this example, we need:
      1) socket.recv(request,true)
      2) MessageHandler() to process the request
      3) socket.send(reply)
   */
   
   // Get client's response, but don't wait.
   repSocket.recv(request,true);
   
   // MessageHandler() should go here.   
   ZmqMsg reply = MessageHandler(request);
   
   // socket.send(reply) should go here.
   repSocket.send(reply);
}
//+------------------------------------------------------------------+

ZmqMsg MessageHandler(ZmqMsg &request) {
   
   // Output object
   ZmqMsg reply;
   
   // Message components for later.
   string components[];
   
   if(request.size() > 0) {
   
      // Get data from request   
      ArrayResize(data, request.size());
      request.getData(data);
      string dataStr = CharArrayToString(data);
      
      // Process data
      ParseZmqMessage(dataStr, components);
      
      // Interpret data
      InterpretZmqMessage(&pushSocket, components);
      
      // Construct response
      ZmqMsg ret(StringFormat("[SERVER] Processing: %s", dataStr));
      reply = ret;
      
   }
   else {
      // NO DATA RECEIVED
   }
   
   return(reply);
}

// Interpret Zmq Message and perform actions
void InterpretZmqMessage(Socket &pSocket, string& compArray[]) {

   Print("ZMQ: Interpreting Message..");
   
   // Message Structures:
   
   // 1) Trading
   // TRADE|ACTION|TYPE|SYMBOL|PRICE|SL|TP|COMMENT|TICKET
   // e.g. TRADE|OPEN|1|EURUSD|0|50|50|R-to-MetaTrader4|12345678
   
   // The 12345678 at the end is the ticket ID, for MODIFY and CLOSE.
   
   // 2) Data Requests
   
   // 2.1) RATES|SYMBOL   -> Returns Current Bid/Ask
   
   // 2.2) DATA|SYMBOL|TIMEFRAME|START_DATETIME|END_DATETIME
   
   // NOTE: datetime has format: D'2015.01.01 00:00'
   
   /*
      compArray[0] = TRADE or RATES
      If RATES -> compArray[1] = Symbol
      
      If TRADE ->
         compArray[0] = TRADE
         compArray[1] = ACTION (e.g. OPEN, MODIFY, CLOSE)
         compArray[2] = TYPE (e.g. OP_BUY, OP_SELL, etc - only used when ACTION=OPEN)
         
         // ORDER TYPES: 
         // https://docs.mql4.com/constants/tradingconstants/orderproperties
         
         // OP_BUY = 0
         // OP_SELL = 1
         // OP_BUYLIMIT = 2
         // OP_SELLLIMIT = 3
         // OP_BUYSTOP = 4
         // OP_SELLSTOP = 5
         
         compArray[3] = Symbol (e.g. EURUSD, etc.)
         compArray[4] = Open/Close Price (ignored if ACTION = MODIFY)
         compArray[5] = SL
         compArray[6] = TP
         compArray[7] = Trade Comment
   */
   
   int switch_action = 0;
   
   if(compArray[0] == "TRADE" && compArray[1] == "OPEN")
      switch_action = 1;
   if(compArray[0] == "RATES")
      switch_action = 2;
   if(compArray[0] == "TRADE" && compArray[1] == "CLOSE")
      switch_action = 3;
   if(compArray[0] == "DATA")
      switch_action = 4;
   
   string ret = "";
   int ticket = -1;
   bool ans = FALSE;
   double price_array[];
   ArraySetAsSeries(price_array, true);
   
   int price_count = 0;
   
   switch(switch_action) 
   {
      case 1: 
         InformPullClient(pSocket, "OPEN TRADE Instruction Received");
         // IMPLEMENT OPEN TRADE LOGIC HERE
         break;
      case 2: 
         ret = "N/A"; 
         if(ArraySize(compArray) > 1) 
            ret = GetBidAsk(compArray[1]); 
            
         InformPullClient(pSocket, ret); 
         break;
      case 3:
         InformPullClient(pSocket, "CLOSE TRADE Instruction Received");
         
         // IMPLEMENT CLOSE TRADE LOGIC HERE
         
         ret = StringFormat("Trade Closed (Ticket: %d)", ticket);
         InformPullClient(pSocket, ret);
         
         break;
      
      case 4:
         InformPullClient(pSocket, "HISTORICAL DATA Instruction Received");
         
         // Format: DATA|SYMBOL|TIMEFRAME|START_DATETIME|END_DATETIME
         price_count = CopyClose(compArray[1], StrToInteger(compArray[2]), 
                        StrToTime(compArray[3]), StrToTime(compArray[4]), 
                        price_array);
         
         if (price_count > 0) {
            
            ret = "";
            
            // Construct string of price|price|price|.. etc and send to PULL client.
            for(int i = 0; i < price_count; i++ ) {
               
               if(i == 0)
                  ret = compArray[1] + "|" + DoubleToStr(price_array[i], 5);
               else if(i > 0) {
                  ret = ret + "|" + DoubleToStr(price_array[i], 5);
               }   
            }
            
            Print("Sending: " + ret);
            
            // Send data to PULL client.
            InformPullClient(pSocket, StringFormat("%s", ret));
            // ret = "";
         }
            
         break;
         
      default: 
         break;
   }
}

// Parse Zmq Message
void ParseZmqMessage(string& message, string& retArray[]) {
   
   Print("Parsing: " + message);
   
   string sep = "|";
   ushort u_sep = StringGetCharacter(sep,0);
   
   int splits = StringSplit(message, u_sep, retArray);
   
   for(int i = 0; i < splits; i++) {
      Print(i + ") " + retArray[i]);
   }
}

//+------------------------------------------------------------------+
// Generate string for Bid/Ask by symbol
string GetBidAsk(string symbol) {
   
   double bid = MarketInfo(symbol, MODE_BID);
   double ask = MarketInfo(symbol, MODE_ASK);
   
   return(StringFormat("%f|%f", bid, ask));
}

// Inform Client
void InformPullClient(Socket& pushSocket, string message) {

   ZmqMsg pushReply(StringFormat("%s", message));
   // pushSocket.send(pushReply,true,false);
   
   pushSocket.send(pushReply,true); // NON-BLOCKING
   // pushSocket.send(pushReply,false); // BLOCKING
   
}
 

Y aquí está el código para r

#+------------------------------------------------------------------+
#|                                          ZeroMQ_MT4_R_Template.R |
#|                                    Copyright 2017, Darwinex Labs |
#|                                        https://www.darwinex.com/ |
#+------------------------------------------------------------------+

# Load "rzmq" library. If not installed, run install.packages("rzmq")
library(rzmq)

# Random placeholder for PULL later.
pull.msg <- "N/A"

# Function to send commands to ZeroMQ MT4 EA
remote.send <- function(rSocket,data) {
  send.raw.string(rSocket, data)
  msg <- receive.string(rSocket)
  
  print(msg)
}

# Function to PULL data from ZeroMQ MT4 EA PUSH socket.
remote.pull <- function(pSocket) {

  msg <- receive.socket(pSocket, unserialize = FALSE, dont.wait = TRUE)
  
  if(is.null(msg)) {
    msg <- "No data PUSHED yet.."
    print(msg)
  } else {
    msg <- rawToChar(msg)
    print(msg)  
  }

  return(msg)
}

# CREATE ZeroMQ Context
context = init.context()

# Initialize ZeroMQ REQ Socket
reqSocket = init.socket(context,"ZMQ_REQ")

# Initialize ZeroMQ PULL Socket
pullSocket = init.socket(context, "ZMQ_PULL")

# Connect to REQ Socket on port 5555
connect.socket(reqSocket,"tcp://localhost:5555")

# Connect to PULL Socket on port 5556
connect.socket(pullSocket,"tcp://localhost:5556")

# Run Tests
while(TRUE) {
  
  # REMEMBER: If the data you're pulling isn't "downloaded" in MT4's History Centre,
  #           it's very likely your PULL will produce no data.
  
  #           So if you're going to be pulling data for a currency pair from MT4,
  #           make sure its data is downloaded, and chart open just in case.
  
  # Pull from server
  remote.pull(pullSocket)
  
  f <- file("stdin")
  open(f)
  
  print("Enter Command for MetaTrader 4 ZeroMQ Server, 'q' to quit")
  # e.g. RATES|EURUSD -> Retrieves Current Bid/Ask for EURUSD from MT4.
  mt4.command <- readLines(f, n=1)
  
  if(tolower(mt4.command) == "q") {
    break
  }
  
  # Send to ZeroMQ MetaTrader 4 Server
  if(!grepl("PULL", mt4.command))
    remote.send(reqSocket, mt4.command)
  
  # Pull from ZeroMQ MetaTrader 4 Server
  pull.msg <- remote.pull(pullSocket)
}