|
The SLANG is a general purpose scripting language. It can be used to perform data processing, charting, to do input and output operations and so on. It can also access the functionality of a program that is using it, giving you the interface to program's functions, in automatic mode, without the need for user input. The functions are implemented in few DLLs, each group covering certain area. This Reference Guide follows the same structure. This DLL contains set of functions implementing a BASIC-like language. The language supports a traditional set of operations: +, -, *, /, % (remainind part after division), ^(power) Used as "condition" part in "if" and "for". Supported logical operations are: && (AND), || (OR), == (equal), != (not equal), < (less than), > (greater than), <=, >= There are four types of variables in SLANG: number, string, array of numbers and array of strings. We need to declare them, before we use them:
double x; double y = 0; string str = "Hello"; array arr = CREATE_ARRAY(0); array_ arr_s = CREATE_ARRAY_S(0); Notice, that we can create numeric or string variables, and later assign the values to them. As for arrays, they have to be created by calling the CREATE_ARRAY or CREATE_ARRAY_S functions. The reason for it is rather simple - in our scripting language we have three different types of arrays: not sorted, sorted and sorted with no duplicated values. We create them by passing 0, 1 and 2 to the CREATE_... function. Be careful with the sorted arrays - there are things you can not do with them. Let's say, you want to alter 5th element of an array: arr[5] = 3; It is OK if an array is not sorted, but what if it was sorted? For example, what if it had 10, 20, 30, and 40? By inserting "3" into the 5th array's element, you will ruin the sorting! To avoid these sort of problems, use the following approach. If the array is unsorted (0 was passed when it was created), you can assign values to its elements using assignment, like in arr[5] = 3; If an array is sorted, you have to use built-in functions of the scripting language. For example, you can add an element to the sorted array by calling double nPos = ARRAY_ADD(arr, dValue); This function will add dValue to the correct (according to sorting) position, and return the index of a new element in array. For example, if we want to insert 3 into the sorted array that already has elements 2, 4, 5, the resulting array will be 2, 3, 4, 5 and the nPos, returned by the ARRAY_ADD function will be equal 1 (indices in arrays are zero-based, 0, 1, 2...). An important advantage of using arrays is the fact that you can use them in cycle, using the cycle variable as an array index.
for(i = 0; i < 10; i = i + 1) { arr[i] = 2 * i; } The //is used to comment code to the end of line. The /*...*/is a block comment. The program exacution begins with "main" function. All other functions are called from "main", and when "main" code is over, the script stops. The "main" function is an example of "user-defined" functions. Other functions can be created as well, provided that they don't use names, that are reserved for built-in functions. A user-defined function can return value, using the returnoperator, in this case, it can be used in expressions: x = UserFunction(y); Note, that all control paths of a function must return the same type: double MyFunc(double x) { if(x == 3) { return 3; } return "Hello"; //WRONG ! } A user-defined function can receive parameters:
double MyFunc(double x, array arr, ...) Check the logical condition and execute or skip corresponding code. if(x > 3 && y < 5) { ... do something ... } else { ... do something else ... } The "else" block is not mandatory. The cycle works as follows: for(i = nInitialValue; condition; i = nNewValue) { ... break i; // break from the (nested) cycle(s) ... continue i; // go back to the beginning of the cycle ... } The initial value should be assigned, it can not be a call to a function, that sets the value, but an explicit assignment. The cycle continues for as long as the Condition is true. Assignment of a new value of a cycle variable can increase or decrease its value, for example i = i + 1. "break i" directive is used to BREAK from the cycle (to pass control to the next operator after the cycle's body) that has the specified cycle variable. "continue i" directive is used to move to the next cycle, ignoring whatever code is after the "continue". arrCoefs = LESS_SQUARE(arrX, arrY, nFirst, nLast); Returns an array, containing two elements. The first element contains a, the second element contains b, where Y = a*X + b. array arr = CREATE_ARRAY(0); array arr_s = CREATE_ARRAY_S(0); Variables of array and array_s types have to be declared, as any other types. In addition, arrays have to be created by calling the CREATE_ARRAY or CREATE_ARRAY_S functions. The reason for it is rather simple - in SLANG we have three different types of arrays: not sorted, sorted and sorted with no duplicated values. We create them by passing 0, 1 and 2 to the CREATE_... function. Be careful with the sorted arrays - there are things you can not do
with them. Let's say, you want to alter 5th element of an array:
arr[5] = 3; It is OK if an array is not sorted, but what if it was sorted? For example, what if it had 10, 20, 30, and 40? By inserting "3" into the 5th array's element, you will ruin the sorting! To avoid these sort of problems, use the following approach. If the array is unsorted (0 was passed when it was created), you can assign values to its elements using assignment, like in arr[5] = 3; If an array is sorted, you have to use built-in functions of the scripting language. For example, you can add an element to the sorted array by calling double nPos = ARRAY_ADD(arr, dValue); This function will add dValue to the correct (according to sorting) position, and return the index of a new element in array. For example, if we want to insert 3 into the sorted array that already has elements 2, 4, 5, the resulting array will be 2, 3, 4, 5 and the nPos, returned by the ARRAY_ADD function will be equal 1 (indices in arrays are zero-based, 0, 1, 2...). An important advantage of using arrays is the fact that you can use them in cycle, using the cycle variable as an array index.
for(i = 0; i < 10; i = i + 1) { arr[i] = 2 * i; } PAUSE(nTimeout); Suspends a program for the specified number of milliseconds. hVarList = WRAP_CREATE(); The way SLANG works with arrays (array, array_s) makes it impossible to have, say, array of arrays, or array of variables. However, it is often necessary. Example: In Stock Downloader script, we need to perform two different tasks. The first time we run the script, we need to load the previously saved stock or Forex quotes from disk. We do not know in advance, how many arrays it will create, because it depends on the number of stock / forex symbols the user specified. The second time we run the script, and every next time (it is called by the timer), we only need to add new quotes to already existing arrays, without spending time on downloading the same data again. Therefore, we need an "array of arrays", or array of wariables. In SLANG, we use the concept of a wrapper. Working with wrappers is similar to working with files: you need to get a handle. A handle represents an array of variables, for example, arrays (you can mix variables of different types in a single array). If we used copies of variables, then, especially in case of arrays, accessing the data would be slow. To make the process faster, we use so called references. Please read the explanations below, to avoid frustrations. 1. When we create a wrapper using WRAP_CREATE, we create an empty array of a special type. 2. To add a variable to this array, you need to call WRAP_ADD, to remove it, call WRAP_REMOVE. The variable in the array is a COPY of the original variable. 3. To "get" the element of a wrapper, you need to call WRAP_GET. The way it works is by making the data (for example, an array) of the new variable to point to the data, that a wrapper holds. When you change the variable (for example, by adding an element to an array, or changing its value), the data in a wrapper are changing as well. Therefore, by calling the WRAP_GET, you are creating an alias for an element of a wrapper. 4. What if you are trying to create an alias for an element of a wrapper, that already have an alias? Then the previous alias is "released". Its value will be reset to a default. For example, if you have an array (arr), and you call WRAP_ADD(handle, arr), the wrapper, that is referred to by a handle "handle" will be added a copy of "arr". Then, if you create an alias, by calling WRAP_GET(handle, arr1, nPos), then the arr1 will POINT to the data, that the wrapper's element contains. Finally, if you call WRAP_GET(handle, arr2, nPos), then arr2 will point to the wrapper's element, while arr1 will contain an empty array, and not a "pointer". nPos = WRAP_ADD(hList, var); Adds a copy of the variable "var" to the wrapper. For details, see the WRAP_CREATE WRAP_REMOVE(hList, nPos); Removes an element from the wrapper. if there is a variable, pointing to this element, its value will be reset. For details, see the WRAP_CREATE WRAP_GET(hList, var, nPos); Create an alias for the element (with the index nPos) of a wrapper. After the call, "var" points to the element of a wrapper. For details, see the WRAP_CREATE WRAP_CLOSE(hVarList); Delete a wrapper, reset all variables that were pointing on it. For details, see the WRAP_CREATE #include "strFileName" Includes file (containing SLANG code) in the current script. This approach allows to use same external "library", instead of pasting the same code in every script that need it. The file is included in the exact place where #include directive is located, so if it uses variables, defined in the parent file, you need to make sure they are already defined. The path is either a full path ("c:\s_projects\cortex...") or a path relative to the location of Cortex.exe ("..\CortexPro\data\samples\scripts\myscript.tsc"). This DLL contains mathematical functions and some data conversion routines. double nSize = ARRAY_SIZE(arr); Returns the size of an array. This function can take both array and array_s types of parameters. nPos = ARRAY_ADD(arr, dValue); or nPos = ARRAY_ADD(arr_s, strValue); Add a new element to an array, according to a sorting rules. If successfull, return the index of a new entry, if failed (for example, the elemetn already present and array allows no duplication) returns -1. dValue = ARRAY_REMOVE(arr, nIdx); or strValue = ARRAY_REMOVE(arr_s, nIdx); Removes an element, and returns it. nPos = ARRAY_FIND(arr, dValue); or nPos = ARRAY_FIND(arr_s, strValue); Returns an index of the array's element, or -1, if not found. nPos = ARRAY_INSERT(arr, dValue, nIdx); or nPos = ARRAY_INSERT(arr_s, strValue, nIdx); Insert an element in the specified position. Returns an index. If an array is sorted, a new element will be inserted according to a sort order, and nIdx will be ignored. ARRAY_TRUNCATE(arr, nIdxFirst, nIdxLAst); or ARRAY_TRUNCATE(arr_s, nIdxFirst, nIdxLAst); Truncates an array. double dSum = ARRAY_SUM(arr, nFirst, nLast); Returns sum of elements of an array, nFirst is the first index, nLast is the last index. For example, to calculate sum of first 10 elements, use dSum = ARRAY_SUM(arr, 0, 9); Use -1 for max and min indexes (same applies to all functions of this kind, like ARRAY_MIN etc) double dSum = ARRAY_SUMSQ(arr, nFirst, nLast); Returns sum of squared elements of an array: x[i]^2 + x[i + 1]^2... dSumXmY2 = ARRAY_SUMXMY2(arr1, arr2, nFirst, nLast); Returns sum of (arr1[i] - arr2[i])^2 dAverage = ARRAY_AVG(arr, nFirst, nLast); Returns sum of array elements divided by the number of elements. dMax = ARRAY_MAX(arr, nFirst, nLast); Returns maximum value of an array element (for the given interval of indices). dMax = ARRAY_MIN(arr, nFirst, nLast); Returns minimum value of an array element (for the given interval of indices). arrMinMax = ARRAY_MIN_MAX(arr, nFirst, nLast); Returns an array of four elements, first containing minimum value of an array elements (for the given interval of indices), the second one containing the maximum, third containing the index of the minimum element, fourth containing the index of the maximum element. Note: if there are more than one min. or max. values in the selected range (more then one point has min or max value), the index contains the location of the first occurence.
arrResult = MV_XXX(arrSrc, nInterval); Returns an array, containing moving average, exponential moving average, moving maximum, moving minimum, or moving sum. dNextExpMa = NEXT_EXP_MA(arrMa, dMaInterval, dValue); Often, data arrive one record in a time, and to process it in real time, we cannot call EXP_MV_AVG every time. This function takes an array of previously calculated MA values, the next number, and calculates next MA. Note, that the new value is not added to the array - you have to do it yourself. dMax = MAX(dX, dY); Returns larger or smaller of two numbers. y = F(x);, where F can be: CEIL - closest integer above x FLOOR - closest integer below x SIN, COS, TAN, ASIN, ACOS, ATAN, COSH, SINH, TANH ABS, EXP, LOG (e), LG (10) DEGREES - converts radians to degrees RADIANS - converts degrees to radians FACT - factorial RAND - random number between 0 and x strDate = REAL_TO_DATE(nDate); Dates and time are processed as numbers. Dates are in days, time - in minutes. To convert these numbers between the form that scripting engine understands and human-readable form, we use these two functions. List of supported formates: 15-01-99, 01-Jan-1999, 01-Jan-99, 10/7/2003, 10/7/03, 10.07.2004, 15-01-1999, 2002.08.15 strTime = REAL_TO_TIME(nTime); bResult = F_MAKEDIR(strDirName); Creates a directory. This function can create only one new directory per call, it means that only one (last) subdirectory or the path can be a new directory. handle = F_OPEN(strFileName, strMode, bIsPathRelative = 0); Open the file, return a file handle, number that is used by other file accessing functions, or -1 if failed. strMode can be "w" - write, "r" - read, "a" - append, also it may be text "t" or binary "b". Third argument can be omitted, default value is 0
(full path is used). 1 stands for path, relative to
the location of EXE file (BIN folder).
For a complete list of file access modes, see fopen function in online C or C++ tutorials. F_PRINT(hFile, strFormat, xArgument, ...); PRINT function is used to perform text output to the window, called Output Panel. F_PRINT can either print to file, or - if you pass it -1 as a file handler - to the same window as PRINT. strFormat is a format string. For strings, you need to use "%s", for numbers - "%f". It is possible to add extra text to the format string, for example: PRINT("x = %f", x, ", y = %f", y); Format strings follow the C language specs, full description of all details can be found in online articles about printf function of C or C++ language. Here we only list the most useful things. Number of decimal places to be printed: "%2.2f" means that 2 digits will be printed before decimal point and 2 - after. "%.0f" prints integer, no decimals. \t prints tabulation. \r\n prints a new line: PRINT("x = %f\r\n", x); "%00.0f" prints two digits, for example 05, it can be useful, when you print time or dates. bIsEof = F_EOF(hFile); Returns 1 if the file cursor is at the end of file, 0 otherwise. str = F_GETS(hFile); Reads a string from the file, until finds end of file, or a new line. bResult = F_READ(hFile, strBuffer, nLen); Reads up to nLen bytes from hFile to strBuffer variable. Returns number of bytes actually read. bResult = F_WRITE(hFile, strBuffer); Writes data (string) from the strBuffer variable to file. Returns 1 if successful, 0 otherwise. bResult = F_SEEK(hFile, nOffset, nSeekType); Moves the file cursor. The distance to move is set by nOffset. Depending on nSeekType, cursor moves:
bResult = F_RENAME(strOldName, strNewName); Renames the file, returns 1 if successful, 0 if failed. bResult = F_COPY(strOldName, strNewName); Creates a copy of a file, returns 1 if successful, 0 if failed. nPos = F_GETPOS(hFile); Returns a position of the file cursor. bResult = F_UNLINK(strFileName); Deletes the file from disk, returns 0 if failed, 1 - if successfull. F_CLOSE(hFile); Close file, previously opened by F_OPEN. It is strongly recommended to close files that are not used, to free system resources. Also, until you close file, there is no guarantee, that the writing into this file is completed. bResult = F_EXE(strFileName); Runs an external executable file (including .BAT files). Returns 0 if failed, 1 if succeded. The function waits for the EXE to finist its work, before it continues. For example, if you run an external .BAT file, that processes 10000 photos, the script will resume only after photos are processed (or command window is manually closed). nNumOfRecords = TABLE_LOADER(strFullPath, bIsRelative, bReverse, strStartPattern, strSkipAfterStartPattern, strEndPattern, nCol_1, arr_1, ...); Used to load data from a disk file to the set of arrays, one array per column. Return value: number of records that was successfully processed. or -1, if failed (for example, no such file). Arguments: strFullPath - location of the file to be loaded bIsRelative - 0, if it is a complete path, and 1 if the path is relative to the location of the program's executable. For example: c:\\s_projects\\CortexPro\\data\\samples\\stocks\\msft.txt bReverse - should arrays that we loaded, be reversed, for example, if the stock quotes file contains newest data first, and we want them last. strStartPattern - a line, AFTER which meaningfull data begin. Used, if we need to skip the file's header. "" (empty string) if none. strSkipAfterStartPattern - number of lines to skip AFTER the startPattern (or beginning of file, if start pattern is "". strEndPattern - string, where to stop, "" if we want to go till the end of file. nCol_1 - the first column to load arr_1 - array (a variable, previously declared) that will get data from the first column. ... there can be more nCol_i, arr_i pairs, if we want to load more than one column. strBuffer = LOAD_FILE(strFilName); Loads file to a string buffer. Get full path from relative (to Cortex's Bin directory). string strFullPath = GET_FULL_PATH(strRelativePath);strToken = GET_TOKEN(strSrc, strDelimiters);
nLegendsColor - color of text labels nGridStyle - style of a grid;
nGridColor - color of the grid lines nLineWidth - width if the lines on chart. nTickWidth - width of ticks nAxesSet - which axes to draw 1 - X axe at the bottom of a chart,
PLOT(nSeriesNumber, arrX, arrY, arrShifts); arrShifts parameter is optional, it is only required for bar and stacked bar charts. Array of shifts is 2 times larger than x and y arrays. It contains information about shifts of bars in BAR_GRAF or BAR_3D_GRAF. s[2*i] contains negative and s[2*i+1] - positive shifts. After every call to this function shifts[] will be modified. Initial values of array elements at first call should be 0. In the case of the stacked bar graphs, the arrDelta array is provided. It is 4 times bigger than the size of data. It can also be used in the case of the chart with deviations (deltax1, deltay1, deltax2, deltay2) Parameters: nSeriesNumber - number of a dataset, zero-based. arrX, arrY - X and Y data to plot. arrShifts - create this array, fill it with 0 and pass to the function. See SAMPLE_07.TSC for an example. MARKER_SET_COLOR(nColor16, nBack16, bFill); Set color, background color and fill flag for the dataset's marker. CONNECTOR_SET_COLOR(nColor16, nBack16, bFill); Set color, background color and fill flag for the dataset's connector. strXML = SAVE_CHART(dWidth, dHeight, bDateX, strFileName, arrX, arrY_1, ...optional arr 2, ...); Creates the line chart and saves it on disk. Returns XML code that can be used to create a web page containing this chart (or can be ignored, it not required). Parameters: dWidth, dHeight - dimensions of the chart, pixels. bDateX - 0 if X axe is numeric, 1 if it contains numbers that should be converted to dates. strFileName - name of the file to create. arrX_1, arrY_1, ...optional arr 2, ...
strXML = SAVE_CHART(dWidth, dHeight, bDateX, strFileName, arrX_1, arrY_1, ...optional arrX_2, arrY_2...); Similar to SAVE_CHART, except X arrays are different for each dataset. strXML = SAVE_CHART_INTRADAY(dWidth, dHeight, strFileName, nNumOfDaysToShow, nMinutesInTheDay, nStartTime, arrDate1, arrTime1, arr1, ...optional arrDate2, arrTime2, arr2, ...); Creates a PNG file, containing intraday (minutes) chart. The dates array contains one date per each time: 01-Jan-2003, 10:00 ...
Dates and times are converted to numbers using DATE_TO_REAL and TIME_TO_REAL functions. Creates the line chart and saves it on disk. Returns XML code that can be used to create a web page containing this chart (or can be ignored, it not required). Parameters: dWidth, dHeight - dimensions of a chart, pixels. strFileName - file name to create nNumOfDaysToShow - allows you to display only last few days, which can be useful, if the chart is too long. nMinutesInTheDay. Used for situations, when we only need part of the day. For example, stock market closes at 5 pm, so we don't need to plot anything between 17.00 and 24.00 nStartTime - same as with nMinutes in the day. For example, the market may open in 9.00. arrDate1, arrTime1, arrY1, ...optional arrDate2, arrTime2, arrY2, ... - data to plot strXML = SAVE_CHART_SMOOTH(arrColors, dWidth, dHeight, bDateX, strFileName, // arrDate, arr_1, ...optional arr 2, ...); Similar to SAVE_CHART, except, it draws the first line, using colors from arrColors. It allows to create a chart, where color changes smoothly - think of marking trends on the stock price chart. Colors are in RGB form. SAVE_XML(strFullPath, "xml_file_name", "xsl_file_name", "root", strXML); As we are saving charts, using SAVE_CHART... functions, we get XML strings, each can be used to show the chart at the Web page. Then we can add these strings, to create a code for a web page, that has more than one chart on it: void Chart() { string strXML = ""; strXML = strXML + "<stocks>"; string strPath = "c:\\S_Projects\\CortexPro\\data\\samples\\images\\"; string strStockName = "genz"; string strFullPath = strPath + strStockName + ".png"; string strNeuralPath = strPath + strStockName + "_neural.png"; strXML = strXML + "<symbol>"; strXML = strXML + "<symbol>"; strXML = strXML + strStockName; strXML = strXML + "</symbol>"; strXML = strXML + SAVE_CHART(400, 200, 1, strFullPath, arrDate, arrClose); strXML = strXML + SAVE_CHART(400, 200, 1, strNeuralPath, arrDate, arrNN); strXML = strXML + "</symbol>"; strXML = strXML + "</stocks>"; SAVE_XML(strPath, "chart_dayend", "chart_dayend", "root", strXML); SHOW_XML(strPath + "chart_dayend.xml"); } (To get more information about XML, visit Free online XML tutorial Finally, to get a complete, working, XML file we need to add some decorations to the string we created. That is what the SAVE_XML does. Parameters: strFullPath - path to the file to be created, without file name (see the example above). "xml_file_name" - name of the xml file to create. "xsl_file_name" - name of the XSL file that XML file is using. "root" - name of the root of the XML tree strXML - the string we created. END_DRAWING(); Finish the drawing session and show the result in Drawing Pane. This DLL takes care of the Internet access via HTTP protocol. bResult = OPEN_HTTP_SESSION(); Opens HTTP session. Returns 1 if successfull, 0 otherwise. bResult = GET_HTTP(strURL, strFileName); Downloads a file from the Internet via HTTP protocol and saves it to strFileName file. bResult is 0 if failed, 1 if successful. CLOSE_HTTP_SESSION(); Closes a previously opened HTTP session. SHOW_XML(strFullPath); Opens a file (XML, HTML, text...) in Internet Explorer. strPageSource = SHOW_XML_EX(strFullPath); Opens a file (XML, HTML, text...) in Internet Explorer, and waits (i.e. pauses the script) until the page is fully loaded. Returns the HTML source for the target page. RUN_JSCRIPT(strJScript, strArg1, ...); If there is a Java Script function on the HTML page, then you can run it, after the page is opened (say, using a call to SHOW_XML). The first argument refers to a function name, optional second etc arguments contain arguments to be passed to a function. strValue = HTML_GET_ELEMENT (strAttributeName, strId); Retrieves a value for a given element of HTML form (of HTML file, opened in IE window, by calling SHOW_XML). The first element contains the element name (say, "value"), the second argument contains element name or ID. Example: strValue = HTML_GET_ELEMENT("value", "given_name") HTML_SET_ELEMENT(strValue, strAttributeName, strId); Sets the value for a form element (of HTML file, opened in IE window, by calling SHOW_XML). The first argument refers to the value to be set, the second contains the property name (say, "value"), the third one contains form element's id or name. Example: HTML_SET_ELEMENT("Hello", "value", "given_name"); HTML_CLICK(strId, nTimeout = -1); Simulates a click on an element (of HTML file, opened in IE window, by calling SHOW_XML), specified by strId (id or name). Sometimes (usually, when Java Script in one frame is trying to open web pages in the other, the function hangs, which means, the "Working..." dialog does not disappear. To fix the problem, you can use the second argument, providing maximum wait time, in milliseconds. FTP_OPEN(strSite, strLogin, strPassword, nIsBinary, bIsPassive, nPort); Opens FTP session.
FTP_UPLOAD(strFileName, strTargetDir); Uploads a file from local disk to FTP location. strFileName is the full path, a file with same name will be created at destination. If we want to copy file to the root, pass an empty string ("") as strTargetDir, otherwise the program will try to create this dir and to copy file there. FTP_CLOSE(); Terminates the FTP session. hNN = OPEN_NN(strPath, bIsPathRelative); Returns the handle of Cortex Neural Network, -1 if failed. Handles of opened Neural Networks are used in a way, similar to the use of file handles. Parameters: strPath - name of the NN file. bIsRelative. Specifies if the strPath contains full path to the file (0) or if this path is relative to the location of program's EXE file. For example: hNN = OPEN_NN("..\Cortex\data\jaco.nn", 1); SAVE_NN(hNn, strPath); Saves NN to disk file. Note, that this function ONLY writes the NN description, not the information for UI dialogs used by Cortex (like number of lines to skip in data file etc). It means, that you will only be able to open this file using script OPEN_NN, but not from the Cortex UI. For Cortex UI compatible NNs, use SAVE_NN_EX. SAVE_NN_EXSAVE_NN_EX(hNn, strFileName, strLagDataFile, nSkipBefore, nSkipAfter, strStartLine, strEndLine, bReverseArrays, pnlistInputs, pstrlistInputs, pnlistOutputs, pstrlistOutputs, nExtract, bExtractRandom, dStopError, nStopEpoch, nLayer1, nLayer2, nLayer3, nLayer4, nNumOfLayers, nActivationType, dAdjustRange, bShowEpochs, bShowEpochsSince, bShowLearningError, bShowTestingError, strApplyDataFile, nApplySkipBefore, nApplySkipAfter, strApplyStartLine, strApplyEndLine, bApplyReverseArrays, plistApplyInputs, pstrlistApplyInputs, plistApplyOutputs, pstrlistOutputs, strOutputDataFile, nOutputSkipBefore, nOutputSkipAfter, strOutputStartLine, strOutputEndLine, bOutputReverseArrays, plistOutputInputs, pstrlistOutputInputs, plistOutputOutputs, pstrlistOutputOutputs); Save NN, associated with the handle (hNn) to the file (strFileName). This function creates the file, that is fully compatible with Cortex UI. If you only plan to use the resulting NN from scripting language (no UI dialogs), use SAVE_NN instead. CLOSE_NNCLOSE_NN(hNN) Close the previously opened NN. APPLY_NNAPPLY_NN(hNnHandle, nNumOfRecords, dExtendRange, nNumOfInputArrays, arrInput_1, arrLags_1, ..., nNumOfOutputArrays, arrOutput_1, ...); Applies (see NN theory) the NN. The following sequence of actions is performed: For the list of inputs and list of lag numbers (5, 6...) generate the lags, together with the input data, it will be fed to the network, pattern by pattern. Normalize the data WITHIN THE RANGE of first nNumOfRecords records. The network was trained on this range, so whatever data we send to it, it should be normalized to the same range. For example, we have learning data: 1, 2, 3. We normalize the data to the range 0 - 1, by dividing by 2 (3 - 1). Now, if we have the testing data, 3.25, we will still divide it by 2. The range can be changed, by providing the dExtendRange coefficient, if we expect new data to be outside the range. Generally, whatever parameters we used when teaching the NN, should be passed here. Each lags array corresponds to an input array. See sample_nn_01.tsc, sample_nn_02_tsc, sample_nn_03.tsc for a code, that works with Neural Networks. Parameters: hNnHandle - handle of a previously opened NN. nNumOfRecords - number of records in learning set. Used to normalize the data. Usually, whatever number was used during teaching of a network, should be passed here. dExtendRange - If test data are outside the range of the learning data, we can use this scaling coefficient. Usually, whatever number was used during teaching of a network, should be passed here. nNumOfInputArrays - number of inputs. arrInput_1, arrLags_1, ... - Pairs of the input array and array of lags to be applied to it. nNumOfOutputArrays - number of outputs arrOutput_1, ... - output arrays TEST_NNdError = TEST_NN(hNnHandle, nNumOfRecords, dExtendRange, nNumOfInputArrays, arrInput_1, arrLag_1, ..., nNumOfOutputArrays, arrOutput_1, ..., ); Tests the NN using provided data, returns the testing error. dError calculated using testing data only (start at nNumOfRecords). For example, we have an array of stock data, 10000 records long. The learning was performed using 8000 records as a learning set, and 2000 records as a testing set. In order to estimate how good the resulting NN is, we need to test it using the same 2000 records. We can do it, by providing original arrays (10000 records) and specifying nNumOfRecords equal 8000. Parameters: hNnHandle - handle of a previously opened NN. nNumOfRecords - number of records in learning set. Used to normalize the data. Usually, whatever number was used during teaching of a network, should be passed here. dExtendRange - If test data are outside the range of the learning data, we can use this scaling coefficient. Usually, whatever number was used during teaching of a network, should be passed here. nNumOfInputArrays - number of inputs. arrInput_1, arrLags_1, ... - Pairs of the input array and array of lags to be applied to it. nNumOfOutputArrays - number of outputs arrOutput_1, ... - output arrays PATTERN_NNPATTERN_NN(hNnHandle, arrPattern, dExtendRange); Run the network against a single pattern. Note that arrPattern contains both inputs (first) and outputs (last), the NN will take inputs and fill the outputs. For example, if we have a stock price predicting network (1 output), that expects 10 inputs, we need to fill arrPattern[0] through arrPattern[9] with inputs. After we call PATTERN_NN, the arrPattern[10] will contain the output of the NN. OPEN_NN_FILEOPEN_NN_FILE(strNnFileName, bIsPathRelative, bStartLearning, bResumeScript, bReset); Brings up a modal dialog, containing the NN parameters. The first parameter is a path to the NN file, the second specifies, if the path is relative (to the location of the Cortex executable), or absolute. If the bStartLearning parameter equals 0, the NN is waiting for the user input (for example, the user can press the "Run" button), if it is 1, the learning begins automatically. The bResumeScript parameter (0 or 1) specifies, if the dialog should be closed automatically and script execution to continue. For example, you may set the "min. testing error" to some value, and when it is reached, the dialog will close. The bReset parameter specifies, if the NN should be reset to the untrained state before the learning begins. CREATE_LAG_FILECREATE_LAG_FILE(srcFileName, bIsPathRelative, dstFileName, bIsPathRelative, nSkipBefore, nSkipAfter, strStartLine, strEndLine, strSeparator, bReverseArrays, arrInputColumns, arrInputColumnNames, arrLags, nNumOfInputColumns); Creates lag (.lgg) file for a network to use. Parameters: srcFileName - name of the source file, for example, file containing stock quotes bIsPathRelative - is it a full path or if it is relative to the location of the program's executable. dstFileName - lag file to be created bIsPathRelative - is it a full path or if it is relative to the location of the program's executable. nSkipBefore - number of lines to skip before the start line. nSkipAfter - number of lines to skip after the start line. strStartLine - the line in the source file, after which meaningfull data begin. strEndLine - the line, at which data loading should stop. strSeparator - list of characters, used to separate data, for example, ",;" bReverseArrays - we need newest data LAST. If the source file contains newest data FIRST, we need to reverse arrays, after we have loaded them. arrInputColumns - array, containing numbers of input columns arrInputColumnNames - array, containing names of input columns, these names will be displayed in the corresponting list box of the dialog. arrLags - array, containing lags. nNumOfInputColumns - number of input columns. CREATE_NNCREATE_NN(strNnFileName, bIsPathRelative, strInputFile, bIsPathRelative, nSkipBefore, nSkipAfter, strStartLine, strEndLine, bReverseArrays, arrInputColumns, arrInputColumnNames, arrOutputColumns, arrOutputColumnNames, nExtractRecords, dStopError, nStopEpoch, nNeuronsLayer1, nNeuronsLayer2, nNeuronsLayer3, nNeuronsLayer4, nLayers, nActivation, nAdjustRange, arrOutTabInputColumns, arrOutTabInputColumnNames, arrOutTabOutputColumns, arrOutTabOutputColumnNames); Creates a new NN on disk, parameters are the same as in the NN dialog tabs. Parameters: strNnFileName - name of the network file bIsPathRelative - is this path absolute, or relative to the location of the program's executable. strInputFile - input (lag) file with data bIsPathRelative - is this path absolute, or relative to the location of the program's executable. nSkipBefore - number of lines to skip before the start pattern. nSkipAfter - number of lines to skip after the start pattern. strStartLine - start pattern, meaningfull data begin after this line. Empty string ("") if not used. strEndLine - the line, at which the data loading should stop. bReverseArrays - should data arrays be reversed. Make sure this parameter is correct. For example, if we have already reversed arrays during the call to CREATE_LAG_FILE, we don't want to reverse them again. arrInputColumns - numbers of input columns arrInputColumnNames - names of input columns arrOutputColumns - number of output columns arrOutputColumnNames - names of output columns nExtractRecords - record extraction method, see Cortex tutorial for details. dStopError - error at which to stop learning. 0 if not used. nStopEpoch - epoch number to stop calculations. 0 if not used. nNeuronsLayer1 - number of neurons in layer 1 nNeuronsLayer2 - number of neurons in layer 2 nNeuronsLayer3 - number of neurons in layer 3 nNeuronsLayer4 - number of neurons in layer 4 nLayers - number of layers nActivation - type of the activation function (0, 1... corresponds to selection in combo box). nAdjustRange - scaling coefficient arrOutTabInputColumns - numbers of input columns for "Output" tab of the dialog. arrOutTabInputColumnNames - names of input columns for "Output" tab. arrOutTabOutputColumns - numbers of output columns for "Output" tab of the dialog. arrOutTabOutputColumnNames - names of output columns for "Output" tab. GET_NN_WEIGHTSarray arrWeights = GET_NN_WEIGHTS(hNn, nLayer); Returns an array, containing weights for all neurons of a given layer. Let's say, we are retrieving weights for the 1st layer, and there are 5 neurons in the previous, 0th layer. Then array elements 0 - 4 will contain weights for the 1st neuron, and so on. GET_NN_DESCRIPTIONarray arrDescription = GET_NN_DESCRIPTION(hNn); Returns an array, containing description of a network. Array elements:
MUTATION_NNhNnCopy = SCRIPT_MUTATION_NN (nNn, nCopyWeights, dRange, bDeterministic); nCopyWeights = 0 - exact copy, 1 - uniformly distributed, 2 - Gauss distributed dRange - range weights are distributed in, centered at weight value of source NN bDeterministic. Used only with nCOpyWeights not equal zero. If 0, we vary weights randomly. If 1, ve vary OUTPUTS randomly, which, in some situations (of genetic learning) can speed up the learning signifficantly. Shortly, if 1, we get a random DIRECTION we want the output to change, and then vary inputs on a neuron in the same direction. Creates a copy of the NN, whose handle is passed as a first parameter. Weights of a resulting NN are distributed around the corresponding weight of a source NN, in the given range. Uniform and Gaussian distributions are supported. SELF ORGANIZING MAPSCREATE_SOMCREATE_SOM("..\Cortex\data\test.kh", bIsPathRelative, nNumOfInputs, nIterations, dimX, DimY, nRedrawEvery); Parameters 1 and 2 are path to a SOM to create (existing file will be
replaced without a warning) and type of a path - absolute (0) or
relative to Cortex's Bin folder.
OPEN_SOM_DLGbOkCancel = OPEN_SOM_DLG("..\Cortex\data\jaco.kh", bIsPathRelative, "..\Cortex\data\jaco.txt", bIsPathRelative, strStartLine, nSkipBefore, strEndLine, arrColNumbers, bStartLearning); Brings up SOM training dialog. Parameters 1 and 2 are path to a SOM description file and type of a path - absolute (0) or
relative to Cortex's Bin folder.
OPEN_SOMhSom = OPEN_SOM("..\Cortex\data\jaco.kh", bIsPathRelative); Open SOM and return its handle. Parameters 1 and 2 are path to a SOM description file and type of a path - absolute (0) or relative to Cortex's Bin folder. CLOSE_SOMCLOSE_SOM(hSom); Closes SOM when it is no longer needed. PATTERN_SOMarrResult = PATTERN_SOM(hNnHandle, arrPattern); Takes SOM handle and an array of data, one element per expected input. returns an array with the following elements: number of a winner neuron, red, green, blue colors, X and Y coordinates of a winner neuron in a SOM's grid. Note, that input is expected to be in 0 - 1 range. GET_SOM_WEIGHTSarray arrWeights = GET_SOM_WEIGHTS(hNn); Returns an array of weights for the SOM:
This function can be used to export SOM information, for example, in order to recreate the trained SOM using some other programming language. GET_SOM_COLORS// array arrColors = GET_SOM_COLORS(hSom); Returns an array of m_dWin values that can be used to calculate BLUE colors for the SOM, one color per neuron. The way we handle colors is explained in GET_SOM_INFO// array arrResult = GET_SOM_INFO(hSom); Returns an array with SOM information.
GET_SOM_WINNERSGET_SOM_WINNERS(hSom, strDataPath, bIsPathRelative, strStartLine, nSkipBefore, strEndLine, arrColNumbers, nStep); Loads the data from file same way TABLE_LOADER does, except column numbers to load are provided as an array. If you look at the C++ code sample in APPLY_SOM section, you will see pNode->m_dWin and pNode->m_dMaxWin, first value is for the current neuron, the second is the maximum value for all neurons. These values are calculated during the SOM training, so technically, you do not have to call GET_SOM_WINNERS. However, if you run an already trained network against set of patterns, you will get different values, so it is better to do it this way. If you run SOM against ALL patterns you have (37,000 patterns in FOREX history file, for example), it will take very long time. Instead, you can specify a step (nStep variable), for example, if nStep equals 100, we will only have 370 patterns, and result still will be reliable. APPLY_SOMarrResult = APPLY_SOM(strSomFileName, bIsPathRelative, strDataFileName, bIsDataPathRelative, strStartLine, nSkipBefore, strEndLine, arrColNumbers); Processes multiple input patterns. Takes input from the data file, loading it the same way TBLE_LOADER does. Returns an array of colors, 3 colors (red, green, blue) per each pattern and its position in a grid. The following C++ code is used to calculate the color (though you do not need to know it in order to use it): void CortexSlang::GetSomColor(int& red, int& green, int& blue, CNode* pNode) { red = (int)((double)pNode->m_nCol / pNode->m_nCellsX * 128); green = (int)((double)pNode->m_nRow / pNode->m_nCellsY * 128); blue = (int)(255.0 * pNode->m_dWin / pNode->m_dMaxWin); } Here, the red and green colors are related to neuron's coordinates, and blue color is based on the strength of its signal. Note: the arrColors is 3 times the size of the data array, per each pattern, we receive 3 numbers: r, g, b. TradingTRADE_INITTRADE_INIT("arrOpen, arrHigh, arrLow, arrClose, &dAdviceMax, &dAdviceMin, arrNnAdvice, arrNnBuyStopLoss, arrNnBuyTakeProfit, arrNnSellStopLoss, arrNnSellTakeProfit, arrNnLotSizes, dSpread, dMinStop, dMaxStop, dLeverade, &arrBalance, &arrBalanceBuy, &arrBalanceSell, &dSuccessRatio, &dBuyToSellRatio, &nWinTrades, &nLooseTrades &nCurrentTradeType, &dMaxDrawDown, &nNumberOfTrades, &nNumberOfTradesBuy, &nNumberOfTradesSell, &dStopLoss, &dTakeProfit"); Initialization for the later calls of TRADE and TRADE_CURRENT functions. The function takes a string with names of parameters to be passed to TRADE and TRADE_CURRENT and to be returned from them. If a parameter is to be modified by the function, it is prefixed (in this description only) with an & character. For example, after we call TRADE(), it fills an array called arrBalance with values. Therefore, this variable is prefixed with &. On the other hand, arrOpen is only used to pass values to the function, but it will not be modified by it.
Note, that all variables must be created before passing their names to the function. Parameters: arrOpen, arrHigh, arrLow, arrClose: price of a security (like EURUSD) we trade &dAdviceMax, &dAdviceMin: max. and min. values of the signal, produced by NN (or of some other signal - whatever we feed to the TRADE function). It is sometimes convenient to know this range, so we return it. arrNnAdvice, arrNnBuyStopLoss, arrNnBuyTakeProfit,
arrNnSellStopLoss, arrNnSellTakeProfit,
arrNnLotSizes: arrays (one value for each bar) with
trading signal, stop loss value, and so on. The TRADE function will
use them to make trade decisions and to calculate profits.
Second, here is the way we handle stop loss and take profit
values.
Take profit: Unlike stop loss, take profit range is not
necessarily used. Therefore, we need to use it, if the signal is small,
and if the signal is large, it will not be used, because it is never
reached. To do it, we use
dSpread, dMinStop, dMaxStop, dLeverade: common parameters used to calculate profit. &arrBalance, &arrBalanceBuy, &arrBalanceSell: arrays, containing profit values, one per bar. &dSuccessRatio, &dBuyToSellRatio, &nWinTrades, &nLooseTrades: see code sample. These are values containing some statistics about trades we made. &nCurrentTradeType: BUY = -2, CLOSE_SELL = -1, CLOSE_BUY = 1, SELL = 2 &dMaxDrawDown, &nNumberOfTrades, &nNumberOfTradesBuy, &nNumberOfTradesSell: additional statistics &dStopLoss, &dTakeProfit: values returned by TRADE_CURRENT, containing information about parameters of a current (this bar) trade. For example, this is how we call this function:
... // arrays are initialized and filled with data first array arrDate = CREATE_ARRAY(0); array arrTime = CREATE_ARRAY(0); array arrOpen = CREATE_ARRAY(0); array arrHigh = CREATE_ARRAY(0); array arrLow = CREATE_ARRAY(0); array arrClose = CREATE_ARRAY(0); TABLE_LOADER(strDataFileName, bIsPathRelative, 0, "", 0, "", 0, arrDate, 1, arrTime, 2, arrOpen, 3, arrHigh, 4, arrLow, 5, arrClose); // Variables to be returned are created first double dSuccessRatio; double dBuySellRatio; double dMaxDrawDown; // Some values must be initialized, use this // sample as a guide double dMinStop = 0.0030; // 30 points double dMaxStop = 0.0250; // 250 points double nNumberOfTradesBuy = 0; double nNumberOfTradesSell = 0; double nNumberOfTrades = 0; double nCurrentTradeType; // Arrays to keep NN output // filled (in this example) by ApplyNN, used in Test array arrNnAdvice = CREATE_ARRAY(0); array arrNnBuyStopLoss = CREATE_ARRAY(0); array arrNnBuyTakeProfit = CREATE_ARRAY(0); array arrNnSellStopLoss = CREATE_ARRAY(0); array arrNnSellTakeProfit = CREATE_ARRAY(0); array arrBalance = CREATE_ARRAY(0); array arrBalanceBuy = CREATE_ARRAY(0); array arrBalanceSell = CREATE_ARRAY(0); double nWinTrades = 0; double nLooseTrades = 0; double dSpread = 0.0005; double dAdviceMax; double dAdviceMin; array arrNnLotSizes = CREATE_ARRAY(0); double dStopLoss; double dTakeProfit; TRADE_INIT("arrOpen, arrHigh, arrLow, arrClose, dAdviceMax, dAdviceMin, arrNnAdvice, arrNnBuyStopLoss, arrNnBuyTakeProfit, arrNnSellStopLoss, arrNnSellTakeProfit, arrNnLotSizes, dSpread, dMinStop, dMaxStop, arrBalance, arrBalanceBuy, arrBalanceSell, dSuccessRatio, dBuySellRatio, nWinTrades, nLooseTrades nCurrentTradeType, dMaxDrawDown, nNumberOfTrades, nNumberOfTradesBuy, nNumberOfTradesSell, dStopLoss, dTakeProfit"); TRADE(nFirstRecordNum, nLastRecordNum, nProcessTrades <1 - buy, 2 - sell, 3 - both>); nFirstRecordNum - first bar
Return value (returned by changing the value of a corresponding
variable, passed to TRADE_INIT): CLOSE_BUY = 1, BUY = 2,
CLOSE_SELL = 4, SELL = 8
Few words about the reasons we use this function. In the code sample you can find a similar functionality, implemented as SLANG code. However, using TRADE() function instead of coding it in SLANG is much faster, you can double speed of your script this way. The reason we moved initialization to TRADE_INIT is simple: we only call it once, outside any cycles, and therefore, we improve speed, by not passing all these parameters over and over again. nTradeType = TRADE_CURRENT(nRecordNum); Returns BUY = -2, CLOSE_SELL = -1, CLOSE_BUY = 1, SELL = 2. These are values for current bar ONLY. Say, 10 bars ago, BUY position opened. Then the return value was -2 10 bars ago, but now (10 bars after the position was opened) it is 0. Cortex can call script one time after another, by timer. Select Timer from the main menu, set timer interval and specify a script file to run. Script file, instead of "main" function, should contain two functios: "init" and "timer"" void init() { double nTimerCounter = 1; PRINT("%s\r\n", "Initializing"); } void timer() { PRINT("%.0f\r\n", nTimerCounter); nTimerCounter = nTimerCounter + 1; } init() is only called once, when the timer starts for the first time. Timer is called every time (including the first time, it is called after init()). #plugin This is a preprocessor directive, that allows you to load your own (or third party) functions from DLLs. The detailed description on how to create Cortex plugins: plugins tutorial The source code for a sample plugin: \CortexPro\Plugins\Sample The use (see CortexPro\data\samples\script\sample_plugin.tsc)
#plugin "sample.dll" Here, sample.dll is a third party plugin. The path to plugins is relative to the Bin directory. To get fully enabled version of the Cortex Built-in Scripting engine, you need to register.
Free Stock trading Course The course consists of five E.mails and covers all essentials of Technical Analysis approach to Stock Trading. Compare to $$$ that you will have to pay elsewhere. All you need to do is to enter your name (nickname will do) and E.mail address in the form below. |
|
Please, provide us with some feedback!
It is a matter of life and death for us, but will only take 20 seconds for you. No personal info collected. Proceed... |
||
NLP, Hypnosis, Power, Manipulation | Tai Chi, Chi Gun |
Neural Networks
Stock and FOREX trading: full cycle, steps-by-step. |
Habits Management | Karate tutorial |
|
|
Back Pain Relief System | Calendar Creator |
Building a small profitable site | Joints Gymnastics | Another Flow Charts Designer |
Profitable web site in 9 days |
|
Flow charts for Presentations and Web |
|
Shareware Directory |
|
Touch Typing: how fast can you learn it? | Web programming : Perl, XML | Stock and FOREX Trading |
Neural Networks
data mining
machine learning
neural networks extrapolation
neural networks stock prediction
neural networks download
free neural networks software
neural networks introduction
tutorial on neural networks
neural networks book
neural network course
neural network free software
invest network neural
stock market neural network
neural network tool box
neural network financial
algorithm backpropagation
application data mining
neural network artificial intelligence
stock neural network
stock market neural network
invest network neural
neural network financial
algorithm backpropagation
neural network artificial intelligence
|