Doc de Mi Lenguaje

El autor:Un sueño pequeño., Creado: 2022-06-30 18:24:06, Actualizado: 2024-02-06 17:36:19

[TOC] ¿Qué quieres decir?

img

MyLanguage es un lenguaje de comercio programático que es compatible y mejorado con MyLanguage. El MyLanguage de FMZ Quant se someterá a una verificación de sintaxis estricta.%%el operador hará que se reporte un error.

  • Instrucciones básicas

    • Contrato

      Contrato de criptomonedas

      Contrato de criptomonedas

      this_week     cryptocurrency futures contract this week
      next_week     cryptocurrency futures contract next week
      month         cryptocurrency futures contract month
      quarter       cryptocurrency futures contract quarter
      next_quarter  cryptocurrency futures contract next quarter
      third_quarter cryptocurrency futures contract third quarter
      last_quarter  contract last quarter
      
      XBTUSD        BITMEX perpetual contract
      swap          cryptocurrency futures perpetual contracts other than BITMEX exchange
      
      For details, please refer to the exchange.SetContractType() function section of the JavaScript/Python/C++ documentation
      

      img

    • Variables

      Una variable es un espacio abierto en la memoria del ordenador para almacenar datos.

      abre la primera variable

      // assign 1 to variable a
      a:=1;
      

      En elMyLanguage, es sencillo distinguirla de ladata volume:

      1. Datos de un solo valor: solo hay un valor, como:0, 1, 'abc'.
      2. Datos de secuencia: una secuencia de datos compuesta por un grupo de datos de un solo valor, tales como:Close(precio de cierre), dondeClosecontiene el precio de cierre den periods. [ 10.1 , 10.2 , 10.3 , 10.4 , 10.5 ...]

      Distinguir entre tipo variable

      1. Tipo de cadena: debe estar envuelto con ````, el tipo de cadena no se permite utilizar directamente, y debe ser enviado a la vista con la función.
      INFO(CLSOE>OPEN,'OK!');
      
      1. Tipos de valores: incluidos los enteros, los números con coma flotante (decimales).
      // integer
      int:=2;
      
      // decimal
      float:=3.1;
      
      1. Tipo booleano, utilizando 1 (para verdadero) o 0 (para falso): 1, 0, verdadero o falso. Por ejemplo:A:=1>0;Después de ejecutar este código, el valor deAes 1.
      // The closing price of the current period is greater than -999, you will find that the return value of each period is 1, which means true, because the closing price is almost impossible to be negative.
      is_true:=Close>-999;
      
      1. Variables globales
      VARIABLE:VALUE1:10;     // Declare a global variable, assign the value 10, and execute it only once.
      

      Observe que cuando se hace backtesting:

      VARIABLE:NX:0;    // The initial global variable NX is 0
      NX..NX+1;         // Accumulate 1 each time
      INFO(1,NX);       // Print NX every time
      

      En primer lugar, elINFOImpresiones de declaraciones101Tal vez no lo sea.0¿Al principio? La razón es que hay 100 líneas K iniciales en el backtest, y 100 líneas K ya se han ejecutado, que se ha acumulado 100 veces. El precio real depende de cuántas líneas K se obtienen inicialmente.

      • Reglas de nombramiento

        En la mayoría de los sistemas, la denominación de variables no permite el uso del sistema palabras reservadas (nombres de variables incorporados, nombres de funciones).Close, CAdemás, no se permiten números puros o números primos. Por último, no se permite que sea muy largo, y diferentes sistemas tienen diferentes restricciones de longitud. De hecho, no tienes que preocuparte por la eficiencia del sistema principal de análisis de chino. Creo que MyLanguage es muy amigable con el chino. Para los programadores experimentados, se recomienda usar las siguientes dos reglas de nombres:

        1. Nombre chino
        // elegant output
        5-day moving average:=MA(C,5);
        
        1. Inglés + subrayado
        // Output
        move_avg_5:=MA(C,5);
        

        Si prefiere el inglés, trate de hacer que el significado de sus variables sea lo más comprensible posible.A1, AAA, BBB...Confíe en mí cuando revise su código de indicador de nuevo en unos días, usted será muy miserable debido a la pérdida de memoria.

        Así que a partir de ahora, abrace MyLanguage al máximo!Espero que pueda convertirse en una poderosa herramienta para su análisis y toma de decisiones.

    • Tipo de datos

      Cuando asignamos datos claros a una variable por escrito, la variable también se convierte en el tipo de los datos en sí.

        1. Tipo de valor:
        1.2.3.1.1234.2.23456 ...
        
        1. Tipo de cadena:
        '1' .'2' .'3' ,String types must be wrapped with ''
        
        1. Datos de la secuencia:
        A collection of data consisting of a series of single-valued data
        
        1. Tipo booleano:

        Utilización1Representa eltruey0parafalse.

        Ejemplo

        // declare a variable of value type
        var_int := 1;
        // Declare a variable for sequence data
        var_arr := Close;
        // The string type cannot be declared alone, it needs to be combined with the function
        INFO(C>O, 'positive line');
        
    • El operador

      La operación y el cálculo utilizados para ejecutar el código del indicador son simplemente los símbolos involucrados en la operación.

      • Operador de asignación

        para asignar un valor a una variable

          1. :

          :, representa la asignación y la salida al gráfico (subgráfico).

          Close1:Close;      // Assign Close to the variable Close1 and output to the figure
          
          1. :=

          :=, representa la asignación, pero no se produce en el gráfico (gráfico principal, subgráfico...), ni se muestra en la tabla de la barra de estado.

          Close2:=Close;     // Assign Close to the variable Close2
          
          1. ^^

          ^^Dos.^Los símbolos representan la asignación, asignan valores a las variables y la salida al gráfico (gráfico principal).

          lastPrice^^C;
          
          1. ..

          .., dos.Los símbolos representan la asignación, asignan valores a las variables y muestran los nombres y valores de las variables en el gráfico, pero no dibujan imágenes en el gráfico (imagen principal, subimagen...).

          openPrice..O
          
      • Operadores relacionales

        Los operadores relacionales son operadores binarios que se utilizan en expresiones condicionales para determinar la relación entre dos datos.

        Valor de retorno: tipo booleano, ya seatrue(1) ofalse(0).

          1. más de>
          // Assign the operation result of 2>1 to the rv1 variable, at this time rv1=1
          rv1:=2>1;
          
          1. Menos de<
          // Returns false, which is 0, because 2 is greater than 1
          rv3:=2<1;
          
          1. mayor o igual a>=
          x:=Close;
          // Assign the result of the operation that the closing price is more than or equal to 10 to the variable rv2
          // Remark that since close is a sequence of data, when close>=10 is performed, the operation is performed in each period, so each period will have a return value of 1 and 0
          rv2:=Close>=10;
          
          1. menor o igual a<=
          omitted here
          
          1. es igual a=
          A:=O=C;     // Determine whether the opening price is equal to the closing price.
          
          1. No es igual a<>
          1<>2       // To determine whether 1 is not equal to 2, the return value is 1 (true)
          
      • Operadores lógicos

        Valor de retorno: tipo booleano, ya seatrue(1) ofalse(0).

        1. La lógica y&&, puede ser sustituido porand, y los lados izquierdo y derecho de la conexión se deben establecer al mismo tiempo.
        // Determine whether cond_a, cond_b, cond_c are established at the same time
        cond_a:=2>1;
        cond_b:=4>3;
        cond_c:=6>5;
        cond_a && cond_b and cond_c;    // The return value is 1, established
        
        1. ¿Qué es esto?||, puedes usarorpara reemplazar los lados izquierdo y derecho del o enlace, un lado es verdadero (verdadero), el conjunto es verdadero (valor de retorno verdadero).
        cond_a:=1>2;
        cond_b:=4>3;
        cond_c:=5>6;
        cond_a || cond_b or cond_c;    // The return value is 1, established
        
        1. ()Operador, la expresión entre paréntesis se evaluará primero.
        1>2 AND (2>3 OR 3<5)    // The result of the operation is false
        1>2 AND 2>3 OR 3<5      // The result of the operation is true
        
      • Operadores aritméticos

        Return value: numeric type
        

        Los operadores aritméticos son operadores aritméticos. Es un símbolo para completar operaciones aritméticas básicas (operadores aritméticos), que es un símbolo utilizado para procesar cuatro operaciones aritméticas.

        • más +

          A:=1+1;      // return 2
          
        • menos -

          A:=2-1;      // return 1
          
        • *multiplicado *

          A:=2*2;      // return 4
          
        • dividir /

          A:=4/2;      // return 2
          
    • Funciones

      • Funciones

        En el mundo de la programación, una función es una pieza de código que implementa una determinada función.

        function(param1,param2,...)
        
        • Composición:

          El nombre de la función (parámetro1, parámetro2,...), puede no tener parámetros o tener múltiples parámetros.MA(x,n);La media móvil simple dexdentro denEntre ellos,MA()es una función,xynson los parámetros de la función.

          Cuando usamos una función, necesitamos entender la definición básica de la función, es decir, qué datos se pueden obtener llamando a la función. En términos generales, las funciones tienen parámetros. Cuando pasamos parámetros, necesitamos asegurarnos de que el tipo de datos entrantes sea consistente. En esta etapa, la función de sugerencia de código de la mayoría de los IDE es muy imperfecta. Hay un tipo de datos del parámetro dado, lo que trae algunos problemas para nuestro uso, yMA(x,n);se interpretará como:

          Return to simple moving average
          Usage:
          AVG:=MA(X,N): N-day simple moving average of X, algorithm (X1+X2+X3+...+Xn)/N, N supports variables
          

          Esto es muy hostil para los principiantes, pero a continuación, vamos a diseccionar la función a fondo, tratando de encontrar una manera rápida de aprender y utilizar la función.

      • Valor de retorno

        Para aprender funciones rápidamente, necesitamos entender un concepto primero, se llama valor de retorno, Regreso, como su nombre indica, significa retorno ; El valor representa valor específico , entonces el significado del valor de retorno es: los datos que se pueden obtener.

        // Because it will be used in the following code, the variable return_value is used to receive and save the return value of function()
        // retrun_value := function(param1,param2);
        // For example:
        AVG:=MA(C,10);     // AVG is retrun_value, function is MA function, param1 parameter: C is the closing price sequence data, param2 parameter: 10.
        
      • Parámetros

        En segundo lugar, el segundo concepto importante de la función es el parámetro, y se pueden obtener diferentes valores de retorno al pasar diferentes parámetros.

        // The variable ma5 receives the 5-day moving average of closing prices
        ma5:=MA(C,5);
        // The variable ma10 receives the 10-day moving average of closing prices
        ma10:=MA(C,10);
        

        El primer parámetroXde las variables anterioresma5, ma10esC(precio de cierre), de hecho,CEl valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre de un valor de cierre.MA()La función se vuelve más flexible para usar a través de los parámetros.

      • Cómo aprender

          1. Primero, necesitamos entender lo que hace una función, es decir, qué datos esta función puede devolvernos.
          1. La última cosa es entender el tipo del valor de retorno.
          1. Además, necesitamos saber el tipo de datos del parámetroMA(x,n), si no conoce el tipo de datos del parámetrox, n, no será capaz de obtener el valor de retorno correctamente.

        En la siguiente introducción y uso de la función, siga los tres principios anteriores.

    • Mejora del lenguaje

      • MyLanguageyJavaScriptProgramación mixta en lenguaje

        %%
        // This can call any API quantified of FMZ
        scope.TEST = function(obj) {
            return obj.val * 100;
        }
        %%
        Closing price: C;
        Closing price magnified 100 times: TEST(C);
        The last closing price is magnified by 100 times: TEST(REF(C, 1)); // When the mouse moves to the K-line of the backtest, the variable value will be prompted
        
        • scopeobjetos

          ElscopeObjeto puede agregar atributos y asignar funciones anónimas a los atributos, y la función anónima a la que se hace referencia por este atributo se puede llamar en la parte de código de MyLanguage.

        • scope.getRefs(obj)Función

          En elJavaScriptBloque de código, llame alscope.getRefs(obj)Función para devolver los datos de la pasada enobj object.

          ElJavaScriptCódigo envuelto con el siguiente:%% %%- ¿ Qué es eso?CEn el momento en que elTEST(C)La función en el código de MyLanguage se llama precio de cierre. Elscope.getRefsla función devolverá todos los precios de cierre de los datos de la línea K.throw "stop"para interrumpir el programa, la variablearrsólo contiene el precio de cierre de la primera barra.throw "stop", se ejecutará elreturnal final de laJavaScriptcódigo, y devuelva todos los datos de precio de cierre.

          %%
          scope.TEST = function(obj){
              var arr = scope.getRefs(obj)
              Log("arr:", arr)
              throw "stop"
              return
          }
          %%
          TEST(C);
          
        • scope.bars

          Acceso a todas las barras de línea K en elJavaScriptBloque de código.

          ElTEST1 es una recta negativa y 0 es una recta positiva.

          %%
          scope.TEST = function(){
              var bars = scope.bars
              return bars[bars.length - 1].Open > bars[bars.length - 1].Close ? 1 : 0    // Only numeric values can be returned
          }
          %%
          arr:TEST;                                                                      
          
          # Attention:
          # An anonymous function received by TEST, the return value must be a numeric value.
          # If the anonymous function has no parameters, it will result in an error when calling TEST, writing VAR:=TEST; and writing VAR:=TEST(); directly.
          # TEST in scope.TEST must be uppercase.
          
        • scope.bar

          En elJavaScriptBloque de código, acceso a la barra de corriente.

          Calcular el promedio de los precios de apertura altos y los precios de cierre bajos.

          %%
          scope.TEST = function(){
              var bar = scope.bar
              var ret = (bar.Open + bar.Close + bar.High + bar.Low) / 4
              return ret
          }
          %%
          avg^^TEST;
          
        • scope.depth

          Acceso a los datos de profundidad del mercado (libro de pedidos).

          %%
          scope.TEST = function(){
              Log(scope.depth)
              throw "stop"             // After printing the depth data once, throw an exception and pause
          }
          %%
          TEST;
          
        • scope.symbol

          Obtener la cadena de nombres del par de negociación actual.

          %%
          scope.TEST = function(){
              Log(scope.symbol)
              throw "stop"
          }
          %%
          TEST;
          
        • scope.barPos

          Obtener la posición de la barra de la línea K.

          %%
          scope.TEST = function(){
              Log(scope.barPos)
              throw "stop"
          }
          %%
          TEST;
          
        • el alcance.get_locals (nombre)

          Esta función se utiliza para obtener las variables en la sección de código de MyLanguage.

          V:10;
          %%
          scope.TEST = function(obj){
              return scope.get_locals('V')
          }
          %%
          GET_V:TEST(C);
          
          # Attention:
          # If a variable cannot calculate the data due to insufficient periods, call the scope.get_locals function in the JavaScript code at this time
          # When getting this variable, an error will be reported: line:XX - undefined locals A variable name is undefined
          
        • scope.canTrade

          ElcanTrademarcas de atributo si la barra actual se puede negociar (si la barra actual es la última)

          Por ejemplo, juzgar que los datos de mercado se imprimen cuando la estrategia se encuentra en un estado en el que la orden se puede negociar

          %%
          scope.LOGTICKER = function() {
              if(exchange.IO("status") && scope.canTrade){
                  var ticker = exchange.GetTicker();
                  if(ticker){
                      Log("ticker:", ticker);
                      return ticker.Last;
                  }
              }
          }
          %%
          LASTPRICE..LOGTICKER;
          
      • Ejemplo de aplicación:

        %%
        scope.TEST = function(a){
            if (a.val) {
                throw "stop"
            }    
        }
        %%
        O>C,BK;
        C>O,SP;
        TEST(ISLASTSP);
        

        Detenga la estrategia después de abrir y cerrar una posición una vez.

    • Referencia de varios períodos

      El sistema seleccionará automáticamente un período de línea K subyacente adecuado y utilizará estos datos de período de línea K subyacentes para sintetizar todos los datos de línea K a los que se hace referencia para garantizar la exactitud de los datos.

      • Utilización:#EXPORT formula_name ... #ENDSi la fórmula no se calcula sólo para obtener datos de diferentes períodos, también se puede escribir una fórmula vacía.

        Una fórmula vacía es:

        #EXPORT TEST 
        NOP;
        #END           // end
        
      • Utilización:#IMPORT [MIN,period,formula name] AS variable valueObtener varios datos del período establecido (precio de cierre, precio de apertura, etc., obtenidos por valor variable).

        ElMINEn elIMPORTel comando significanivel de minuto.MyLanguage de la plataforma FMZ Quant, y sólo elMINEl nivel de apoyo en elIMPORTAhora se soportan períodos no estándar. Por ejemplo, se puede usar#IMPORT [MIN, 240, TEST] AS VAR240para importar datos como el período de 240 minutos (4 horas) K-line.

        Ejemplo de código:

        // This code demonstrates how to reference formulas of different periods in the same code
        // #EXPORT extended grammar, ending with #END marked as a formula, you can declare multiple
        #EXPORT TEST 
        Mean value 1: EMA(C, 20);
        Mean value 2: EMA(C, 10);
        #END // end
        
        #IMPORT [MIN,15,TEST] AS VAR15 // Quoting the formula, the K-line period takes 15 minutes
        #IMPORT [MIN,30,TEST] AS VAR30 // Quoting the formula, the K-line period takes 30 minutes
        CROSSUP(VAR15.Mean value is 1, VAR30.Mean value is 1),BPK;
        CROSSDOWN(VAR15.Mean value is 2, VAR30.Mean value is 2),SPK;
        The highest price in fifteen minutes:VAR15.HIGH;
        The highest price in thirty minutes:VAR30.HIGH;
        AUTOFILTER;
        
      • Es necesario prestar atención al utilizarREF, LLV, HHVy otras instrucciones para hacer referencia a los datos cuando se hacen referencia a datos en períodos múltiples.

        (*backtest
        start: 2021-08-05 00:00:00
        end: 2021-08-05 00:15:00
        period: 1m
        basePeriod: 1m
        exchanges: [{"eid":"Futures_OKCoin","currency":"ETH_USD"}]
        args: [["TradeAmount",100,126961],["ContractType","swap",126961]]
        *)      
        
        %%
        scope.PRINTTIME = function() {
            var bars = scope.bars;
            return _D(bars[bars.length - 1].Time);
        }
        %%
        BARTIME:PRINTTIME;      
        
        #EXPORT TEST 
        REF1C:REF(C,1);
        REF1L:REF(L,1);
        #END // end      
        
        #IMPORT [MIN,5,TEST] AS MIN5
        INFO(1, 'C:', C, 'MIN5.REF1C:', MIN5.REF1C, 'REF(MIN5.C, 1):', REF(MIN5.C, 1), 'Trigger BAR time:', BARTIME, '#FF0000');
        INFO(1, 'L:', L, 'MIN5.REF1L:', MIN5.REF1L, 'REF(MIN5.L, 1):', REF(MIN5.L, 1), 'Trigger BAR time:', BARTIME, '#32CD32');
        AUTOFILTER;
        

        Comparando la diferencia entreMIN5.REF1CyREF(MIN5.C, 1), podemos encontrar:MIN5.REF1Ces el valor del precio de cierre del penúltimo BAR en el momento actual de los datos de la línea K de 5 minutos.REF(MIN5.C, 1)es el período de línea K del modelo actual (el período de prueba posterior del código anterior se establece en 1 minuto, es decir, ```period: 1m``), el precio de cierre del período de 5 minutos en el que se encuentra el penúltimo BAR en el momento actual. Estas dos definiciones se diferencian y pueden utilizarse según sea necesario.

    • Descripción del modo

      • Modelo de filtrado de señal de una abertura y una nivelación

        En el modelo, elAUTOFILTERCuando hay múltiples señales de apertura que cumplen con las condiciones, la primera señal se toma como la señal válida, y la misma señal en la línea K se filtrará.

        Las instrucciones soportadas por el modelo de filtrado: BK, BP, BPK, SK, SP, SPK, CLOSEOUT, etc. No se admiten las instrucciones con números de lote como BK ((5).

        Por ejemplo,

        MA1:MA(CLOSE,5);
        MA2:MA(CLOSE,10);
        CROSSUP(C,MA1),BK;
        CROSSUP(MA1,MA2),BK;
        C>BKPRICE+10||C<BKPRICE-5,SP;
        AUTOFILTER;
        
        Comprehension:
        As in the above example, when AUTOFILTER is not set, the third row BK, the fourth row BK and the fifth row SP are triggered in sequence, and each K-line triggers a signal once. After opening the position, and closing the position, the model state is reset.      
        If AUTOFILTER is set, after triggering BK, only SP is triggered, other BK signals are ignored, and each K-line triggers a signal once.
        
      • Modelo de posición de aumento y disminución

        ElAUTOFILTERla función no está escrita en el modelo, lo que permite señales de apertura o cierre continuas, que pueden aumentar y disminuir las posiciones.

        Las instrucciones soportadas: BK(N), BP(N), SK(N), SP(N), CLOSEOUT, BPK(N), SPK(N, las órdenes de apertura y cierre sin tamaño de lote no son compatibles. (1) Se apoya la agrupación de instrucciones. (2) Cuando se cumplen simultáneamente varias condiciones de instrucción, las señales se ejecutan en el orden en que se escriben las instrucciones condicionales. Por ejemplo:

        MA1:MA(CLOSE,5);
        MA2:MA(CLOSE,10);
        CROSSUP(C,MA1),BK(1);
        CROSSUP(MA1,MA2),BK(1);
        C>BKPRICE+10||C<BKPRICE-5,SP(BKVOL);
        

        UtilizaciónTRADE\_AGAINEs posible hacer la misma línea de comandos, múltiples señales en sucesión.

        Comprehension:
        The above example is executed one by one, and the signal after execution is no longer triggered. Reset the model status after closing the position. A K -line triggers a signal once.
        
      • Modelo con una línea K y una señal

        Independientemente de si la línea K está terminada, la señal se calcula en órdenes en tiempo real, es decir, la línea K se coloca antes de que se complete la orden; la línea K se revisa al final.

        Por ejemplo:

        MA1:MA(CLOSE,5);
        MA2:MA(CLOSE,10);
        CROSSUP(MA1,MA2),BPK;    //The 5-period moving average crosses up, and the 10-period moving average goes long.
        CROSSDOWN(MA1,MA2),SPK;  //The 5-period moving average crosses down, and the 10-period moving average goes short.
        AUTOFILTER;
        
      • Un modelo de múltiples señales en una línea K

        El modelo utilizamultsigpara controlar e implementar múltiples señales desde una línea K.

        Independientemente de si la línea K está terminada, la señal se calcula en tiempo real.

        La señal no se revisa, no hay desaparición de señal, y la dirección de la señal siempre es consistente con la dirección de la posición.

        Si se cumplen varias condiciones de señal en una línea K, se puede ejecutar repetidamente.

        For example:
        MA1:MA(CLOSE,5);
        MA2:MA(CLOSE,10);
        CROSSUP(MA1,MA2),BK;
        C>BKPRICE+10||C<BKPRICE-5,SP;
        AUTOFILTER;
        MULTSIG(0,0,2,0);
        

        MULTSIGpuede ejecutar varias líneas de comando dentro de una línea K. Una línea de comandos sólo se señala una vez.

        O<C,BK;            // These conditions may all be executed in a K-line Bar, but only one signal per line
        10+O<C,BK;         // Strategy plus TRADE_AGAIN(10);it can make multiple signals per line
        20+O<C,BK;
        40+O<C,BK;
        MULTSIG(1,1,10);
        

        El suplemento: 1.El modelo de suma y reducción de posiciones, dos formas de una señal y una línea K: colocar una orden al precio de cierre y colocar una orden al precio de la orden, son ambos compatibles. 2.El modelo de suma y disminución de posiciones también admite la ordenación de múltiples señales de una línea K. El modelo de suma y disminución de posiciones, escriba elmultsigfunción para realizar múltiples adiciones o múltiples reducciones en una línea K.

    • Modo de ejecución

      img

      • Modelo de barra

        El modelo Bar se refiere al modelo que se ejecuta después de que se complete el BAR actual, y la negociación se ejecuta cuando comienza el siguiente BAR.

      • Modelo de tick

        El modelo Tick significa que el modelo se ejecuta una vez por cada movimiento de precios y se negocia inmediatamente cuando hay una señal. El modelo Tick ignora la señal del día anterior (la señal del día anterior se ejecuta inmediatamente el mismo día), y el modelo Tick se centra solo en los datos actuales del mercado para determinar si se activa la señal.

    • Display de gráfico

      • Indicadores adicionales para el gráfico principal

        Utilice el operador^^, los indicadores establecidos se muestran en el gráfico principal mientras se asignan valores a las variables.

        MA60^^MA(C, 60);  // Calculate the average indicator with the parameter of 60
        

        img

      • Indicadores adicionales para el subgráfico

        Utilice el operador:, los indicadores establecidos se muestran en el subgráfico mientras se asignan valores a las variables.

        ATR:MA(MAX(MAX((HIGH-LOW),ABS(REF(CLOSE,1)-HIGH)),ABS(REF(CLOSE,1)-LOW)),26);    // Assign a value to the ATR variable, the ":" symbol is followed by the formula for calculating the ATR
        

        img

        Si no desea que se muestre en el gráfico principal o subgráfico, utilice el operador ....

        MA60..MA(C, 60);  // Calculate the average indicator with the parameter of 60
        

        Puedes usarDOTyCOLORREDPara establecer el tipo de línea y el color de la línea, etc., en línea con los hábitos de los usuarios familiarizados con MyLanguage.

    • Problemas comunes

      ¿Qué es lo queproblemasLos puntos que se encuentran comúnmente en el proceso de redacción de indicadores, por lo general los puntos a los que se debe prestar atención al escribir (agregados continuamente).

      • Observe el punto y coma;al final.

      • Tenga en cuenta que las palabras clave del sistema no pueden declararse como variables.

      • Tenga en cuenta que la cadena utilizalas cotizaciones únicas, por ejemplo: la cadena'Open position'.

      • No obstante,

        Anotado

        • // The Remark content(el método de entrada puede escribirse tanto en chino como en inglés) significa que el código no se compila durante el proceso de ejecución, es decir, el contenido después de//Normalmente lo usamos para marcar el significado del código, cuando es conveniente para la revisión del código, puede ser rápidamente entendido y recordado.

        • { Remark content }No quiero hacer comentarios.

          A:=MA(C,10);
          {The previous line of code is to calculate the moving average.}
          
        • (* Remark content *)No quiero hacer comentarios.

          A:=MA(C,10);
          (*The previous line of code is to calculate the moving average.*)
          
      • Ingreso

        Cuando se escribe código, porque el método de entrada a menudo se cambia entre chino e inglés, lo que resulta en errores de símbolos.:, el Terminador;, coma,, entre corchetes()Estos caracteres en diferentes estados de chino e inglés necesitan atención.

        Si utiliza Sogou, Baidu, o Bing métodos de entrada, puede cambiar rápidamente entre el chino y el inglés pulsando elshiftLa llave una vez.

      • Lógica propensa a errores

        1. Al menos, no menos que, no menos que: el operador relacional correspondiente>=.
        2. Hasta, como máximo: el operador relacional correspondiente<=.
      • Sincronización de lanzamiento de estrategia

        En la estrategia de futuros, si hay una posición abierta manualmente antes de que el robot de estrategia se inicie, cuando el robot se inicie, detectará la información de posición y la sincronizará con el estado real de la posición. En la estrategia, se puede utilizar elSP, BP, CLOSEOUTlas órdenes para cerrar la posición.

        %%
        if (!scope.init) {
            var ticker = exchange.GetTicker();
            exchange.Buy(ticker.Sell+10, 1);
            scope.init = true;
        }
        %%
        C>0, CLOSEOUT;
        
      • Las posiciones bidireccionales no son compatibles

        MyLanguage no admite el mismo contrato con posiciones largas y cortas.

  • Citación de datos de línea K

    • Se abre

      Obtenga el precio de apertura del gráfico de la línea K.

      Precio de apertura

      Función: OPEN, abreviatura de O

      Parámetros: ninguno

      Explicación: devuelve el precio de apertura de este período

      Datos de secuencia

      OPEN gets the opening price of the K-line chart.
      
      Remark:
      1.It can be abbreviated as O.
      
      Example 1:
      OO:=O;           //Define OO as the opening price; Remark that the difference between O and 0.
      Example 2:
      NN:=BARSLAST(DATE<>REF(DATE,1));
      OO:=REF(O,NN);   //Take the opening price of the day
      Example 3:
      MA5:=MA(O,5);    //Define the 5-period moving average of the opening price (O is short for OPEN).
      
    • - Es muy alto.

      Obtener el precio más alto en el gráfico de la línea K.

      El precio más alto

      Función: HIGH, abreviado H

      Parámetros: ninguno

      Explicación: Devuelva el precio más alto de este período

      Datos de secuencia

      HIGH achieved the highest price on the K-line chart.
      
      Remark:
      1.It can be abbreviated as H.
      
      Example 1:
      HH:=H;         // Define HH as the highest price
      Example 2:
      HH:=HHV(H,5);  // Take the maximum value of the highest price in 5 periods
      Example 3:
      REF(H,1);      // Take the highest price of the previous K-line
      
    • Bajo

      Obtener el precio más bajo en el gráfico de la línea K.

      El precio más bajo

      Función: BAJO, abreviado L

      Parámetros: ninguno

      Explicación: Retorno del precio más bajo de este período

      Datos de secuencia

      LOW gets the lowest price on the K-line chart.
      
      Remark:
      1.It can be abbreviated as L.
      
      Example 1:
      LL:=L;            // Define LL as the lowest price
      Example 2:
      LL:=LLV(L,5);     // Get the minimum value of the lowest price in 5 periods
      Example 3:
      REF(L,1);         // Get the lowest price of the previous K-line
      
    • - ¿ Por qué no?

      Obtenga el precio de cierre del gráfico de la línea K.

      Precio de cierre

      Función: CLOSE, abreviado como C

      Parámetros: ninguno

      Explicación: devuelve el precio de cierre de este período

      Datos de secuencia

      CLOSE Get the closing price of the K-line chart
      
      Remarks:
      1.Obtain the latest price when the intraday K-line has not finished.
      2.It can be abbreviated as C.
      
      Example 1:
      A:=CLOSE;          //Define the variable A as the closing price (A is the latest price when the intraday K-line has not finished)
      Example 2:
      MA5:=MA(C,5);      //Define the 5-period moving average of the closing price (C is short for CLOSE)
      Example 3:
      A:=REF(C,1);       //Get the closing price of the previous K-line
      
    • VOL

      Obtener el volumen de negociación del gráfico de línea K.

      Volumen de las operaciones

      Función: VOL, abreviado como V

      Parámetros: ninguno

      Explicación: devuelve el volumen de operaciones de este período

      Datos de secuencia

      VOL obtains the trading volume of the K-line chart.
      
      Remarks:
       It can be abbreviated as V.
      The return value of this function on the current TICK is the cumulative value of all TICK trading volume on that day.
      
      Example 1:
      VV:=V;       // Define VV as the trading volume
      Example 2:
      REF(V,1);    // Indicates the trading volume of the previous period
      Example 3:
      V>=REF(V,1); // The trading volume is greater than the trading volume of the previous period, indicating that the trading volume has increased (V is the abbreviation of VOL)
      
    • OPI

      Tome la posición total actual en el mercado de futuros (contratos).

      OpenInterest:OPI;
      
    • El REF

      Citación en el futuro.

      Reference the value of X before N periods.
      
      Remarks:
      1.When N is a valid value, but the current number of K-lines is less than N, returns null;
      2.Return the current X value when N is 0;
      3.Return a null value when N is null.
      4.N can be a variable.
      
      Example 1:
      REF(CLOSE,5);Indicate the closing price of the 5th period before the current period is referenced
      Example 2:
      AA:=IFELSE(BARSBK>=1,REF(C,BARSBK),C);//Take the closing price of the K-line of the latest position opening signal
      // 1)When the BK signal is sent, the bar BARSBK returns null, then the current K-line REF(C, BARSBK) that sends out the BK signal returns null;
      // 2)When the BK signal is sent out, the K-line BARSBK returns null, and if BARSBK>=1 is not satisfied, it is the closing price of the K-line.
      // 3)The K-line BARSBK after the BK signal is sent, returns the number of periods from the current K-line between the K-line for purchasing and opening a position, REF(C,BARSBK)
      Return the closing price of the opening K-line.
      // 4)Example: three K-lines: 1, 2, and 3, 1 K-line is the current K-line of the position opening signal, then returns the closing price of the current K-line, 2, 3
      The K-line returns the closing price of the 1 K-line.
      
    • Unidad

      Consigue la unidad de negociación del contrato de datos.

      Get the trading unit of the data contract.
      Usage:
      UNIT takes the trading unit of the loaded data contract.
      

      Venta al contado de criptomonedas

      El valor UNIT es 1.

      Futuros de criptomonedas

      El valor UNIT está relacionado con la moneda del contrato.

      OKEX futures currency standard contracts: 1 contract for BTC represents $100, 1 contract for other currencies represents $10
      
    • Precio mínimo

      El precio mínimo de variación del contrato de datos.

      Take the minimum variation price of the data contract.
      Usage:
      MINPRICE; Take the minimum variation price of the loaded data contract.
      
    • Precio mínimo1

      El precio mínimo de variación de un contrato de negociación.

      Take the minimum variation price of a trading contract.
      Usage:
      MINPRICE1; Take the minimum variation price of a trading contract.
      
  • Función de tiempo

    • Las barras

      Toma la posición de la línea K.

      BARPOS, Returns the number of periods from the first K-line to the current one.
      
      Remarks:
      1.BARPOS returns the number of locally available K-line, counting from the data that exists on the local machine.
      2.The return value of the first K-line existing in this machine is 1.
      
      Example 1:LLV(L,BARPOS);        // Find the minimum value of locally available data.
      
      Example 2:IFELSE(BARPOS=1,H,0); // The current K-line is the first K-line that already exists in this machine, and it takes the highest value, otherwise it takes 0.
      
    • El día

      DAYBARPOS el actual K-line BAR es el K-line BAR del día.

    • Periodo

      El valor del período es el número de minutos.

      1, 3, 5, 15, 30, 60, 1440
      
    • DATOS

      Fecha en la que se produjoFunción DATE, Obtener el año, mes y día del período desde 1900.

      Example 1:
      AA..DATE;                  // The value of AA at the time of testing is 220218, which means February 18, 2022
      
    • Tiempo

      Es el momento de tomar la línea K.

      TIME, the time of taking the K-line.
      
      Remarks:
      1.The function returns in real time in the intraday, and returns the starting time of the K-line after the K-line is completed.
      2.This function returns the exchange data reception time, which is the exchange time.
      3.The TIME function returns a six-digit form when used on a second period, namely: HHMMSS, and displays a four-digit form on other periods, namely: HHMM.
      4.The TIME function can only be loaded in periods less than the daily period, and the return value of the function is always 1500 in the daily period and periods above the daily period.
      5. It requires attention when use the TIME function to close a position at the end of the day
      (1).It is recommended to set the time for closing positions at the end of the market to the time that can actually be obtained from the return value of the K-line (for example: the return time of the last K-line in the 5-minute period of the thread index is 1455, and the closing time at the end of the market is set to TIME>=1458, CLOSEOUT; the signal of closing the position at the end of the market cannot appear in the effect test)
      (2).If the TIME function is used as the condition for closing the position at the end of the day, it is recommended that the opening conditions should also have a corresponding time limit (for example, if the condition for closing the position at the end of the day is set to TIME>=1458, CLOSEOUT; then the condition TIME needs to be added to the corresponding opening conditions. <1458; avoid re-opening after closing)
      
      Example 1:
      C>O&&TIME<1450,BK;
      C<O&&TIME<1450,SK;
      TIME>=1450,SP;
      TIME>=1450,BP;
      AUTOFILTER;
      // Close the position after 14:50.
      Example 2:
      ISLASTSK=0&&C>O&&TIME>=0915,SK;
      
    • Año

      Year.

      YEAR, year of acquisition.
      
      Remark:
      The value range of YEAR is 1970-2033.
      
      Example 1:
      N:=BARSLAST(YEAR<>REF(YEAR,1))+1;
      HH:=REF(HHV(H,N),N);
      LL:=REF(LLV(L,N),N);
      OO:=REF(VALUEWHEN(N=1,O),N);
      CC:=REF(C,N);                               // Take the highest price, lowest price, opening price, and closing price of the previous year
      Example 2:
      NN:=IFELSE(YEAR>=2000 AND MONTH>=1,0,1);
      
    • Mes de trabajo

      Toma el mes.

      MONTH, returns the month of a period.
      
      Remark:
      The value range of MONTH is 1-12.
      
      Example 1:
      VALUEWHEN(MONTH=3&&DAY=1,C);                // Take its closing price when the K-line date is March 1
      Example 2:
      C>=VALUEWHEN(MONTH<REF(MONTH,1),O),SP;
      
    • DÍA

      Obtener el número de días en un período

      DAY, returns the number of days in a period.
      
      Remark:
      The value range of DAY is 1-31.
      
      Example 1:
      DAY=3&&TIME=0915,BK;                      // 3 days from the same day, at 9:15, buy it
      Example 2:
      N:=BARSLAST(DATE<>REF(DATE,1))+1;
      CC:=IFELSE(DAY=1,VALUEWHEN(N=1,O),0);      // When the date is 1, the opening price is taken, otherwise the value is 0
      
    • Horario de trabajo

      Hour.

      HOUR, returns the number of hours in a period.
      
      Remark:
      The value range of HOUR is 0-23
      
      Example 1:
      HOUR=10;                                   // The return value is 1 on the K-line at 10:00, and the return value on the remaining K-lines is 0
      
    • ¿Qué es esto?

      Minute.

      MINUTE, returns the number of minutes in a period.
      
      Remarks:
      1: The value range of MINUTE is 0-59
      2: This function can only be loaded in the minute period, and returns the number of minutes when the K-line starts.
      Example 1:
      MINUTE=0;                                 // The return value of the minute K-line at the hour is 1, and the return value of the other K-lines is 0
      Example 2:
      TIME>1400&&MINUTE=50,SP;                   // Sell and close the position at 14:50
      
    • DÍA de la semana

      Consigue el número de la semana.

      WEEKDAY, get the number of the week.
      
      Remark:
      1: The value range of WEEKDAY is 0-6. (Sunday ~ Saturday)
      
      Example 1:
      N:=BARSLAST(MONTH<>REF(MONTH,1))+1;
      COUNT(WEEKDAY=5,N)=3&&TIME>=1450,BP;
      COUNT(WEEKDAY=5,N)=3&&TIME>=1450,SP;
      AUTOFILTER;                               // Automatically close positions at the end of the monthly delivery day
      Example 2:
      C>VALUEWHEN(WEEKDAY<REF(WEEKDAY,1),O)+10,BK;
      AUTOFILTER;
      
  • Función de juicio lógico

    • Las demás especies

      Devuelva el estado de la posición para el período actual.

      BARSTATUS returns the position status for the current period.
      
      Remark:
      The function returns 1 to indicate that the current period is the first period, returns 2 to indicate that it is the last period, and returns 0 to indicate that the current period is in the middle.
      
      Example:
      A:=IFELSE(BARSTATUS=1,H,0);              // If the current K-line is the first period, variable A returns the highest value of the K-line, otherwise it takes 0
      
    • En el medio

      Between.

      BETWEEN(X,Y,Z) indicates whether X is between Y and Z, returns 1 (Yes) if established, otherwise returns 0 (No).
      
      Remark:
      1.The function returns 1(Yse) if X=Y, X=Z, or X=Y and Y=Z.
      
      Example 1:
      BETWEEN(CLOSE,MA5,MA10);                // It indicates that the closing price is between the 5-day moving average and the 10-day moving average
      
    • El último conde.

      BARSLASTCOUNT(COND) cuenta el número de períodos consecutivos que satisfacen la condición, contando hacia adelante desde el período actual.

      Remark:
      1. The return value is the number of consecutive non zero periods calculated from the current period
      2. the first time the condition is established when the return value of the current K-line BARSLASTCOUNT(COND) is 1
      
      Example:
      BARSLASTCOUNT(CLOSE>OPEN);
      //Calculate the number of consecutive positive periods within the current K-line
      
    • Las demás

      Función cruzada.

      CROSS(A,B) means that A crosses B from bottom to top, and returns 1 (Yes) if established, otherwise returns 0 (No)
      
      Remark:
      1.To meet the conditions for crossing, the previous k-line must satisfy A<=B, and when the current K-line satisfies A>B, it is considered to be crossing.
      
      Example 1:
      CROSS(CLOSE,MA(CLOSE,5));              // Indicates that the closing line crosses the 5-period moving average from below
      
    • En el caso de los productos

      Descenso

      CROSSDOWN(A,B): indicates that when A passes through B from top to bottom, it returns 1 (Yes) if it is established, otherwise it returns 0 (No)
      
      Remark:
      1.CROSSDOWN(A,B) is equivalent to CROSS(B,A), and CROSSDOWN(A,B) is easier to understand
      
      Example 1:
      MA5:=MA(C,5);
      MA10:=MA(C,10);
      CROSSDOWN(MA5,MA10),SK;               // MA5 crosses down MA10 to sell and open a position
      // CROSSDOWN(MA5,MA10),SK; Same meaning as CROSSDOWN(MA5,MA10)=1,SK;
      
    • Las demás:

      Crossup.

      CROSSUP(A,B) means that when A crosses B from the bottom up, it returns 1 (Yes) if it is established, otherwise it returns 0 (No)
      
      Remark:
      1.CROSSUP(A,B) is equivalent to CROSS(A,B), and CROSSUP(A,B) is easier to understand.
      
      Example 1:
      MA5:=MA(C,5);
      MA10:=MA(C,10);
      CROSSUP(MA5,MA10),BK;                 // MA5 crosses MA10, buy open positions
      // CROSSUP(MA5,MA10),BK;与CROSSUP(MA5,MA10)=1,BK; express the same meaning
      
    • Todo el mundo

      Determinar si se satisface continuamente.

      EVERY(COND,N), Determine whether the COND condition is always satisfied within N periods. The return value of the function is 1 if it is satisfied, and 0 if it is not satisfied.
      
      Remarks:
      1.N contains the current K-line.
      2.If N is a valid value, but there are not so many K-lines in front, or N is a null value, it means that the condition is not satisfied, and the function returns a value of 0.
      3.N can be a variable.
      
      Example 1:
      EVERY(CLOSE>OPEN,5);                // Indicates that it has been a positive line for 5 periods
      Example 2:
      MA5:=MA(C,5);                       // Define a 5-period moving average
      MA10:=MA(C,10);                     // Define a 10-period moving average
      EVERY(MA5>MA10,4),BK;               // If MA5 is greater than MA10 within 4 periods, then buy the open position
      // EVERY(MA5>MA10,4),BK; has the same meaning as EVERY(MA5>MA10,4)=1,BK;
      
    • Existen

      Determine si hay satisfacción.

      EXIST(COND, N) judges whether there is a condition that satisfies COND within N periods.
      
      Remarks:
      1.N contains the current K-line.
      2.N can be a variable.
      3.If N is a valid value, but there are not so many K-lines in front, it is calculated according to the actual number of periods.
      
      Example 1:
      EXIST(CLOSE>REF(HIGH,1),10);     // Indicates whether there is a closing price greater than the highest price of the previous period in 10 periods, returns 1 if it exists, and returns 0 if it does not exist
      Example 2:
      N:=BARSLAST(DATE<>REF(DATE,1))+1;
      EXIST(C>MA(C,5),N);              // Indicates whether there is a K-line that satisfies the closing price greater than the 5-period moving average on the day, returns 1 if it exists, returns 0 if it does not exist
      
    • Si es

      Función de condición.

      IF(COND,A,B)Returns A if the COND condition is true, otherwise returns B.
      
      Remarks:
      1.COND is a judgment condition; A and B can be conditions or values.
      2.This function supports the variable circular reference to the previous period's own variable, that is, supports the following writing Y: IF(CON,X,REF(Y,1)).
      Example 1:
      IF(ISUP,H,L);                   // The K-line is the positive line, the highest price is taken, otherwise the lowest price is taken
      Example 2:
      A:=IF(MA5>MA10,CROSS(DIFF,DEA),IF(CROSS(D,K),2,0));     // When MA5>MA10, check whether it satisfies the DIFF and pass through DEA, otherwise (MA5 is not greater than MA10), when K and D are dead fork, let A be assigned a value of 2, if none of the above conditions are met, A is assigned a value of 0
      A=1,BPK;                                                // When MA5>MA10, the condition for opening a long position is to cross DEA above the DIFF
      A=2,SPK;                                                // When MA5 is not greater than MA10, use K and D dead forks as the conditions for opening short positions
      
    • - ¿Por qué no?

      Función de condición.

      IFELSE(COND,A,B) Returns A if the COND condition is true, otherwise returns B.
      
      Remarks:
      1.COND is a judgment condition; A and B can be conditions or values.
      2.This function supports variable circular reference to the previous period's own variable, that is, supports the following writing Y: IFELSE(CON,X,REF(Y,1));
      Example 1:
      IFELSE(ISUP,H,L);                                             // The K-line is the positive line, the highest price is taken, otherwise the lowest price is taken
      Example 2:
      A:=IFELSE(MA5>MA10,CROSS(DIFF,DEA),IFELSE(CROSS(D,K),2,0));   // When MA5>MA10, check whether it satisfies the DIFF and pass through DEA, otherwise (MA5 is not greater than MA10), when K and D are dead fork, let A be assigned a value of 2, if none of the above conditions are met, A is assigned a value of 0
      A=1,BPK;                                                      // When MA5>MA10, the condition for opening a long position is to cross DEA above the DIFF
      A=2,SPK;                                                      // When MA5 is not greater than MA10, use K and D dead forks as the conditio

Relacionados

Más.