├── Django_tutorial ├── a.py └── tutorial │ ├── catalog │ ├── __init__.py │ ├── migrations │ │ ├── __init__.py │ │ └── 0001_initial.py │ ├── tests.py │ ├── apps.py │ ├── management │ │ └── commands │ │ │ ├── delete_all.py │ │ │ └── populate.py │ ├── templates │ │ ├── catalog │ │ │ ├── actor_detail.html │ │ │ ├── actor_list.html │ │ │ ├── film_list.html │ │ │ └── film_detail.html │ │ └── index.html │ ├── admin.py │ ├── urls.py │ ├── views.py │ └── models.py │ ├── tutorial │ ├── __init__.py │ ├── asgi.py │ ├── wsgi.py │ └── urls.py │ ├── authentication │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── admin.py │ ├── tests.py │ ├── apps.py │ ├── templates │ │ ├── registration │ │ │ ├── logged_out.html │ │ │ ├── password_reset_email.html │ │ │ ├── password_reset_complete.html │ │ │ ├── password_reset_done.html │ │ │ ├── signup.html │ │ │ ├── password_reset_form.html │ │ │ ├── login.html │ │ │ └── password_reset_confirm.html │ │ ├── signup.html │ │ └── base.html │ ├── urls.py │ ├── forms.py │ └── views.py │ ├── db.sqlite3 │ └── manage.py ├── NodeJS └── Notes-app │ ├── .gitignore │ ├── db │ └── data.json │ ├── package.json │ ├── helpers │ ├── file.js │ └── inquirer.js │ └── app.js ├── tutoriales ├── Python │ ├── mongodb │ │ ├── commands_windows │ │ ├── commands_ubuntu │ │ └── db.py │ ├── Files │ │ ├── nuevo_archivo │ │ └── files.py │ ├── faker │ │ ├── commands │ │ └── test.py │ ├── comprehension.py │ ├── sockets │ │ ├── sockets.py │ │ └── server_socket.py │ ├── signals │ │ └── handler.py │ ├── SKLearn - RN │ │ └── neuralNetwork.py │ ├── sems │ │ └── sems.py │ ├── zip_enum.py │ ├── sort.py │ └── sems_exercise │ │ └── sem.py ├── Trading │ ├── commands │ └── .ipynb_checkpoints │ │ ├── MACD-checkpoint.ipynb │ │ └── trading_data_pandas-checkpoint.ipynb ├── Django │ └── tutorial │ │ ├── catalog │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── __init__.py │ │ │ ├── 0004_author_slug.py │ │ │ ├── 0003_book_author.py │ │ │ ├── 0002_auto_20211224_0822.py │ │ │ └── 0001_initial.py │ │ ├── tests.py │ │ ├── templates │ │ │ ├── catalog │ │ │ │ ├── author_detail.html │ │ │ │ ├── author_list.html │ │ │ │ ├── book_detail.html │ │ │ │ └── book_list.html │ │ │ ├── index.html │ │ │ └── base.html │ │ ├── apps.py │ │ ├── admin.py │ │ ├── urls.py │ │ ├── views.py │ │ ├── management │ │ │ └── commands │ │ │ │ └── populate.py │ │ └── models.py │ │ ├── tutorial │ │ ├── __init__.py │ │ ├── asgi.py │ │ ├── wsgi.py │ │ └── urls.py │ │ ├── .vscode │ │ └── settings.json │ │ ├── db.sqlite3 │ │ └── manage.py ├── Pandas │ ├── commands │ └── pandas_example.py ├── Flask │ ├── flask_tutorial_1 │ │ ├── commands │ │ ├── templates │ │ │ └── index.html │ │ └── tutorial1.py │ ├── flask_tutorial_2 │ │ ├── templates │ │ │ ├── page_3.html │ │ │ ├── page_2.html │ │ │ └── index.html │ │ └── tutorial2.py │ ├── flask_tutorial_3 │ │ ├── templates │ │ │ ├── page_2.html │ │ │ ├── index.html │ │ │ └── page_3.html │ │ └── tutorial3.py │ ├── flask_tutorial_4 │ │ ├── templates │ │ │ ├── page_2.html │ │ │ ├── page_3.html │ │ │ └── index.html │ │ └── tutorial4.py │ ├── flask_tutorial_5 │ │ ├── templates │ │ │ ├── page_2.html │ │ │ ├── page_3.html │ │ │ ├── product.html │ │ │ └── index.html │ │ └── tutorial5.py │ ├── flask_tutorial_6 │ │ ├── templates │ │ │ ├── page_2.html │ │ │ ├── base.html │ │ │ ├── page_3.html │ │ │ ├── product.html │ │ │ └── index.html │ │ └── tutorial6.py │ └── flask_tutorial_7 │ │ ├── templates │ │ ├── page_2.html │ │ ├── base.html │ │ ├── page_3.html │ │ ├── product.html │ │ └── index.html │ │ └── tutorial7.py ├── TikToks_Shorts │ └── lista.py ├── C │ ├── Signals │ │ ├── tutorial_1 │ │ │ ├── commands │ │ │ └── infinite.c │ │ ├── .vscode │ │ │ └── settings.json │ │ ├── tutorial_2 │ │ │ ├── infinite.c │ │ │ └── kill_process.c │ │ └── tutorial_3 │ │ │ └── handler.c │ ├── Binary tree │ │ ├── node.h │ │ ├── tree.h │ │ ├── main.c │ │ ├── tree.c │ │ └── node.c │ ├── Queue │ │ ├── makefile │ │ ├── queue.h │ │ ├── .vscode │ │ │ └── c_cpp_properties.json │ │ ├── main.c │ │ └── queue.c │ ├── Stack │ │ ├── makefile │ │ ├── stack.h │ │ ├── main.c │ │ └── stack.c │ ├── Files │ │ ├── write_file.c │ │ └── read_file.c │ ├── a.c │ ├── Linked list │ │ ├── linked_list.h │ │ └── test.c │ ├── Mask │ │ └── mask.c │ ├── Shared memory │ │ ├── .vscode │ │ │ └── c_cpp_properties.json │ │ └── shared_mem.c │ ├── mensajes │ │ ├── receptor.c │ │ └── sender.c │ ├── sockets │ │ ├── client.c │ │ └── server.c │ ├── Semaphores │ │ ├── named.c │ │ └── unnamed.c │ └── sems_exercise │ │ └── sem.c ├── Java │ ├── interfaces │ │ ├── IAuto.java │ │ ├── ICar.java │ │ ├── Test.java │ │ └── Car.java │ ├── tutorial │ │ ├── Book.class │ │ ├── test.class │ │ ├── test.java │ │ └── Book.java │ ├── inheritance │ │ ├── Car.class │ │ ├── SUV.class │ │ ├── Test.class │ │ ├── Hypercar.class │ │ ├── Test.java │ │ ├── Car.java │ │ ├── SUV.java │ │ ├── Hypercar.java │ │ └── .vscode │ │ │ └── launch.json │ ├── collections │ │ ├── Hash_table.class │ │ ├── List_test.class │ │ ├── List_test.java │ │ └── Hash_table.java │ └── generic │ │ └── generic_class.java └── .vscode │ └── settings.json ├── .gitignore ├── .vscode └── settings.json ├── mql5 ├── .vscode │ └── settings.json ├── profitable │ └── MACD_RSI_STOCH │ │ ├── MACD_RSI_STOCH_V1 │ │ ├── ReportTester-54232522.png │ │ ├── ReportTester-54232522.html │ │ ├── ReportTester-54232522-hst.png │ │ ├── ReportTester-54232522-mfemae.png │ │ └── ReportTester-54232522-holding.png │ │ ├── MACD_RSI_STOCH_V2 │ │ ├── ReportTester-54232522.png │ │ ├── ReportTester-54232522.html │ │ ├── ReportTester-54232522-hst.png │ │ ├── ReportTester-54232522-mfemae.png │ │ └── ReportTester-54232522-holding.png │ │ ├── MACD_RSI_STOCH_V3 │ │ ├── ReportTester-54232522.png │ │ ├── ReportTester-54232522.html │ │ ├── ReportTester-54232522-hst.png │ │ ├── ReportTester-54232522-mfemae.png │ │ └── ReportTester-54232522-holding.png │ │ ├── MACD_RSI_STOCH_V4 │ │ ├── ReportTester-54232522.png │ │ ├── ReportTester-54232522.html │ │ ├── ReportTester-54232522-hst.png │ │ ├── ReportTester-54232522-mfemae.png │ │ └── ReportTester-54232522-holding.png │ │ ├── MACD_RSI_STOCH_V5 │ │ ├── ReportTester-54232522.png │ │ ├── ReportTester-54232522.html │ │ ├── ReportTester-54232522-hst.png │ │ ├── ReportTester-54232522-mfemae.png │ │ └── ReportTester-54232522-holding.png │ │ └── MACD_RSI_STOCH_V2_LOT_1 │ │ ├── ReportTester-54232522.html │ │ ├── ReportTester-54232522.png │ │ ├── ReportTester-54232522-hst.png │ │ ├── ReportTester-54232522-holding.png │ │ └── ReportTester-54232522-mfemae.png ├── block_account.mq5 ├── lot_size.mq5 ├── ClosePartial.mq5 ├── input_parameters.mq5 ├── ADX.mq5 ├── news.mq5 ├── index_bot.mq5 ├── index_crash.mq5 ├── index_boom.mq5 ├── line.mq5 ├── rsi.mq5 ├── martingala.mq5 ├── high_lows.mq5 ├── sound.mq5 ├── MAs.mq5 ├── trailing_stops_several_positions.mq5 ├── CloseOnCross.mq5 ├── VolatilityIndexBot.mq5 ├── MACD.mq5 ├── volatility_index.mq5 ├── maxperdida-ganancia.mq5 ├── MACD_lotaje_dinamico.mq5 ├── resistances.mq5 ├── time_bot.mq5 └── break_even.mq5 ├── MQL5_PYTHON ├── INDEX_BOT │ ├── .vscode │ │ └── settings.json │ ├── main.py │ ├── CANDLE.py │ ├── index_client.mq5 │ ├── bot.py │ ├── test_order.py │ └── orders.py ├── MACD_BOT │ ├── main.py │ ├── steps │ ├── MACD.py │ ├── macd_client.mq5 │ ├── bot.py │ └── test_order.py ├── RSI_BOT │ ├── main.py │ ├── RSI.py │ ├── RSI_client.mq5 │ ├── bot.py │ ├── test_order.py │ └── orders.py ├── server.py ├── client.mq5 ├── client_closes.mq5 └── MACD_client.mq5 ├── ta ├── RSI │ └── BOT │ │ ├── main.py │ │ ├── test_order.py │ │ ├── .vscode │ │ └── launch.json │ │ ├── RSI.py │ │ └── orders.py └── .vscode │ └── launch.json ├── Binance └── binance_ticks.py ├── server.py ├── Python trading bot ├── src │ ├── main.py │ └── RSI.py └── backtesting │ ├── parsing_script.py │ ├── backtesting_script.py │ └── csv_log_parser.py └── README.md /Django_tutorial/a.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /NodeJS/Notes-app/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ -------------------------------------------------------------------------------- /tutoriales/Python/mongodb/commands_windows: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tutoriales/Trading/commands: -------------------------------------------------------------------------------- 1 | pip install ta -------------------------------------------------------------------------------- /Django_tutorial/tutorial/catalog/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Django_tutorial/tutorial/tutorial/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/catalog/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/tutorial/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tutoriales/Pandas/commands: -------------------------------------------------------------------------------- 1 | pip install pandas -------------------------------------------------------------------------------- /Django_tutorial/tutorial/authentication/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /NodeJS/Notes-app/db/data.json: -------------------------------------------------------------------------------- 1 | {"Hola":"L","A":"C"} -------------------------------------------------------------------------------- /tutoriales/Python/Files/nuevo_archivo: -------------------------------------------------------------------------------- 1 | Hola caracola -------------------------------------------------------------------------------- /tutoriales/Python/faker/commands: -------------------------------------------------------------------------------- 1 | pip install Faker -------------------------------------------------------------------------------- /Django_tutorial/tutorial/catalog/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/catalog/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Django_tutorial/tutorial/authentication/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_1/commands: -------------------------------------------------------------------------------- 1 | pip install flask -------------------------------------------------------------------------------- /tutoriales/TikToks_Shorts/lista.py: -------------------------------------------------------------------------------- 1 | print([i for i in range(10)]) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.txt 2 | *.csv 3 | *.log 4 | src/*txt 5 | __pycache__/ 6 | src/__pycache__/ -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "*.mq5": "cpp" 4 | } 5 | } -------------------------------------------------------------------------------- /tutoriales/C/Signals/tutorial_1/commands: -------------------------------------------------------------------------------- 1 | man kill 2 | man 2 kill 3 | man signal 4 | 5 | kill -l -------------------------------------------------------------------------------- /tutoriales/Java/interfaces/IAuto.java: -------------------------------------------------------------------------------- 1 | public interface IAuto { 2 | public void accelerate(); 3 | } -------------------------------------------------------------------------------- /mql5/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "*.mq5": "cpp" 4 | } 5 | } -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.formatting.provider": "autopep8" 3 | } -------------------------------------------------------------------------------- /Django_tutorial/tutorial/catalog/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /Django_tutorial/tutorial/authentication/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/catalog/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /tutoriales/Python/Files/files.py: -------------------------------------------------------------------------------- 1 | with open("ejemplo.txt", "r") as f: 2 | for line in f: 3 | print(line) -------------------------------------------------------------------------------- /Django_tutorial/tutorial/authentication/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /Django_tutorial/tutorial/authentication/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /MQL5_PYTHON/INDEX_BOT/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "*.mq5": "cpp" 4 | } 5 | } -------------------------------------------------------------------------------- /tutoriales/C/Signals/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "signal.h": "c" 4 | } 5 | } -------------------------------------------------------------------------------- /Django_tutorial/tutorial/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/Django_tutorial/tutorial/db.sqlite3 -------------------------------------------------------------------------------- /tutoriales/Java/tutorial/Book.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/tutoriales/Java/tutorial/Book.class -------------------------------------------------------------------------------- /tutoriales/Java/tutorial/test.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/tutoriales/Java/tutorial/test.class -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/tutoriales/Django/tutorial/db.sqlite3 -------------------------------------------------------------------------------- /tutoriales/Java/inheritance/Car.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/tutoriales/Java/inheritance/Car.class -------------------------------------------------------------------------------- /tutoriales/Java/inheritance/SUV.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/tutoriales/Java/inheritance/SUV.class -------------------------------------------------------------------------------- /tutoriales/Java/inheritance/Test.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/tutoriales/Java/inheritance/Test.class -------------------------------------------------------------------------------- /tutoriales/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "stdio.h": "c", 4 | "string.h": "c" 5 | } 6 | } -------------------------------------------------------------------------------- /tutoriales/Java/collections/Hash_table.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/tutoriales/Java/collections/Hash_table.class -------------------------------------------------------------------------------- /tutoriales/Java/collections/List_test.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/tutoriales/Java/collections/List_test.class -------------------------------------------------------------------------------- /tutoriales/Java/inheritance/Hypercar.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/tutoriales/Java/inheritance/Hypercar.class -------------------------------------------------------------------------------- /tutoriales/Python/comprehension.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | l = [{ i:["aaa" for _ in range(2)] for i in range(2) } for _ in range(10)] 4 | 5 | print(l) -------------------------------------------------------------------------------- /tutoriales/Trading/.ipynb_checkpoints/MACD-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 5 6 | } 7 | -------------------------------------------------------------------------------- /tutoriales/C/Binary tree/node.h: -------------------------------------------------------------------------------- 1 | typedef struct _node Node; 2 | 3 | Node *node_init(int data); 4 | void node_destroy(Node *n); 5 | void node_add(Node *n, int data); -------------------------------------------------------------------------------- /tutoriales/C/Queue/makefile: -------------------------------------------------------------------------------- 1 | all: clean compile execute 2 | 3 | clean: 4 | rm -f exe 5 | 6 | compile: 7 | gcc -o exe *.c 8 | 9 | execute: 10 | ./exe -------------------------------------------------------------------------------- /tutoriales/C/Stack/makefile: -------------------------------------------------------------------------------- 1 | all: clean compile execute 2 | 3 | clean: 4 | rm -f exe 5 | 6 | compile: 7 | gcc -o exe *.c 8 | 9 | execute: 10 | ./exe -------------------------------------------------------------------------------- /tutoriales/C/Signals/tutorial_1/infinite.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void main() { 5 | while(1) printf("%d Infinite LOOP\n", getpid()); 6 | } -------------------------------------------------------------------------------- /tutoriales/C/Signals/tutorial_2/infinite.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void main() { 5 | while(1) printf("%d Infinite LOOP\n", getpid()); 6 | } -------------------------------------------------------------------------------- /tutoriales/Trading/.ipynb_checkpoints/trading_data_pandas-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 5 6 | } 7 | -------------------------------------------------------------------------------- /tutoriales/Java/interfaces/ICar.java: -------------------------------------------------------------------------------- 1 | public interface ICar { 2 | // NO ATTRIBUTES 3 | 4 | // ONLY METHODS (behaviour) 5 | public void move(); 6 | public void turnOff(); 7 | } -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/catalog/templates/catalog/author_detail.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Author: {{ author.name }}

5 | {% endblock %} -------------------------------------------------------------------------------- /tutoriales/C/Binary tree/tree.h: -------------------------------------------------------------------------------- 1 | #include "node.h" 2 | 3 | typedef struct _tree Tree; 4 | 5 | Tree *tree_init(); 6 | void tree_destroy(Tree *t); 7 | void tree_add_node(Tree *t, int node_data); -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V1/ReportTester-54232522.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V1/ReportTester-54232522.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2/ReportTester-54232522.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2/ReportTester-54232522.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V3/ReportTester-54232522.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V3/ReportTester-54232522.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V4/ReportTester-54232522.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V4/ReportTester-54232522.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V5/ReportTester-54232522.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V5/ReportTester-54232522.png -------------------------------------------------------------------------------- /MQL5_PYTHON/MACD_BOT/main.py: -------------------------------------------------------------------------------- 1 | from bot import Bot 2 | import MetaTrader5 as mt5 3 | 4 | 5 | mt5.initialize() 6 | 7 | macd_bot = Bot(0.01, 60, "BTCEUR") 8 | 9 | macd_bot.start() 10 | macd_bot.wait() -------------------------------------------------------------------------------- /MQL5_PYTHON/RSI_BOT/main.py: -------------------------------------------------------------------------------- 1 | from bot import Bot 2 | import MetaTrader5 as mt5 3 | 4 | 5 | mt5.initialize() 6 | 7 | macd_bot = Bot(0.01, 60, "BTCEUR") 8 | 9 | macd_bot.start() 10 | macd_bot.wait() -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V1/ReportTester-54232522.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V1/ReportTester-54232522.html -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2/ReportTester-54232522.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2/ReportTester-54232522.html -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V3/ReportTester-54232522.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V3/ReportTester-54232522.html -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V4/ReportTester-54232522.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V4/ReportTester-54232522.html -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V5/ReportTester-54232522.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V5/ReportTester-54232522.html -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_1/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

6 | Hello! Ahoj! ¡Hola! 7 |

8 | 9 | -------------------------------------------------------------------------------- /Django_tutorial/tutorial/catalog/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class CatalogConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'catalog' 7 | -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V1/ReportTester-54232522-hst.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V1/ReportTester-54232522-hst.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2/ReportTester-54232522-hst.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2/ReportTester-54232522-hst.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V3/ReportTester-54232522-hst.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V3/ReportTester-54232522-hst.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V4/ReportTester-54232522-hst.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V4/ReportTester-54232522-hst.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V5/ReportTester-54232522-hst.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V5/ReportTester-54232522-hst.png -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/catalog/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class CatalogConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'catalog' 7 | -------------------------------------------------------------------------------- /MQL5_PYTHON/INDEX_BOT/main.py: -------------------------------------------------------------------------------- 1 | from bot import Bot 2 | import MetaTrader5 as mt5 3 | 4 | # 5 | mt5.initialize() 6 | 7 | macd_bot = Bot(0.1, 60, "Boom 300 Index") 8 | 9 | macd_bot.start() 10 | macd_bot.wait() -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V1/ReportTester-54232522-mfemae.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V1/ReportTester-54232522-mfemae.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2/ReportTester-54232522-mfemae.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2/ReportTester-54232522-mfemae.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2_LOT_1/ReportTester-54232522.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2_LOT_1/ReportTester-54232522.html -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2_LOT_1/ReportTester-54232522.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2_LOT_1/ReportTester-54232522.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V3/ReportTester-54232522-mfemae.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V3/ReportTester-54232522-mfemae.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V4/ReportTester-54232522-mfemae.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V4/ReportTester-54232522-mfemae.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V5/ReportTester-54232522-mfemae.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V5/ReportTester-54232522-mfemae.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V1/ReportTester-54232522-holding.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V1/ReportTester-54232522-holding.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2/ReportTester-54232522-holding.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2/ReportTester-54232522-holding.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2_LOT_1/ReportTester-54232522-hst.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2_LOT_1/ReportTester-54232522-hst.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V3/ReportTester-54232522-holding.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V3/ReportTester-54232522-holding.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V4/ReportTester-54232522-holding.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V4/ReportTester-54232522-holding.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V5/ReportTester-54232522-holding.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V5/ReportTester-54232522-holding.png -------------------------------------------------------------------------------- /Django_tutorial/tutorial/authentication/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class AuthenticationConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'authentication' 7 | -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2_LOT_1/ReportTester-54232522-holding.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2_LOT_1/ReportTester-54232522-holding.png -------------------------------------------------------------------------------- /mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2_LOT_1/ReportTester-54232522-mfemae.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kecoma1/Trading_BOT/HEAD/mql5/profitable/MACD_RSI_STOCH/MACD_RSI_STOCH_V2_LOT_1/ReportTester-54232522-mfemae.png -------------------------------------------------------------------------------- /tutoriales/Java/interfaces/Test.java: -------------------------------------------------------------------------------- 1 | public class Test { 2 | public static void main(String args[]) { 3 | Car c = new Car(); 4 | c.accelerate(); 5 | c.move(); 6 | c.turnOff(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Django_tutorial/tutorial/authentication/templates/registration/logged_out.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Logged out!

5 | Click here to login again. 6 | {% endblock %} -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_2/templates/page_3.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

6 | This is the page 3!
The post was correctly done :-) 7 |

8 | 9 | -------------------------------------------------------------------------------- /Django_tutorial/tutorial/authentication/templates/registration/password_reset_email.html: -------------------------------------------------------------------------------- 1 | Someone asked for password reset for email {{ email }}. Follow the link below: 2 | {{ protocol}}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} -------------------------------------------------------------------------------- /Django_tutorial/tutorial/authentication/templates/registration/password_reset_complete.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

The password has been changed!

5 |

log in again?

6 | {% endblock %} -------------------------------------------------------------------------------- /tutoriales/C/Stack/stack.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct _stack Stack; 5 | 6 | Stack *stack_ini(); 7 | void push(Stack *s, int value); 8 | int pop(Stack *s); 9 | void stack_destroy(Stack *s); 10 | void stack_print(Stack *s); 11 | -------------------------------------------------------------------------------- /tutoriales/C/Queue/queue.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | typedef struct _queue Queue; 6 | 7 | 8 | Queue *queue_ini(); 9 | void push(Queue *q, int value); 10 | int pop(Queue *q); 11 | void queue_destroy(Queue *q); 12 | void queue_print(Queue *q); -------------------------------------------------------------------------------- /Django_tutorial/tutorial/authentication/templates/signup.html: -------------------------------------------------------------------------------- 1 | {% extends 'base.html' %} 2 | 3 | {% block content %} 4 |

Sign Up

5 |
6 | {% csrf_token %} 7 | {{ form.as_p }} 8 | 9 |
10 | {% endblock %} -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_1/tutorial1.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask import render_template 3 | 4 | app = Flask(__name__) 5 | 6 | @app.route("/") 7 | def home(): 8 | return render_template("index.html") 9 | 10 | if __name__ == "__main__": 11 | app.run() -------------------------------------------------------------------------------- /Django_tutorial/tutorial/authentication/templates/registration/password_reset_done.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

We've emailed you instructions for setting your password. If they haven't arrived in a few minutes, check your spam folder.

5 | {% endblock %} -------------------------------------------------------------------------------- /tutoriales/C/Files/write_file.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | 6 | FILE *fp = NULL; 7 | fp = fopen("nuevo_archivo.txt", "w"); 8 | 9 | fprintf(fp, "Hola este es un test %d\n", 3); 10 | 11 | fclose(fp); 12 | 13 | return 0; 14 | } -------------------------------------------------------------------------------- /tutoriales/Java/interfaces/Car.java: -------------------------------------------------------------------------------- 1 | public class Car implements ICar, IAuto { 2 | public void move() { System.out.println("I'm moving"); } 3 | public void turnOff() { System.out.println("I'm turning my self off"); } 4 | public void accelerate() { System.out.println("I'm accelerating"); } 5 | } -------------------------------------------------------------------------------- /Django_tutorial/tutorial/authentication/templates/registration/signup.html: -------------------------------------------------------------------------------- 1 | {% extends 'base.html' %} 2 | 3 | {% block content %} 4 |

Sign up

5 |
6 | {% csrf_token %} 7 | {{ form.as_p }} 8 | 9 |
10 | {% endblock %} -------------------------------------------------------------------------------- /tutoriales/C/Signals/tutorial_2/kill_process.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | #include 6 | 7 | void main() { 8 | int pid = 0; 9 | 10 | printf("Introduce the PID: "); 11 | scanf("%d", &pid); 12 | 13 | kill(pid, SIGTERM); 14 | } -------------------------------------------------------------------------------- /MQL5_PYTHON/MACD_BOT/steps: -------------------------------------------------------------------------------- 1 | 1. Install Metatrader 5 2 | 2. Allow algorithmic trading 3 | 2.1. Go to "Tools" 4 | 2.2. Click on "Allow algorithmic trading" 5 | 3. Install metatrader 5 python - pip install MetaTrader5 6 | 4. Install python extension in VSCode 7 | 5. Add url in MT5 "localhost" 8 | 5. Code and test! -------------------------------------------------------------------------------- /Django_tutorial/tutorial/authentication/urls.py: -------------------------------------------------------------------------------- 1 | 2 | from django.contrib import admin 3 | from django.urls import path, include 4 | from .views import SignUpView 5 | 6 | urlpatterns = [ 7 | path('signup/', SignUpView.as_view(), name='signup'), 8 | path('', include('django.contrib.auth.urls')), 9 | ] 10 | -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/catalog/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Number of books: {{ num_books }}

5 |

Number of authors: {{ num_authors }}

6 | {% endblock %} -------------------------------------------------------------------------------- /tutoriales/Python/sockets/sockets.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | # Cretating a TCP socket 4 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 5 | 6 | # Connecting to the server 7 | s.connect(("localhost", 8456)) 8 | 9 | # Message to send 10 | msg = input("Message to send: ") 11 | 12 | s.sendall(msg.encode()) -------------------------------------------------------------------------------- /mql5/block_account.mq5: -------------------------------------------------------------------------------- 1 | 2 | int OnInit() { 3 | long account_id = AccountInfoInteger(ACCOUNT_LOGIN); 4 | 5 | Print("Account ID: ", account_id); 6 | 7 | if (account_id != 5012711372) { 8 | Print("Cuenta inválida"); 9 | return INIT_FAILED; 10 | } 11 | 12 | return INIT_SUCCEEDED; 13 | } -------------------------------------------------------------------------------- /ta/RSI/BOT/main.py: -------------------------------------------------------------------------------- 1 | import bot 2 | import MetaTrader5 as mt5 3 | 4 | # Creating a bot 5 | b = bot.Bot(0.01, 60*15, "EURUSD") 6 | 7 | # Login into mt5 8 | mt5.initialize(login=50708418, server='ICMarketsEU-Demo',password='Yyaexkks') 9 | 10 | b.thread_candle() 11 | b.thread_RSI() 12 | b.thread_orders() 13 | b.wait() -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_2/templates/page_2.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

6 | This is the page 2!
7 | 8 | Click here to go back to the main page 9 | 10 |

11 | 12 | -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_3/templates/page_2.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

6 | This is the page 2!
7 | 8 | Click here to go back to the main page 9 | 10 |

11 | 12 | -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_4/templates/page_2.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

6 | This is the page 2!
7 | 8 | Click here to go back to the main page 9 | 10 |

11 | 12 | -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_5/templates/page_2.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

6 | This is the page 2!
7 | 8 | Click here to go back to the main page 9 | 10 |

11 | 12 | -------------------------------------------------------------------------------- /tutoriales/Python/mongodb/commands_ubuntu: -------------------------------------------------------------------------------- 1 | sudo apt update 2 | 3 | sudo apt install python # Installs python 4 | sudo apt install python-pip # Installs pip 5 | 6 | # Installing mongodb 7 | pip install pymongo 8 | sudo apt install mongodb 9 | 10 | # Checking everything works fine 11 | sudo systemctl status mongodb -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/catalog/templates/catalog/author_list.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Authors

5 |
    6 | {% for author in author_list %} 7 |
  • 8 | Name: {{ author }} 9 |
  • 10 | {% endfor %} 11 |
12 | {% endblock %} -------------------------------------------------------------------------------- /Django_tutorial/tutorial/authentication/forms.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth import forms 2 | from django.contrib.auth.forms import UserCreationForm 3 | from django.contrib.auth.models import User 4 | 5 | class UserCreationFormModified(UserCreationForm): 6 | class Meta: 7 | model = User 8 | fields = ('username', 'email', 'first_name', 'last_name') 9 | -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/catalog/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import Author, Book 3 | 4 | @admin.register(Author) 5 | class AuthorAdmin(admin.ModelAdmin): 6 | list_display = ('id', 'name') 7 | 8 | @admin.register(Book) 9 | class BookAdmin(admin.ModelAdmin): 10 | list_display = ('id', 'title', 'price', 'slug') -------------------------------------------------------------------------------- /Binance/binance_ticks.py: -------------------------------------------------------------------------------- 1 | from websocket import WebSocketApp 2 | import json 3 | 4 | def on_message(ws, msg): 5 | tick = json.loads(msg) 6 | if tick['k']['x']: 7 | print("NUEVA VEL") 8 | print(tick['k']['c']) 9 | 10 | 11 | ws = WebSocketApp("wss://stream.binance.com:9443/ws/btcusdt@kline_1m", on_message=on_message) 12 | ws.run_forever() -------------------------------------------------------------------------------- /ta/RSI/BOT/test_order.py: -------------------------------------------------------------------------------- 1 | import orders 2 | import time 3 | import MetaTrader5 as mt5 4 | 5 | mt5.initialize(login=50708418, server='ICMarketsEU-Demo',password='Yyaexkks') 6 | 7 | orders.STOPLOSS = 100 8 | orders.TAKEPROFIT = 500 9 | orders.open_position("EURUSD", 0.01, "buy") 10 | time.sleep(5) 11 | 12 | orders.open_position("EURGBP", 0.01, "sell") 13 | -------------------------------------------------------------------------------- /Django_tutorial/tutorial/catalog/management/commands/delete_all.py: -------------------------------------------------------------------------------- 1 | from django.core.management.base import BaseCommand 2 | from catalog.models import Actor, Film, Comment 3 | 4 | 5 | class Command(BaseCommand): 6 | 7 | def handle(self, *args, **kwargs): 8 | Actor.objects.all().delete() 9 | Film.objects.all().delete() 10 | Comment.objects.all().delete() -------------------------------------------------------------------------------- /Django_tutorial/tutorial/catalog/templates/catalog/actor_detail.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Actor: {{actor.name}}

5 |

Age: {{actor.age}}

6 | 7 |
    8 | {% for film in actor.get_films %} 9 |
  • {{film.title}}
  • 10 | {% endfor %} 11 |
12 | {% endblock %} -------------------------------------------------------------------------------- /tutoriales/C/a.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() { 7 | if (fork() == 0) { // Child's execution 8 | printf("I'm the child\n"); 9 | } else { // Father's execution 10 | printf("I'm the father\n"); 11 | wait(NULL); 12 | } 13 | return 0; 14 | } -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_6/templates/page_2.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block titlecontnet %} 4 | PAGE 2 5 | {% endblock %} 6 | 7 | {% block bodycontent %} 8 |

9 | This is the page 2!
10 | 11 | Click here to go back to the main page 12 | 13 |

14 | {% endblock %} -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_7/templates/page_2.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block titlecontnet %} 4 | PAGE 2 5 | {% endblock %} 6 | 7 | {% block bodycontent %} 8 |

9 | This is the page 2!
10 | 11 | Click here to go back to the main page 12 | 13 |

14 | {% endblock %} -------------------------------------------------------------------------------- /Django_tutorial/tutorial/authentication/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from django.views import generic 3 | from django.urls import reverse_lazy 4 | from .forms import UserCreationFormModified 5 | 6 | class SignUpView(generic.CreateView): 7 | form_class = UserCreationFormModified 8 | success_url = reverse_lazy('home') 9 | template_name = 'signup.html' -------------------------------------------------------------------------------- /NodeJS/Notes-app/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "todo-app", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "inquirer": "^8.2.0" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /tutoriales/C/Files/read_file.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | 6 | FILE *fp = NULL; 7 | fp = fopen("ejemplo.txt", "r"); 8 | 9 | for (int i = 0; i < 4; i++) { 10 | char str[10]; 11 | fscanf(fp, "%s\n", str); 12 | printf("%s\n", str); 13 | } 14 | 15 | fclose(fp); 16 | 17 | return 0; 18 | } -------------------------------------------------------------------------------- /tutoriales/Java/inheritance/Test.java: -------------------------------------------------------------------------------- 1 | public class Test { 2 | public static void main(String args[]) { 3 | SUV b = new SUV(250, 5, "Lexus", 500.2); 4 | Hypercar c = new Hypercar(1000, 2, "Lamborghini", 375.78); 5 | Car d = new SUV(1, 1, "d", 1.2); 6 | 7 | System.out.println(b.show()); 8 | System.out.println(c.show()); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/catalog/templates/catalog/book_detail.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Book: {{ book.title }}

5 |

Price: {{ book.price }}

6 |

Authors: 7 | {% for author in book.author.all %} 8 | {{ author }} 9 | {% endfor %} 10 |

11 | {% endblock %} -------------------------------------------------------------------------------- /tutoriales/Python/signals/handler.py: -------------------------------------------------------------------------------- 1 | import signal 2 | 3 | # DOCUMENTATION! 4 | # https://docs.python.org/3/library/signal.html 5 | 6 | 7 | def signal_handler(signum, frame): 8 | """Handler""" 9 | print("En vez de cerrarme voy a printear esto.") 10 | 11 | 12 | # Setting the handler 13 | signal.signal(signal.SIGINT, signal_handler) 14 | 15 | # Infinite loop 16 | while True: 17 | pass 18 | -------------------------------------------------------------------------------- /server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | ADDR = "localhost" 4 | PORT = 8081 5 | 6 | server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 7 | 8 | server_socket.bind((ADDR, PORT)) 9 | server_socket.listen(10) 10 | 11 | connection, addr = server_socket.accept() 12 | print("[INFO]\t", addr, "connected") 13 | 14 | msg = connection.recv(1024).decode() 15 | print(msg) 16 | connection.send("Hello".encode()) -------------------------------------------------------------------------------- /mql5/lot_size.mq5: -------------------------------------------------------------------------------- 1 | double getLotage(double percentage, long lot_size = 100000) { 2 | double balance = AccountInfoDouble(ACCOUNT_BALANCE); 3 | 4 | double to_use = percentage * balance; 5 | 6 | double lotes = to_use / lot_size; 7 | 8 | return NormalizeDouble(lotes, 2); 9 | } 10 | 11 | 12 | void OnInit() { 13 | double lotage = getLotage(0.10); 14 | 15 | Print("Lotaje: ", lotage); 16 | } -------------------------------------------------------------------------------- /tutoriales/Python/SKLearn - RN/neuralNetwork.py: -------------------------------------------------------------------------------- 1 | from sklearn.neural_network import MLPClassifier 2 | import numpy as np 3 | 4 | data = np.genfromtxt('xor.csv', delimiter=',') 5 | X = data[:, [0, 1]] 6 | y = data[:, -1] 7 | 8 | rn = MLPClassifier(hidden_layer_sizes=(2,), activation='logistic', max_iter=1000, alpha=0.001) 9 | 10 | rn.fit(X, y) 11 | 12 | for i in range(4): 13 | print(X[i], '->', rn.predict([X[i]])) -------------------------------------------------------------------------------- /tutoriales/C/Binary tree/main.c: -------------------------------------------------------------------------------- 1 | #include "tree.h" 2 | 3 | int main() { 4 | Tree *t = tree_init(); 5 | 6 | tree_add_node(t, 1); 7 | tree_add_node(t, 2); 8 | tree_add_node(t, 3); 9 | tree_add_node(t, 4); 10 | tree_add_node(t, 5); 11 | tree_add_node(t, 6); 12 | tree_add_node(t, 7); 13 | tree_add_node(t, 8); 14 | tree_add_node(t, 9); 15 | tree_add_node(t, 10); 16 | 17 | tree_destroy(t); 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /tutoriales/C/Linked list/linked_list.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef struct Node Node; 6 | typedef struct Linked_list Linked_list; 7 | 8 | 9 | 10 | Linked_list *linked_list_init(); 11 | Node *linked_list_last(Linked_list *l); 12 | int linked_list_add_node(Linked_list *l, int data); 13 | void linked_list_destroy(Linked_list *l); 14 | void linked_list_print(Linked_list *l); -------------------------------------------------------------------------------- /tutoriales/Java/tutorial/test.java: -------------------------------------------------------------------------------- 1 | package tutorial; 2 | import tutorial.Book; 3 | 4 | public class test { 5 | public static void main(String args[]) { 6 | Book b = new Book("The rational male", "Rollo tomassi", 300); 7 | Book c = new Book("The unplugged alpha", "Richard Cooper", 200); 8 | 9 | System.out.println(c.showBook()); 10 | System.out.println(c.createDesc()); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_2/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

6 | Hello! Ahoj! ¡Hola!
7 | 8 | CLICK 9 | 10 | 11 |
12 | 13 |
14 |

15 | 16 | -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_3/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

6 | Hello! Ahoj! ¡Hola!
7 | 8 | CLICK 9 | 10 | 11 |
12 | 13 |
14 |

15 | 16 | -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_3/templates/page_3.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

6 | This is the page 3!
The post was correctly done :-)
7 |
8 | 9 | 10 |
11 |

12 | 13 | -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_4/templates/page_3.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

6 | This is the page 3!
The post was correctly done :-)
7 |
8 | 9 | 10 |
11 |

12 | 13 | -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_5/templates/page_3.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

6 | This is the page 3!
The post was correctly done :-)
7 |
8 | 9 | 10 |
11 |

12 | 13 | -------------------------------------------------------------------------------- /Django_tutorial/tutorial/catalog/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block title %} 4 | Kevin Films 5 | {% endblock %} 6 | 7 | {% block content %} 8 |

Kevin Films

9 | 13 | {% endblock %} 14 | -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_6/templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {% block headcontent %}{% endblock %} 6 | {% block titlecontnet %}{% endblock %} 7 | 8 | 9 | {% block bodycontent %}{% endblock %} 10 | 11 | -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_7/templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {% block headcontent %}{% endblock %} 6 | {% block titlecontnet %}{% endblock %} 7 | 8 | 9 | {% block bodycontent %}{% endblock %} 10 | 11 | -------------------------------------------------------------------------------- /tutoriales/Python/sems/sems.py: -------------------------------------------------------------------------------- 1 | import threading 2 | 3 | sem1 = threading.Semaphore(0) 4 | sem2 = threading.Semaphore(0) 5 | 6 | def fun_1(): 7 | print(1) 8 | sem1.release() 9 | sem2.acquire() 10 | sem1.release() 11 | print(3) 12 | 13 | def fun_2(): 14 | print(2) 15 | sem1.acquire() 16 | sem2.release() 17 | sem1.acquire() 18 | print(4) 19 | 20 | threading.Thread(target=fun_1).start() 21 | threading.Thread(target=fun_2).start() -------------------------------------------------------------------------------- /Django_tutorial/tutorial/catalog/templates/catalog/actor_list.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Actor List

5 |
    6 | {% for actor in actor_list %} 7 |
  • Name: {{actor.name}}, Age: {{actor.age}}, Films: 8 | {% for film in actor.get_films %} 9 | {{film}} - 10 | {% endfor %} 11 |
  • 12 | {% endfor %} 13 |
14 | {% endblock %} -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_6/templates/page_3.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block titlecontnet %} 4 | PAGE 3 5 | {% endblock %} 6 | 7 | {% block bodycontent %} 8 |

9 | This is the page 3!
The post was correctly done :-)
10 |
11 | 12 | 13 |
14 |

15 | {% endblock %} -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_7/templates/page_3.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block titlecontnet %} 4 | PAGE 3 5 | {% endblock %} 6 | 7 | {% block bodycontent %} 8 |

9 | This is the page 3!
The post was correctly done :-)
10 |
11 | 12 | 13 |
14 |

15 | {% endblock %} -------------------------------------------------------------------------------- /NodeJS/Notes-app/helpers/file.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | 3 | const filepath = './db/data.json'; 4 | 5 | 6 | const write = (data) => fs.writeFileSync(filepath, JSON.stringify(data)); 7 | 8 | const read = () => { 9 | if (!fs.existsSync(filepath)) 10 | return null; 11 | 12 | const info = fs.readFileSync(filepath, {encoding: 'utf-8'}); 13 | 14 | if (info) return JSON.parse(info); 15 | else return {} 16 | } 17 | 18 | module.exports = { write, read } -------------------------------------------------------------------------------- /Django_tutorial/tutorial/authentication/templates/registration/password_reset_form.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Reset your password

5 |
6 | {% csrf_token %} 7 | 8 | {% if form.email.errors %} 9 | {{ form.email.errors }} 10 | {% endif %} 11 |

{{ form.email }}

12 | 13 |
14 | {% endblock %} -------------------------------------------------------------------------------- /Django_tutorial/tutorial/catalog/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import Actor, Film, Comment 3 | 4 | 5 | @admin.register(Actor) 6 | class ActorAdmin(admin.ModelAdmin): 7 | list_display = ('id', 'name', 'display_films') 8 | 9 | @admin.register(Film) 10 | class FilmAdmin(admin.ModelAdmin): 11 | list_display = ('id', 'title', 'score', 'price', 'display_actors') 12 | 13 | @admin.register(Comment) 14 | class CommentAdmin(admin.ModelAdmin): 15 | list_display = ('id',) -------------------------------------------------------------------------------- /Django_tutorial/tutorial/catalog/templates/catalog/film_list.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Film List

5 |
    6 | {% for film in film_list %} 7 |
  • Title: {{film.title}}, Price: {{film.price}}, Score: {{film.score}}, Actors: 8 | {% for actor in film.actor.all %} 9 | {{actor}} - 10 | {% endfor %} 11 |
  • 12 | {% endfor %} 13 |
14 | {% endblock %} -------------------------------------------------------------------------------- /tutoriales/Java/inheritance/Car.java: -------------------------------------------------------------------------------- 1 | public abstract class Car { 2 | private int hp; 3 | public int seats; 4 | public String name; 5 | 6 | public Car(int hp, int seats, String name) { 7 | this.hp = hp; 8 | this.seats = seats; 9 | this.name = name; 10 | } 11 | 12 | public int getSeats() { return this.seats; } 13 | public String show() { return this.name+"\n"+this.hp+"\n"+this.seats+"\n"; } 14 | public abstract void move(); 15 | } 16 | -------------------------------------------------------------------------------- /MQL5_PYTHON/server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 4 | 5 | serversocket.bind(("localhost", 8888)) 6 | serversocket.listen(10) 7 | 8 | connection, addr = serversocket.accept() 9 | print("[INFO]\tConexión establecida con:", addr) 10 | 11 | msg = "\0" 12 | while not "END CONNECTION\0" in msg and msg != "": 13 | msg = connection.recv(1024).decode() 14 | print("[INFO]\tMensaje:", msg) 15 | connection.close() 16 | serversocket.close() -------------------------------------------------------------------------------- /mql5/ClosePartial.mq5: -------------------------------------------------------------------------------- 1 | #include 2 | CTrade trade; 3 | ulong trade_ticket = 0; 4 | 5 | void OnInit() { 6 | double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits); 7 | 8 | trade.Sell(1, _Symbol, Bid, Bid+100000*_Point, Bid-100000*_Point); 9 | trade_ticket = trade.ResultOrder(); 10 | } 11 | 12 | void OnTick() { 13 | if (trade_ticket != 0) { 14 | trade.PositionClosePartial(trade_ticket, 0.2); 15 | trade_ticket = 0; 16 | } 17 | } -------------------------------------------------------------------------------- /Django_tutorial/tutorial/tutorial/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for tutorial project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tutorial.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /Django_tutorial/tutorial/tutorial/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for tutorial project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tutorial.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/catalog/urls.py: -------------------------------------------------------------------------------- 1 | from django import views 2 | from django.contrib import admin 3 | from django.urls import path 4 | from . import views 5 | 6 | urlpatterns = [ 7 | path('books/', views.BookListView.as_view(), name='books'), 8 | path('authors/', views.AuthorListView.as_view(), name='authors'), 9 | path('book//', views.BookDetailView.as_view(), name='book'), 10 | path('author//', views.AuthorDetailView.as_view(), name='author') 11 | ] 12 | -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/tutorial/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for tutorial project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tutorial.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/tutorial/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for tutorial project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tutorial.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_2/tutorial2.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask import render_template 3 | 4 | app = Flask(__name__) 5 | 6 | @app.route("/") 7 | def home(): 8 | return render_template("index.html") 9 | 10 | @app.route("/page_2") 11 | def page_2(): 12 | return render_template("page_2.html") 13 | 14 | @app.route("/page_3", methods=["POST", "GET"]) # 15 | def page_3(): 16 | return render_template("page_3.html") 17 | 18 | if __name__ == "__main__": 19 | app.run() -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/catalog/templates/catalog/book_list.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Books

5 |
    6 | {% for book in book_list %} 7 |
  • 8 | Title: {{ book.title }} 9 | Price: {{ book.price }} 10 | Authors: 11 | {% for author in book.author.all %} 12 | {{ author }} 13 | {% endfor %} 14 |
  • 15 | {% endfor %} 16 |
17 | {% endblock %} -------------------------------------------------------------------------------- /mql5/input_parameters.mq5: -------------------------------------------------------------------------------- 1 | input int MA_Period=14; 2 | input int MA_Shift=0; 3 | input ENUM_MA_METHOD MA_Method=MODE_SMA; 4 | 5 | input int MA_Period2=14; // Period 6 | input int MA_Shift2=0; // Shift 7 | input ENUM_MA_METHOD MA_Method2=MODE_SMA; // Method 8 | 9 | enum customEnum { 10 | value1=0, // Red 11 | value2=1, // Green 12 | value3=2, // Blue 13 | }; 14 | 15 | input customEnum val=value1; // Color 16 | 17 | void OnInit() {} -------------------------------------------------------------------------------- /tutoriales/Java/inheritance/SUV.java: -------------------------------------------------------------------------------- 1 | public class SUV extends Car { 2 | private double volume; 3 | 4 | public SUV(int hp, int seats, String name, double volume) { 5 | super(hp, seats, name); 6 | this.volume = volume; 7 | } 8 | 9 | @Override 10 | public String show() { 11 | return super.show()+this.volume+"\n"; 12 | } 13 | 14 | @Override 15 | public void move() { 16 | System.out.println("I'm moving slow because I'm big."); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/catalog/migrations/0004_author_slug.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.6 on 2021-12-24 09:21 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ('catalog', '0003_book_author'), 10 | ] 11 | 12 | operations = [ 13 | migrations.AddField( 14 | model_name='author', 15 | name='slug', 16 | field=models.SlugField(blank=True, null=True), 17 | ), 18 | ] 19 | -------------------------------------------------------------------------------- /tutoriales/Java/inheritance/Hypercar.java: -------------------------------------------------------------------------------- 1 | public class Hypercar extends Car { 2 | 3 | private double topSpeed; 4 | 5 | public Hypercar(int hp, int seats, String name, double topSpeed) { 6 | super(hp, seats, name); 7 | this.topSpeed = topSpeed; 8 | } 9 | 10 | @Override 11 | public String show() { 12 | return super.show()+this.topSpeed+"\n"; 13 | } 14 | 15 | @Override 16 | public void move() { 17 | System.out.println("I'm moving fast"); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/catalog/migrations/0003_book_author.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.6 on 2021-12-24 08:36 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ('catalog', '0002_auto_20211224_0822'), 10 | ] 11 | 12 | operations = [ 13 | migrations.AddField( 14 | model_name='book', 15 | name='author', 16 | field=models.ManyToManyField(to='catalog.Author'), 17 | ), 18 | ] 19 | -------------------------------------------------------------------------------- /ta/RSI/BOT/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Python: Archivo actual", 9 | "type": "python", 10 | "request": "launch", 11 | "program": "main.py", 12 | "console": "integratedTerminal" 13 | } 14 | ] 15 | } -------------------------------------------------------------------------------- /tutoriales/C/Mask/mask.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* For masks */ 5 | #include 6 | 7 | /* For getpid */ 8 | #include 9 | #include 10 | 11 | 12 | void main () { 13 | sigset_t mask, suspendmask; 14 | 15 | sigfillset(&mask); 16 | sigdelset(&mask, SIGINT); 17 | 18 | sigfillset(&suspendmask); 19 | sigdelset(&suspendmask, SIGUSR1); 20 | 21 | sigprocmask(SIG_BLOCK, &mask, NULL); 22 | 23 | printf("PID: %d\n", getpid()); 24 | 25 | sigsuspend(&suspendmask); 26 | } -------------------------------------------------------------------------------- /Django_tutorial/tutorial/catalog/urls.py: -------------------------------------------------------------------------------- 1 | 2 | from django.urls import path, include 3 | from catalog.views import home_page 4 | from . import views 5 | 6 | urlpatterns = [ 7 | path('films/', views.FilmListView.as_view(), name='films'), 8 | path('actors/', views.ActorListView.as_view(), name='actors'), 9 | path('actor//', views.ActorDetailView.as_view(), name='actor'), 10 | path('film//', views.FilmDetailView.as_view(), name='film'), 11 | path('film//post_score/', views.post_score, name='post_score'), 12 | ] 13 | -------------------------------------------------------------------------------- /ta/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense para saber los atributos posibles. 3 | // Mantenga el puntero para ver las descripciones de los existentes atributos. 4 | // Para más información, visite: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Python: Archivo actual", 9 | "type": "python", 10 | "request": "launch", 11 | "program": "a.py", 12 | "console": "integratedTerminal" 13 | } 14 | ] 15 | } -------------------------------------------------------------------------------- /tutoriales/C/Queue/.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "Win32", 5 | "includePath": [ 6 | "${workspaceFolder}/**" 7 | ], 8 | "defines": [ 9 | "_DEBUG", 10 | "UNICODE", 11 | "_UNICODE" 12 | ], 13 | "compilerPath": "/usr/bin/gcc", 14 | "cStandard": "c17", 15 | "cppStandard": "c++17", 16 | "intelliSenseMode": "windows-gcc-x64" 17 | } 18 | ], 19 | "version": 4 20 | } -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/catalog/migrations/0002_auto_20211224_0822.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.6 on 2021-12-24 08:22 2 | 3 | from django.db import migrations 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ('catalog', '0001_initial'), 10 | ] 11 | 12 | operations = [ 13 | migrations.AlterModelOptions( 14 | name='book', 15 | options={'ordering': ['title', 'price']}, 16 | ), 17 | migrations.RemoveField( 18 | model_name='author', 19 | name='slug', 20 | ), 21 | ] 22 | -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/catalog/templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {% block title %}Tutorial Library{% endblock %} 6 | 7 | 8 | 10 | 11 | 12 | 13 |
{% block content %}{% endblock %}
14 | 15 | 16 | -------------------------------------------------------------------------------- /tutoriales/Java/tutorial/Book.java: -------------------------------------------------------------------------------- 1 | package tutorial; 2 | 3 | public class Book { 4 | private String title; 5 | private String author; 6 | private Integer pages; 7 | 8 | public Book(String title, String author, Integer pages) { 9 | this.title = title; 10 | this.author = author; 11 | this.pages = pages; 12 | } 13 | 14 | public String showBook() { 15 | return this.title+"\n"+this.author+"\n"+this.pages; 16 | } 17 | 18 | public String createDesc() { 19 | return "TITLE: "+this.title+"\nAUTHOR: "+this.author+"\nPAGES: "+this.pages; 20 | } 21 | } -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_6/templates/product.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block titlecontnet %} 4 | {{name}} 5 | {% endblock %} 6 | 7 | {% block bodycontent %} 8 |

9 | {{ name }} 10 |
11 | {% if "czech" in full_name %} 12 | Czech republic 13 | {% elif "esp" in full_name %} 14 | ESPAÑA, GRANDE Y LIBRE 15 | {% else %} 16 | English 17 | {% endif %} 18 |
19 |

20 | 21 | {% for i in range(5) %} 22 | {{ full_name }}
23 | {% endfor %} 24 | {% endblock %} -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_7/templates/product.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block titlecontnet %} 4 | {{name}} 5 | {% endblock %} 6 | 7 | {% block bodycontent %} 8 |

9 | {{ name }} 10 |
11 | {% if "czech" in full_name %} 12 | Czech republic 13 | {% elif "esp" in full_name %} 14 | ESPAÑA, GRANDE Y LIBRE 15 | {% else %} 16 | English 17 | {% endif %} 18 |
19 |

20 | 21 | {% for i in range(5) %} 22 | {{ full_name }}
23 | {% endfor %} 24 | {% endblock %} -------------------------------------------------------------------------------- /tutoriales/Python/sockets/server_socket.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | # Creating a TCP socket 4 | serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 5 | 6 | # Setting the ip and the port of the server 7 | serversocket.bind(("localhost", 8456)) 8 | 9 | # Max 5 connections in a queue 10 | serversocket.listen(5) 11 | 12 | # Accepting one connection 13 | connection, addr = serversocket.accept() 14 | print("Connection stablished with:", addr) 15 | 16 | print("Waiting for message") 17 | rec_msg = connection.recv(1024).decode() 18 | connection.close() 19 | print(addr, "sent you the message:", rec_msg) 20 | 21 | -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_5/templates/product.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

6 | {{ name }} 7 |
8 | {% if "czech" in full_name %} 9 | Czech republic 10 | {% elif "esp" in full_name %} 11 | ESPAÑA, GRANDE Y LIBRE 12 | {% else %} 13 | English 14 | {% endif %} 15 |
16 |

17 | 18 | {% for i in range(2) %} 19 | {{ full_name }}
20 | {% endfor %} 21 | 22 | 23 | -------------------------------------------------------------------------------- /tutoriales/Python/zip_enum.py: -------------------------------------------------------------------------------- 1 | from faker import Faker 2 | 3 | # Just for random strings 4 | fake = Faker() 5 | 6 | l1 = [i for i in range(10)] 7 | l2 = [fake.first_name() for _ in range(10)] 8 | 9 | l3 = [] 10 | d = {} 11 | 12 | for number, name in zip(l1, l2): 13 | l3.append((number, name)) 14 | d[name] = number 15 | 16 | print("New list:", l3) 17 | print("New dict:", d) 18 | 19 | # New names 20 | l2 = [fake.first_name() for _ in range(10)] 21 | enumerated = [] 22 | 23 | # Lets enumerate them 24 | for i, name in enumerate(l2): 25 | enumerated.append((i, name)) 26 | 27 | print("Enumerated names:", enumerated) 28 | -------------------------------------------------------------------------------- /Django_tutorial/tutorial/catalog/templates/catalog/film_detail.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Film: {{film.title}}

5 |

Price: {{film.price}}

6 |

Score: {{film.score}}

7 | 8 | {% if user.is_authenticated %} 9 |

Give it a score!

10 |
11 | {% csrf_token %} 12 | 13 | 14 |
15 | {% endif %} 16 |
    17 | {% for actor in film.actor.all %} 18 |
  • {{actor.name}}
  • 19 | {% endfor %} 20 |
21 | {% endblock %} -------------------------------------------------------------------------------- /tutoriales/Python/faker/test.py: -------------------------------------------------------------------------------- 1 | from faker import Faker 2 | 3 | 4 | # Incase you want to create the object with different languages 5 | languages = ['it_IT', 'en_US', 'ja_JP'] 6 | 7 | 8 | # Creating the fake object 9 | fake = Faker(languages) 10 | 11 | # Creating 10 names 12 | print("Names:") 13 | for _ in range(10): 14 | name = fake.name() 15 | print(name) 16 | 17 | 18 | # Use unique values 19 | print("\nUnique names:") 20 | names = [fake.unique.first_name() for _ in range(50)] 21 | print(names) 22 | 23 | # A lot of things can be generated 24 | # https://faker.readthedocs.io/en/master/providers.html 25 | for _ in range(5): 26 | print(fake.isbn13()) 27 | -------------------------------------------------------------------------------- /NodeJS/Notes-app/app.js: -------------------------------------------------------------------------------- 1 | const { read } = require("./helpers/file"); 2 | const { iMenu, addNote, delNote } = require("./helpers/inquirer"); 3 | 4 | 5 | const main = async() => { 6 | let cmd = ''; 7 | 8 | // Reading the previous notes 9 | const notes = read(); 10 | 11 | do { 12 | cmd = await iMenu(); 13 | 14 | switch (cmd) { 15 | case 1: 16 | await addNote(notes); 17 | break; 18 | 19 | case 2: 20 | await delNote(notes); 21 | break 22 | 23 | default: 24 | break; 25 | } 26 | 27 | } while (cmd !== 3); 28 | } 29 | 30 | main(); -------------------------------------------------------------------------------- /tutoriales/C/Signals/tutorial_3/handler.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | 6 | #include 7 | 8 | void handler(int sig) { 9 | printf("I'm in the handler!\n"); 10 | } 11 | 12 | int main(void) { 13 | struct sigaction act; 14 | 15 | /* Setting the handler */ 16 | act.sa_handler = handler; 17 | 18 | /* The mask of the handler is empty */ 19 | sigemptyset(&(act.sa_mask)); 20 | act.sa_flags = 0; 21 | 22 | /* Now the handler is linked to the process */ 23 | sigaction(SIGINT, &act, NULL); 24 | 25 | while(1) { 26 | printf("Waiting for SIGINT (PID = %d)\n", getpid()); 27 | sleep(1); 28 | } 29 | } -------------------------------------------------------------------------------- /Django_tutorial/tutorial/authentication/templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {% block title %}Tutorial Films{% endblock %} 6 | 7 | 8 | 10 | 11 | 12 | 13 | {% if user.is_authenticated %} 14 |

Hello {{user.username}}

15 | {% endif %} 16 |
{% block content %}{% endblock %}
17 | 18 | 19 | -------------------------------------------------------------------------------- /MQL5_PYTHON/client.mq5: -------------------------------------------------------------------------------- 1 | string address = "localhost"; 2 | int port = 8466; 3 | 4 | 5 | void OnInit() { 6 | // Initializing the socket 7 | int socket = SocketCreate(); 8 | if (socket == INVALID_HANDLE) Print("Error - 1: SocketCreate failure. ", GetLastError()); 9 | else { 10 | if (SocketConnect(socket, address, port, 10000)) { 11 | Print("[INFO]\tConnection stablished"); 12 | 13 | // Creating the message 14 | char req[]; 15 | int len = StringToCharArray("END CONNECTION\0", req)-1; 16 | 17 | SocketSend(socket, req, len); 18 | } else Print("Error - 2: SocketConnect failure. ", GetLastError()); 19 | SocketClose(socket); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /tutoriales/Java/collections/List_test.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class List_test { 4 | public static void main(String args[]) { 5 | List listA = new ArrayList(); 6 | List listB = new LinkedList(); 7 | Collection set = new TreeSet(); 8 | 9 | for (int i = 0; i < 10; i++) { 10 | listA.add(i+1); 11 | listB.add("n "+i); 12 | set.add("Hola"); 13 | } 14 | 15 | System.out.println(listA); 16 | System.out.println(listB); 17 | System.out.println(set); 18 | 19 | System.out.println("\n"); 20 | System.out.print("ListB: "); 21 | for (String s : listB) { 22 | System.out.print(s+ " - "); 23 | } 24 | System.out.println("\n"); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /tutoriales/C/Binary tree/tree.c: -------------------------------------------------------------------------------- 1 | #include "tree.h" 2 | #include 3 | #include 4 | 5 | struct _tree { 6 | Node *root; 7 | }; 8 | 9 | Tree *tree_init() { 10 | Tree *t = NULL; 11 | 12 | t = (Tree *)malloc(sizeof(Tree)); 13 | if (t == NULL) { 14 | fprintf(stderr, "Error en la función tree_init\n"); 15 | return NULL; 16 | } 17 | 18 | t->root = NULL; 19 | 20 | return t; 21 | } 22 | 23 | void tree_destroy(Tree *t) { 24 | if (t == NULL) return; 25 | 26 | node_destroy(t->root); 27 | free(t); 28 | } 29 | 30 | void tree_add_node(Tree *t, int node_data) { 31 | 32 | if (t == NULL) return; 33 | 34 | if (t->root == NULL) 35 | t->root = node_init(node_data); 36 | else 37 | node_add(t->root, node_data); 38 | } -------------------------------------------------------------------------------- /mql5/ADX.mq5: -------------------------------------------------------------------------------- 1 | 2 | 3 | int adx_h; 4 | double main[]; 5 | double plus[]; 6 | double minus[]; 7 | 8 | 9 | int OnInit() { 10 | adx_h = iADX(_Symbol, _Period, 15); 11 | 12 | if (adx_h == INVALID_HANDLE) { 13 | Print("Error loading the indicator"); 14 | return INIT_FAILED; 15 | } 16 | 17 | ArraySetAsSeries(main, true); 18 | ArraySetAsSeries(plus, true); 19 | ArraySetAsSeries(minus, true); 20 | 21 | return INIT_SUCCEEDED; 22 | } 23 | 24 | void OnDeinit(const int reason) { 25 | if (adx_h != INVALID_HANDLE) IndicatorRelease(adx_h); 26 | } 27 | 28 | void OnTick() { 29 | CopyBuffer(adx_h, MAIN_LINE, 1, 10, main); 30 | CopyBuffer(adx_h, PLUSDI_LINE, 1, 10, plus); 31 | CopyBuffer(adx_h, MINUSDI_LINE, 1, 10, minus); 32 | } -------------------------------------------------------------------------------- /tutoriales/C/Shared memory/.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "Win32", 5 | "includePath": [ 6 | "${workspaceFolder}/**" 7 | ], 8 | "defines": [ 9 | "_DEBUG", 10 | "UNICODE", 11 | "_UNICODE" 12 | ], 13 | "windowsSdkVersion": "10.0.17763.0", 14 | "compilerPath": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Tools\\MSVC\\14.16.27023\\bin\\Hostx64\\x64\\cl.exe", 15 | "cStandard": "c17", 16 | "cppStandard": "c++17", 17 | "intelliSenseMode": "windows-msvc-x64" 18 | } 19 | ], 20 | "version": 4 21 | } -------------------------------------------------------------------------------- /tutoriales/Java/inheritance/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense para saber los atributos posibles. 3 | // Mantenga el puntero para ver las descripciones de los existentes atributos. 4 | // Para más información, visite: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "java", 9 | "name": "Launch Current File", 10 | "request": "launch", 11 | "mainClass": "Test" 12 | }, 13 | { 14 | "type": "java", 15 | "name": "Launch Test", 16 | "request": "launch", 17 | "mainClass": "Test", 18 | "projectName": "inheritance_26d3450c" 19 | } 20 | ] 21 | } -------------------------------------------------------------------------------- /Django_tutorial/tutorial/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tutorial.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tutorial.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_6/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | 4 | 5 | {% block titlecontnet %} 6 | Index 7 | {% endblock %} 8 | 9 | {% block bodycontent %} 10 |

11 | Hello! Ahoj! ¡Hola!
12 | 13 | CLICK 14 | 15 |
16 | 17 | Español 18 | 19 |
20 | 21 | čeština 22 | 23 |
24 | 25 | English 26 | 27 |
28 |
29 | 30 |
31 |

32 | {% endblock %} 33 | -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/catalog/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from django.views import generic 3 | from .models import Author, Book 4 | 5 | class BookListView(generic.ListView): 6 | model = Book 7 | context_object_name = 'book_list' 8 | 9 | class AuthorListView(generic.ListView): 10 | model = Author 11 | context_object_name = 'author_list' 12 | 13 | class BookDetailView(generic.DetailView): 14 | model = Book 15 | 16 | class AuthorDetailView(generic.DetailView): 17 | model = Author 18 | 19 | def index(request): 20 | num_books = Book.objects.all().count() 21 | num_authors = Author.objects.all().count() 22 | 23 | context_ = { 24 | 'num_books': num_books, 25 | 'num_authors': num_authors, 26 | } 27 | 28 | return render(request, 'index.html', context=context_) 29 | -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_5/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

6 | Hello! Ahoj! ¡Hola!
7 | 8 | CLICK 9 | 10 |
11 | 12 | Español 13 | 14 |
15 | 16 | čeština 17 | 18 |
19 | 20 | English 21 | 22 |
23 |
24 | 25 |
26 |

27 | 28 | -------------------------------------------------------------------------------- /tutoriales/Java/collections/Hash_table.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Hash_table { 4 | public static void main(String args[]) { 5 | 6 | List list = new ArrayList(Arrays.asList("First", "Second", "Third", "Fourth", "Fifth")); 7 | 8 | HashMap dict1 = new HashMap(); 9 | Hashtable dict2 = new Hashtable(); 10 | 11 | int i = 1; 12 | for (String s: list) { 13 | dict1.put(s, i); 14 | dict2.put(i, s); 15 | i++; 16 | } 17 | 18 | System.out.println(dict1); 19 | System.out.println(dict2); 20 | 21 | // Updating a value 22 | dict1.put("Second", 3); 23 | System.out.println("\n"+dict1); 24 | 25 | // Getting a value 26 | System.out.println(dict1.get("Second")); 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Python trading bot/src/main.py: -------------------------------------------------------------------------------- 1 | import bot 2 | import matplotlib.pyplot as plt 3 | 4 | # Creating a bot 5 | b = bot.Bot(0.01, 15*60, "EURUSD") 6 | 7 | with open("login_data.txt", 'r') as f: 8 | lines = f.readlines() 9 | usr = int(lines[0]) 10 | password = lines[1] 11 | 12 | 13 | # Login into mt5 14 | if not b.mt5_login(usr, password): 15 | quit() 16 | b.thread_tick_reader() 17 | b.thread_slope_abs_rel() 18 | b.thread_MACD() 19 | b.thread_RSI() 20 | b.thread_orders() 21 | b.wait() 22 | 23 | # Haciendo una gráfica de los datos 24 | lista_segundos = b.get_ticks() 25 | xAxis = [] 26 | yAxis = [] 27 | i = 1 28 | if len(lista_segundos) < 10000: 29 | for element in b.get_ticks(): 30 | xAxis.append(i) 31 | yAxis.append(element) 32 | i += 1 33 | 34 | plt.plot(xAxis, yAxis) 35 | plt.show() 36 | -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_4/tutorial4.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask import render_template, request, redirect, url_for # Importing redirect and url_for! 3 | 4 | app = Flask(__name__) 5 | 6 | @app.route("/") 7 | def home(): 8 | return render_template("index.html") 9 | 10 | @app.route("/page_2") 11 | def page_2(): 12 | return render_template("page_2.html") 13 | 14 | @app.route("/page_3", methods=["POST"]) 15 | def page_3(): 16 | username = request.form.get("username") 17 | 18 | print("I received the name:", username) 19 | return render_template("page_3.html") 20 | 21 | @app.route("/EXAMPLE/") 22 | def example(arg): 23 | print("The extension in the url is:", arg) 24 | return redirect(url_for("home")) # Name of the function!! 25 | 26 | if __name__ == "__main__": 27 | app.run(debug=True) -------------------------------------------------------------------------------- /tutoriales/C/Queue/main.c: -------------------------------------------------------------------------------- 1 | #include "queue.h" 2 | 3 | int main() { 4 | 5 | Queue *q = queue_ini(); 6 | 7 | push(q, 1); 8 | queue_print(q); 9 | push(q, 2); 10 | queue_print(q); 11 | push(q, 3); 12 | queue_print(q); 13 | push(q, 4); 14 | queue_print(q); 15 | 16 | printf("\n"); 17 | 18 | printf("POP %d - ", pop(q)); 19 | queue_print(q); 20 | printf("POP %d - ", pop(q)); 21 | queue_print(q); 22 | printf("POP %d - ", pop(q)); 23 | queue_print(q); 24 | printf("POP %d - ", pop(q)); 25 | queue_print(q); 26 | 27 | printf("\n"); 28 | 29 | push(q, 112); 30 | queue_print(q); 31 | push(q, 22); 32 | queue_print(q); 33 | push(q, 345131); 34 | queue_print(q); 35 | push(q, 13141); 36 | queue_print(q); 37 | 38 | printf("\n"); 39 | 40 | printf("POP %d - ", pop(q)); 41 | queue_print(q); 42 | 43 | queue_destroy(q); 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_7/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | 4 | 5 | {% block titlecontnet %} 6 | Index 7 | {% endblock %} 8 | 9 | {% block bodycontent %} 10 |

Número de visitas en la página: {{visits}}

11 |

12 | Hello! Ahoj! ¡Hola!
13 | 14 | CLICK 15 | 16 |
17 | 18 | Español 19 | 20 |
21 | 22 | čeština 23 | 24 |
25 | 26 | English 27 | 28 |
29 |
30 | 31 |
32 |

33 | {% endblock %} 34 | -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_5/tutorial5.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask import render_template, request, redirect, url_for # Importing redirect and url_for! 3 | 4 | app = Flask(__name__) 5 | 6 | @app.route("/") 7 | def home(): 8 | return render_template("index.html") 9 | 10 | @app.route("/page_2") 11 | def page_2(): 12 | return render_template("page_2.html") 13 | 14 | @app.route("/page_3", methods=["POST"]) 15 | def page_3(): 16 | username = request.form.get("username") 17 | 18 | print("I received the name:", username) 19 | return render_template("page_3.html") 20 | 21 | @app.route("/EXAMPLE/") 22 | def example(arg): 23 | print("The extension in the url is:", arg) 24 | return render_template("product.html", name=arg.split("_")[1], full_name=arg) 25 | 26 | if __name__ == "__main__": 27 | app.run(debug=True) -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_6/tutorial6.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask import render_template, request, redirect, url_for # Importing redirect and url_for! 3 | 4 | app = Flask(__name__) 5 | 6 | @app.route("/") 7 | def home(): 8 | return render_template("index.html") 9 | 10 | @app.route("/page_2") 11 | def page_2(): 12 | return render_template("page_2.html") 13 | 14 | @app.route("/page_3", methods=["POST"]) 15 | def page_3(): 16 | username = request.form.get("username") 17 | 18 | print("I received the name:", username) 19 | return render_template("page_3.html") 20 | 21 | @app.route("/EXAMPLE/") 22 | def example(arg): 23 | print("The extension in the url is:", arg) 24 | return render_template("product.html", name=arg.split("_")[1], full_name=arg) 25 | 26 | if __name__ == "__main__": 27 | app.run(debug=True) -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_4/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

6 | Hello! Ahoj! ¡Hola!
7 | 8 | CLICK 9 | 10 |
11 | 12 | 1 13 | 14 |
15 | 16 | TYVOLE 17 | 18 |
19 | 20 | KAMO 21 | 22 |
23 | 24 | LASKO 25 | 26 |
27 |
28 | 29 |
30 |

31 | 32 | -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/catalog/management/commands/populate.py: -------------------------------------------------------------------------------- 1 | from catalog.models import Author, Book 2 | from django.core.management.base import BaseCommand 3 | from faker import Faker 4 | from random import randint 5 | 6 | class Command(BaseCommand): 7 | 8 | def handle(self, *args, **kwargs): 9 | fake = Faker() 10 | 11 | Author.objects.all().delete() 12 | Book.objects.all().delete() 13 | 14 | # Fake authors 15 | for _ in range(10): 16 | a = Author(name=fake.name()) 17 | a.save() 18 | 19 | # Fake books 20 | for _ in range(20): 21 | b = Book() 22 | b.title = fake.company() 23 | b.price = 15.99 24 | b.save() 25 | 26 | 27 | prev = -1 28 | for _ in range(randint(1, 2)): 29 | index = randint(0, 10-1) 30 | while index == prev: 31 | index = randint(0, 10-1) 32 | b.author.add(Author.objects.all()[index]) 33 | prev = index 34 | 35 | 36 | -------------------------------------------------------------------------------- /tutoriales/Python/mongodb/db.py: -------------------------------------------------------------------------------- 1 | import pymongo 2 | 3 | # Stablishing the connection with the db 4 | myclient = pymongo.MongoClient("mongodb://localhost:27017/") 5 | 6 | example_db = myclient["example_db"] 7 | example_collection = example_db["example_collection"] 8 | 9 | 10 | example_collection.insert_one({"name": "Kevin", "year": 1999}) 11 | example_collection.insertMany([ 12 | {"name": "Kevin", "year": 1999}, 13 | {"name": "a", "year": 1}, 14 | {"name": "b", "year": 2}, 15 | {"name": "c", "year": 3}, 16 | {"name": "d", "year": 4}, 17 | {"name": "e", "year": 5}, 18 | {"name": "f", "year": 6}, 19 | {"name": "g", "year": 7} 20 | ]) 21 | -------------------------------------------------------------------------------- /Python trading bot/backtesting/parsing_script.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | print("Parsing script 1/6 AUDUSD_5YEARS", end='\r') 4 | os.system('python csv_log_parser.py data/AUDUSD_5YEARS.csv data/AUDUSD_5YEARS.log') 5 | print("Parsing script 2/6 EURUSD_5YEARS", end='\r') 6 | os.system('python csv_log_parser.py data/EURUSD_5YEARS.csv data/EURUSD_5YEARS.log') 7 | print("Parsing script 3/6 GBPUSD_5YEARS", end='\r') 8 | os.system('python csv_log_parser.py data/GBPUSD_5YEARS.csv data/GBPUSD_5YEARS.log') 9 | print("Parsing script 4/6 USDCAD_5YEARS", end='\r') 10 | os.system('python csv_log_parser.py data/USDCAD_5YEARS.csv data/USDCAD_5YEARS.log') 11 | print("Parsing script 5/6 USDCHF_5YEARS", end='\r') 12 | os.system('python csv_log_parser.py data/USDCHF_5YEARS.csv data/USDCHF_5YEARS.log') 13 | print("Parsing script 6/6 USDJPY_5YEARS", end='\r') 14 | os.system('python csv_log_parser.py data/USDJPY_5YEARS.csv data/USDJPY_5YEARS.log') 15 | print() -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_3/tutorial3.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask import render_template, request # Importing request! 3 | 4 | app = Flask(__name__) 5 | 6 | @app.route("/") 7 | def home(): 8 | return render_template("index.html") 9 | 10 | @app.route("/page_2") 11 | def page_2(): 12 | return render_template("page_2.html") 13 | 14 | @app.route("/page_3", methods=["POST"]) 15 | def page_3(): 16 | #username = request.form.get("username") 17 | #username = request.form["username"] # We can access it as a dictionary 18 | 19 | #password = request.form["password"] # Error! password is not there 20 | password = request.form.get("password") # It returns None, not an exception 21 | #print("The password is:", password) 22 | 23 | print("I received the name:", password) 24 | return render_template("page_3.html") 25 | 26 | if __name__ == "__main__": 27 | app.run(debug=True) -------------------------------------------------------------------------------- /tutoriales/Python/sort.py: -------------------------------------------------------------------------------- 1 | import random 2 | from faker import Faker 3 | 4 | # Just for random strings 5 | fake = Faker() 6 | 7 | # Generating the list 8 | nums = [random.randint(0, 10) for _ in range(10)] 9 | print("Unsorted list:", nums) 10 | nums = sorted(nums) 11 | print("Sorted list:", nums) 12 | 13 | # List of tuples 14 | tuples = [(fake.first_name(), random.randint(0, 10)) for _ in range(10)] 15 | print("Unsorted list:", tuples) 16 | tuples = sorted(tuples) # Not working as expected 17 | # tuples = sorted(tuples, key=lambda tuple: tuple[1]) 18 | print("Sorted list:", tuples) 19 | 20 | # Sorting values of a dictionary 21 | dictionary = {fake.first_name(): random.randint(0, 10) for _ in range(10)} 22 | print("Unsorted dictionary:", dictionary) 23 | # dictionary = sorted(dictionary.values()) 24 | dictionary = sorted(dictionary.items(), key=lambda tuple: tuple[1], reverse=True) 25 | print("Sorted dictionary:", dictionary) -------------------------------------------------------------------------------- /tutoriales/C/Binary tree/node.c: -------------------------------------------------------------------------------- 1 | #include "node.h" 2 | #include 3 | #include 4 | 5 | struct _node { 6 | int data; 7 | Node *left; 8 | Node *right; 9 | }; 10 | 11 | Node *node_init(int data) { 12 | Node *n = NULL; 13 | 14 | n = (Node *)malloc(sizeof(Node)); 15 | if (n == NULL) { 16 | fprintf(stderr, "Error en la función node_init\n"); 17 | return NULL; 18 | } 19 | 20 | n->data = data; 21 | n->left = NULL; 22 | n->right = NULL; 23 | 24 | return n; 25 | } 26 | 27 | void node_destroy(Node *n) { 28 | if (n == NULL) return; 29 | 30 | node_destroy(n->left); 31 | node_destroy(n->right); 32 | 33 | free(n); 34 | } 35 | 36 | void node_add(Node *n, int data) { 37 | 38 | if (n == NULL) return; 39 | 40 | if (data > n->data) { 41 | if (n->right == NULL) n->right = node_init(data); 42 | else node_add(n->right, data); 43 | } else if (data <= n->data) { 44 | if (n->left == NULL) n->left = node_init(data); 45 | else node_add(n->left, data); 46 | } 47 | } -------------------------------------------------------------------------------- /tutoriales/C/mensajes/receptor.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define MQ_NAME "/mq_cola_queue" 8 | 9 | typedef struct { 10 | char msg[80]; 11 | } Mensaje; 12 | 13 | int main(void) { 14 | struct mq_attr attributes = { 15 | .mq_flags = 0, 16 | .mq_maxmsg = 10, 17 | .mq_curmsgs = 0, 18 | .mq_msgsize = sizeof(Mensaje) 19 | }; 20 | 21 | mqd_t queue = mq_open(MQ_NAME, 22 | O_CREAT | O_RDONLY, 23 | S_IRUSR | S_IWUSR, 24 | &attributes); 25 | 26 | 27 | Mensaje struct_to_receive; 28 | 29 | mq_receive(queue, (char *)&struct_to_receive, sizeof(struct_to_receive), NULL); 30 | 31 | printf("RECEPTOR: %s\n", struct_to_receive.msg); 32 | 33 | /* Wait for input to end the program */ 34 | fprintf(stdout, "Press any key to finish\n"); 35 | getchar(); 36 | 37 | mq_close(queue); 38 | 39 | return EXIT_SUCCESS; 40 | } -------------------------------------------------------------------------------- /tutoriales/C/mensajes/sender.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include 6 | #include 7 | #include 8 | #define MQ_NAME "/mq_cola_queue" 9 | 10 | typedef struct { 11 | char msg[80]; 12 | } Mensaje; 13 | 14 | int main(void) { 15 | struct mq_attr attributes = { 16 | .mq_flags = 0, 17 | .mq_maxmsg = 10, 18 | .mq_curmsgs = 0, 19 | .mq_msgsize = sizeof(Mensaje) 20 | }; 21 | 22 | mqd_t queue = mq_open(MQ_NAME, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR, &attributes); 23 | 24 | Mensaje struct_to_send; 25 | strcpy(struct_to_send.msg, "Este es el mensaje que voy a enviar"); 26 | 27 | mq_send(queue, (char *)&struct_to_send, sizeof(struct_to_send), 1); 28 | 29 | /* Wait for input to end the program */ 30 | fprintf(stdout, "Press any key to finish\n"); 31 | getchar(); 32 | 33 | mq_close(queue); 34 | mq_unlink(MQ_NAME); 35 | 36 | return EXIT_SUCCESS; 37 | } -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/tutorial/urls.py: -------------------------------------------------------------------------------- 1 | """tutorial URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path, include 18 | from catalog.views import index 19 | 20 | 21 | urlpatterns = [ 22 | path('admin/', admin.site.urls), 23 | path('catalog/', include('catalog.urls')), 24 | path('', index) 25 | ] 26 | -------------------------------------------------------------------------------- /tutoriales/C/Stack/main.c: -------------------------------------------------------------------------------- 1 | #include "stack.h" 2 | 3 | int main() { 4 | 5 | Stack *s = stack_ini(); 6 | 7 | push(s, 1); 8 | stack_print(s); 9 | push(s, 2); 10 | stack_print(s); 11 | push(s, 3); 12 | stack_print(s); 13 | push(s, 4); 14 | stack_print(s); 15 | 16 | printf("\n"); 17 | 18 | printf("POP %d - ", pop(s)); 19 | stack_print(s); 20 | printf("POP %d - ", pop(s)); 21 | stack_print(s); 22 | printf("POP %d - ", pop(s)); 23 | stack_print(s); 24 | printf("POP %d - ", pop(s)); 25 | stack_print(s); 26 | 27 | printf("\n"); 28 | 29 | push(s, 10); 30 | stack_print(s); 31 | push(s, 223); 32 | stack_print(s); 33 | push(s, 31); 34 | stack_print(s); 35 | push(s, 44); 36 | stack_print(s); 37 | 38 | printf("\n"); 39 | 40 | printf("POP %d - ", pop(s)); 41 | stack_print(s); 42 | printf("POP %d - ", pop(s)); 43 | stack_print(s); 44 | printf("POP %d - ", pop(s)); 45 | stack_print(s); 46 | printf("POP %d - ", pop(s)); 47 | stack_print(s); 48 | 49 | stack_destroy(s); 50 | 51 | return 0; 52 | } -------------------------------------------------------------------------------- /Python trading bot/backtesting/backtesting_script.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | print("Backtesting file 1/6 AUDUSD_5YEARS", end='\r') 4 | os.system('python backtester.py data/AUDUSD_5YEARS.log data/AUDUSD_5YEARS_backtested.log 15 AUDUSD') 5 | print("Backtesting file 2/6 EURUSD_5YEARS", end='\r') 6 | os.system('python backtester.py data/EURUSD_5YEARS.log data/EURUSD_5YEARS_backtested.log 15 EURUSD') 7 | print("Backtesting file 3/6 GBPUSD_5YEARS", end='\r') 8 | os.system('python backtester.py data/GBPUSD_5YEARS.log data/GBPUSD_5YEARS_backtested.log 15 GBPUSD') 9 | print("Backtesting file 4/6 USDCAD_5YEARS", end='\r') 10 | os.system('python backtester.py data/USDCAD_5YEARS.log data/USDCAD_5YEARS_backtested.log 15 USDCAD') 11 | print("Backtesting file 5/6 USDCHF_5YEARS", end='\r') 12 | os.system('python backtester.py data/USDCHF_5YEARS.log data/USDCHF_5YEARS_backtested.log 15 USDCHF') 13 | print("Backtesting file 6/6 USDJPY_5YEARS", end='\r') 14 | os.system('python backtester.py data/USDJPY_5YEARS.log data/USDJPY_5YEARS_backtested.log 15 USDJPY') 15 | print() -------------------------------------------------------------------------------- /tutoriales/Java/generic/generic_class.java: -------------------------------------------------------------------------------- 1 | public class generic_class { 2 | 3 | static Double add(T a, T b) { return a.doubleValue()+b.doubleValue(); } 4 | 5 | public static void main(String args[]){ 6 | GenericExample g1 = new GenericExample("Hola"); 7 | //GenericExample g2 = new GenericExample(2); 8 | //GenericOnlyNumbers g3 = new GenericExample("Hola"); 9 | //GenericOnlyNumbers g4 = new GenericOnlyNumbers(3); 10 | } 11 | } 12 | 13 | class GenericExample { 14 | private T attr; 15 | 16 | public GenericExample(T attr) { this.attr = attr; } 17 | 18 | public T get() { return attr; } 19 | public void set(T attr) { this.attr = attr; } 20 | } 21 | 22 | 23 | class GenericOnlyNumbers { 24 | 25 | private T attr; 26 | 27 | public GenericOnlyNumbers(T attr) { this.attr = attr; } 28 | 29 | public T get() { return attr; } 30 | public void set(T attr) { this.attr = attr; } 31 | } -------------------------------------------------------------------------------- /MQL5_PYTHON/RSI_BOT/RSI.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | PORT = 8688 4 | ADDR = "localhost" 5 | 6 | def socket_ini(): 7 | server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 | 9 | server_socket.bind((ADDR, PORT)) 10 | server_socket.listen(10) 11 | 12 | connection, addr = server_socket.accept() 13 | print("[INFO]\t", addr, "connected") 14 | 15 | return connection, server_socket 16 | 17 | 18 | def thread_rsi(stop_event, data): 19 | msg = "" 20 | 21 | connection, server_socket = socket_ini() 22 | 23 | while not stop_event.is_set(): 24 | msg = connection.recv(1024).decode() 25 | 26 | if "END CONNECTION" in msg: 27 | break 28 | 29 | rsi = msg.split(',') 30 | 31 | try: 32 | data["RSI"] = [float(m) for m in reversed(rsi)] 33 | except: 34 | print("[INFO]\tError trying to convert to float, ignored"); 35 | 36 | connection.close() 37 | server_socket.close() 38 | 39 | -------------------------------------------------------------------------------- /Django_tutorial/tutorial/tutorial/urls.py: -------------------------------------------------------------------------------- 1 | """tutorial URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path, include 18 | from catalog.views import home_page 19 | 20 | urlpatterns = [ 21 | path('admin/', admin.site.urls), 22 | path('authentication/', include('authentication.urls')), 23 | path('catalog/', include('catalog.urls')), 24 | path('', home_page, name='home'), 25 | ] 26 | -------------------------------------------------------------------------------- /mql5/news.mq5: -------------------------------------------------------------------------------- 1 | void OnInit() { 2 | // Eventos del euro 3 | MqlCalendarEvent eventos_euro[]; 4 | int euro_count = CalendarEventByCurrency("EUR", eventos_euro); 5 | Print("Hay ", IntegerToString(euro_count), " eventos del euro."); 6 | 7 | // Mostramos la fecha de cada evento y su importancia 8 | for (int i = 0; i < euro_count; i++) { 9 | Print("Evento ", eventos_euro[i].name, " con importancia=", eventos_euro[i].importance); 10 | 11 | Print("Calendario:"); 12 | MqlCalendarValue calendarios_eventos[]; 13 | datetime desde = D'2022.01.01 00:00'; 14 | if (CalendarValueHistoryByEvent(eventos_euro[i].id, calendarios_eventos, desde)) { 15 | 16 | // Recorremos todos los calendarios 17 | for (int n = 0; n < ArraySize(calendarios_eventos); n++) { 18 | Print("\tFecha: ", calendarios_eventos[n].time); 19 | } 20 | 21 | } else { 22 | Print("\tSin calendario"); 23 | } 24 | Print("------------------------------------------------------------"); 25 | } 26 | } -------------------------------------------------------------------------------- /tutoriales/Flask/flask_tutorial_7/tutorial7.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask import render_template, request, redirect, url_for 3 | from flask.globals import session 4 | 5 | app = Flask(__name__) 6 | app.secret_key = "oaknvciabvuahrajhvbahrbfvuabviuariuvahrvbauvbraiubva" 7 | 8 | @app.route("/") 9 | def home(): 10 | if "visits" not in session: 11 | session["visits"] = 1 12 | else: 13 | session["visits"] += 1 14 | return render_template("index.html", visits=session["visits"]) 15 | 16 | @app.route("/page_2") 17 | def page_2(): 18 | return render_template("page_2.html") 19 | 20 | @app.route("/page_3", methods=["POST"]) 21 | def page_3(): 22 | username = request.form.get("username") 23 | 24 | print("I received the name:", username) 25 | return render_template("page_3.html") 26 | 27 | @app.route("/EXAMPLE/") 28 | def example(arg): 29 | print("The extension in the url is:", arg) 30 | return render_template("product.html", name=arg.split("_")[1], full_name=arg) 31 | 32 | if __name__ == "__main__": 33 | app.run(debug=True) -------------------------------------------------------------------------------- /MQL5_PYTHON/INDEX_BOT/CANDLE.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import json 3 | 4 | PORT = 8678 5 | ADDR = "localhost" 6 | 7 | def socket_ini(): 8 | server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 9 | 10 | server_socket.bind((ADDR, PORT)) 11 | server_socket.listen(10) 12 | 13 | connection, addr = server_socket.accept() 14 | print("[INFO]\t", addr, "connected") 15 | 16 | return connection, server_socket 17 | 18 | 19 | def thread_candle(stop_event, data): 20 | msg = "" 21 | 22 | connection, server_socket = socket_ini() 23 | 24 | while not stop_event.is_set(): 25 | msg = connection.recv(1024).decode() 26 | 27 | if "END" in msg: 28 | break 29 | 30 | try: 31 | temp = json.loads(msg) 32 | data['0'], data['1'] = temp['0'], temp['1'] 33 | except: 34 | print("[INFO]\tError trying to convert to float, ignored") 35 | break 36 | 37 | 38 | connection.close() 39 | server_socket.close() 40 | -------------------------------------------------------------------------------- /tutoriales/C/sockets/client.c: -------------------------------------------------------------------------------- 1 | /* SOCKETS */ 2 | #include 3 | #include 4 | 5 | /* Descriptor functions (read and close) */ 6 | #include 7 | 8 | /* Classic tyvole */ 9 | #include 10 | #include 11 | 12 | /* For htons */ 13 | #include // man inet 14 | 15 | void main() { 16 | int client_descriptor = 0; 17 | 18 | struct sockaddr_in address; 19 | address.sin_family = AF_INET; 20 | address.sin_addr.s_addr = INADDR_ANY; 21 | address.sin_port = htons( 5001 ); 22 | 23 | /* Creating the client's socket IPv4 TCP */ 24 | client_descriptor = socket(AF_INET, SOCK_STREAM, 0); 25 | 26 | /* Connecting to the server */ 27 | connect(client_descriptor, (struct sockaddr *)&address,sizeof (address)); 28 | printf("Connected to the server\n"); 29 | 30 | char msg[100] = ""; 31 | 32 | printf("Write something to send to the server: "); 33 | scanf("%s", msg); 34 | 35 | printf("Sending the message to the server\n"); 36 | write(client_descriptor, msg, 100); 37 | 38 | close(client_descriptor); 39 | } -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/catalog/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from django.template.defaultfilters import slugify 3 | 4 | 5 | class Author(models.Model): 6 | name = models.CharField(max_length=100) 7 | slug = models.SlugField(null=True, 8 | blank=True) 9 | 10 | def __str__(self): 11 | return self.name 12 | 13 | def save(self, *args, **kwargs): 14 | self.slug = slugify(self.name) 15 | return super().save(*args, **kwargs) 16 | 17 | 18 | class Book(models.Model): 19 | title = models.CharField(max_length=100) 20 | price = models.DecimalField(decimal_places=2, 21 | max_digits=4) 22 | slug = models.SlugField(null=True, 23 | blank=True) 24 | author = models.ManyToManyField(Author) 25 | 26 | class Meta: 27 | ordering = ['title', 'price'] 28 | 29 | def save(self, *args, **kwargs): 30 | self.slug = slugify(self.title) 31 | return super().save(*args, **kwargs) 32 | 33 | def __str__(self): 34 | return self.title+" - "+str(self.price)+"€" 35 | -------------------------------------------------------------------------------- /Django_tutorial/tutorial/catalog/views.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth.decorators import login_required 2 | from django.shortcuts import redirect, render 3 | from .models import Actor, Film 4 | from django.views import generic 5 | 6 | def home_page(request): 7 | num_actors = Actor.objects.all().count() 8 | num_film = Film.objects.all().count() 9 | 10 | data_dict = { 11 | 'number_actors': num_actors, 12 | 'number_films': num_film, 13 | } 14 | 15 | return render(request, 'index.html', context=data_dict) 16 | 17 | 18 | class ActorListView(generic.ListView): 19 | model = Actor 20 | context_object_name = 'actor_list' 21 | 22 | 23 | class FilmListView(generic.ListView): 24 | model = Film 25 | context_object_name = 'film_list' 26 | 27 | 28 | class ActorDetailView(generic.DetailView): 29 | model = Actor 30 | 31 | 32 | class FilmDetailView(generic.DetailView): 33 | model = Film 34 | 35 | @login_required 36 | def post_score(request, slug): 37 | score = request.POST.get("score") 38 | film = Film.objects.filter(slug=slug)[0] 39 | if score is not None and score != "": 40 | film.set_score(int(score)) 41 | return redirect(film.get_absolute_url()) -------------------------------------------------------------------------------- /tutoriales/Django/tutorial/catalog/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.6 on 2021-12-24 08:07 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='Author', 16 | fields=[ 17 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('name', models.CharField(max_length=100)), 19 | ('slug', models.SlugField(null=True)), 20 | ], 21 | ), 22 | migrations.CreateModel( 23 | name='Book', 24 | fields=[ 25 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 26 | ('title', models.CharField(max_length=100)), 27 | ('price', models.DecimalField(decimal_places=2, max_digits=4)), 28 | ('slug', models.SlugField(blank=True, null=True)), 29 | ], 30 | ), 31 | ] 32 | -------------------------------------------------------------------------------- /Django_tutorial/tutorial/authentication/templates/registration/login.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% block title %}Log In{% endblock %} 3 | {% block content %} 4 | 5 | {% if form.errors %} 6 |

Your username and password didn't match. Please try again.

7 | {% endif %} 8 | 9 | {% if next %} 10 | {% if user.is_authenticated %} 11 |

Your account doesn't have access to this page. To proceed, 12 | please login with an account that has access.

13 | {% else %} 14 |

Please login to see this page.

15 | {% endif %} 16 | {% endif %} 17 | 18 |
19 | {% csrf_token %} 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 |
{{ form.username.label_tag }}{{ form.username }}
{{ form.password.label_tag }}{{ form.password }}
30 | 31 | 32 |
33 | 34 | {# Assumes you setup the password_reset view in your URLconf #} 35 |

Lost password?

36 | 37 | {% endblock %} -------------------------------------------------------------------------------- /tutoriales/C/Stack/stack.c: -------------------------------------------------------------------------------- 1 | #include "stack.h" 2 | 3 | 4 | struct _stack { 5 | int *items; 6 | short num_items; 7 | }; 8 | 9 | 10 | Stack *stack_ini() { 11 | 12 | Stack *s = NULL; 13 | 14 | s = (Stack *)malloc(sizeof(Stack)); 15 | if (s == NULL) return NULL; 16 | 17 | s->items = NULL; 18 | s->num_items = 0; 19 | } 20 | 21 | void push(Stack *s, int value) { 22 | 23 | s->items = (int *)realloc(s->items, (s->num_items+1)*sizeof(int)); 24 | if (s == NULL) return; 25 | 26 | s->items[s->num_items] = value; 27 | 28 | s->num_items++; 29 | } 30 | 31 | int pop(Stack *s) { 32 | 33 | if (s->num_items == 0) return -1; 34 | 35 | int last = s->items[s->num_items-1]; 36 | 37 | if (s->num_items - 1 > 0) { 38 | s->items = (int *)realloc(s->items, (s->num_items - 1)*sizeof(int)); 39 | if (s->items == NULL) return -1; 40 | } else { 41 | free(s->items); 42 | s->items = NULL; 43 | } 44 | 45 | s->num_items--; 46 | 47 | return last; 48 | } 49 | 50 | void stack_destroy(Stack *s) { 51 | if (s->items != NULL) free(s->items); 52 | free(s); 53 | } 54 | 55 | void stack_print(Stack *s) { 56 | for (int i = 0; i < s->num_items; i++) 57 | printf("%d ", s->items[i]); 58 | printf("\n"); 59 | } -------------------------------------------------------------------------------- /mql5/index_bot.mq5: -------------------------------------------------------------------------------- 1 | #include 2 | CTrade trade; 3 | ulong trade_ticket = 0; 4 | 5 | MqlRates candles[]; 6 | 7 | bool time_flag = true; 8 | 9 | double get_lotage() { 10 | double balance = AccountInfoDouble(ACCOUNT_BALANCE); 11 | double lotage = NormalizeDouble((balance/1000)*0.2, 2); 12 | return lotage <= 50 ? lotage : 50; 13 | } 14 | 15 | bool bullish(int candle_pos, double candle_len=0) { 16 | return candles[candle_pos].close-candles[candle_pos].open > candle_len; 17 | } 18 | 19 | void OnInit() { 20 | ArraySetAsSeries(candles, true); 21 | } 22 | 23 | void OnTick() { 24 | CopyRates(_Symbol, _Period, 0, 3, candles); 25 | 26 | if (bullish(1) && !bullish(0) && trade_ticket <= 0 && time_flag) { 27 | 28 | double bid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits); 29 | 30 | trade.Sell(get_lotage(), _Symbol, bid); 31 | trade_ticket = trade.ResultOrder(); 32 | 33 | time_flag = false; 34 | 35 | } else if (trade_ticket > 0 && bullish(0, 500*_Point)) { 36 | trade.PositionClose(trade_ticket); 37 | 38 | trade_ticket = 0; 39 | 40 | EventSetTimer(60); 41 | } 42 | } 43 | 44 | void OnTimer() { time_flag = true; } -------------------------------------------------------------------------------- /tutoriales/C/Queue/queue.c: -------------------------------------------------------------------------------- 1 | #include "queue.h" 2 | 3 | 4 | struct _queue { 5 | int *items; 6 | short num_items; 7 | }; 8 | 9 | 10 | Queue *queue_ini() { 11 | Queue *q = NULL; 12 | 13 | q = (Queue *)malloc(sizeof(Queue)); 14 | if (q == NULL) return NULL; 15 | 16 | q->items = NULL; 17 | q->num_items = 0; 18 | } 19 | 20 | void push(Queue *q, int value) { 21 | q->items = realloc(q->items, (q->num_items+1)*sizeof(int)); 22 | if (q == NULL) return; 23 | 24 | q->items[q->num_items] = value; 25 | 26 | q->num_items++; 27 | } 28 | 29 | int pop(Queue *q) { 30 | if (q->num_items == 0) return -1; 31 | 32 | int first = q->items[0]; 33 | 34 | if (q->num_items-1 > 0) { 35 | for(int i = 0; i+1 < q->num_items; i++) 36 | q->items[i] = q->items[i+1]; 37 | 38 | q->items = realloc(q->items, (q->num_items-1)*sizeof(int)); 39 | if (q == NULL) return -1; 40 | 41 | } else { 42 | free(q->items); 43 | q->items = NULL; 44 | } 45 | 46 | q->num_items--; 47 | 48 | return first; 49 | } 50 | 51 | void queue_destroy(Queue *q) { 52 | if (q->items != NULL) free(q->items); 53 | free(q); 54 | } 55 | 56 | void queue_print(Queue *q) { 57 | for (int i = 0; i < q->num_items; i++) 58 | printf("%d ", q->items[i]); 59 | printf("\n"); 60 | } -------------------------------------------------------------------------------- /Django_tutorial/tutorial/authentication/templates/registration/password_reset_confirm.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 | {% if validlink %} 5 |

Please enter (and confirm) your new password.

6 |
7 | {% csrf_token %} 8 | 9 | 10 | 12 | 13 | 14 | 15 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |
{{ form.new_password1.errors }} 11 | {{ form.new_password1 }}
{{ form.new_password2.errors }} 16 | {{ form.new_password2 }}
24 |
25 | {% else %} 26 |

Password reset failed

27 |

The password reset link was invalid, possibly because it has already been used. Please request a new password reset.

28 | {% endif %} 29 | {% endblock %} -------------------------------------------------------------------------------- /mql5/index_crash.mq5: -------------------------------------------------------------------------------- 1 | #include 2 | CTrade trade; 3 | ulong trade_ticket = 0; 4 | bool time_flag = true; 5 | 6 | MqlRates candles[]; 7 | 8 | /*double get_lotage() { // The lotage grows, not static 9 | double balance = AccountInfoDouble(ACCOUNT_BALANCE); 10 | double lotage = NormalizeDouble((balance/1000)*0.2, 2); 11 | return lotage <= 50 ? lotage : 50; 12 | }*/ 13 | 14 | double get_lotage() { return 0.1; } 15 | 16 | bool bearish(int candle_pos, double candle_len=0) { 17 | return candles[candle_pos].open-candles[candle_pos].close > candle_len; 18 | } 19 | 20 | void OnInit() { 21 | ArraySetAsSeries(candles, true); 22 | } 23 | 24 | void OnTick() { 25 | CopyRates(_Symbol, _Period, 0, 3, candles); 26 | 27 | if (bearish(0, 200*_Point) && time_flag) { 28 | double bid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits); 29 | 30 | trade.Sell(get_lotage(), _Symbol, bid); 31 | trade_ticket = trade.ResultOrder(); 32 | 33 | time_flag = false; 34 | EventSetTimer(60); 35 | 36 | } else if (trade_ticket > 0 && !bearish(0)) { 37 | 38 | trade.PositionClose(trade_ticket); 39 | trade_ticket = 0; 40 | 41 | } 42 | } 43 | 44 | void OnTimer() { 45 | time_flag = true; 46 | EventKillTimer(); 47 | } -------------------------------------------------------------------------------- /mql5/index_boom.mq5: -------------------------------------------------------------------------------- 1 | #include 2 | CTrade trade; 3 | ulong trade_ticket = 0; 4 | bool time_flag = true; 5 | 6 | MqlRates candles[]; 7 | 8 | /*double get_lotage() { 9 | double balance = AccountInfoDouble(ACCOUNT_BALANCE); 10 | double lotage = NormalizeDouble((balance/1000)*0.2, 2); 11 | return lotage <= 50 ? lotage : 50; 12 | }*/ 13 | 14 | double get_lotage() { return 0.1; } 15 | 16 | bool bullish(int candle_pos, double candle_len=0) { 17 | return candles[candle_pos].close-candles[candle_pos].open > candle_len; 18 | } 19 | 20 | void OnInit() { 21 | ArraySetAsSeries(candles, true); 22 | } 23 | 24 | void OnTick() { 25 | CopyRates(_Symbol, _Period, 0, 3, candles); 26 | 27 | if (bullish(0, 200*_Point) && time_flag) { 28 | double ask = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK), _Digits); 29 | 30 | trade.Buy(get_lotage(), _Symbol, ask); 31 | trade_ticket = trade.ResultOrder(); 32 | 33 | time_flag = false; 34 | EventSetTimer(60); 35 | 36 | } else if (trade_ticket > 0 && !bullish(0)) { 37 | 38 | trade.PositionClose(trade_ticket); 39 | trade_ticket = 0; 40 | 41 | } 42 | } 43 | 44 | void OnTimer() { 45 | time_flag = true; 46 | EventKillTimer(); 47 | } -------------------------------------------------------------------------------- /mql5/line.mq5: -------------------------------------------------------------------------------- 1 | int MAX_CANDLES = 50; 2 | 3 | MqlRates candles[]; 4 | double closes[]; 5 | 6 | bool line_created = false; 7 | 8 | double avg_close_in_period(int start, int end) { 9 | double values = 0; 10 | for (int i = start; i < end; i++) values += closes[i]; 11 | return values/(end-start); 12 | } 13 | 14 | int OnInit() { 15 | ArraySetAsSeries(candles, true); 16 | ArraySetAsSeries(closes, true); 17 | 18 | return INIT_SUCCEEDED; 19 | } 20 | 21 | 22 | void OnTick() { 23 | 24 | // Loading the candles 25 | CopyRates(_Symbol, _Period, 0, MAX_CANDLES, candles); 26 | 27 | // Getting all the closes 28 | CopyClose(_Symbol, _Period, 0, MAX_CANDLES, closes); 29 | 30 | double avg_first = avg_close_in_period(MAX_CANDLES/2, MAX_CANDLES); 31 | double avg_second = avg_close_in_period(0, MAX_CANDLES/2); 32 | 33 | Print(candles[MAX_CANDLES-1].time, " ", candles[0].time); 34 | 35 | // Setting the lines 36 | if (line_created == true) ObjectDelete(0, "line"); 37 | else line_created = true; 38 | ObjectCreate(0, "line", OBJ_TREND, 0, candles[MAX_CANDLES-1].time, avg_first, candles[0].time, avg_second); 39 | 40 | // Setting the color 41 | ObjectSetInteger(0, "line", OBJPROP_COLOR, clrAqua); 42 | 43 | // Setting the width 44 | ObjectSetInteger(0, "line", OBJPROP_WIDTH, 4); 45 | } -------------------------------------------------------------------------------- /mql5/rsi.mq5: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int rsi_h; 4 | 5 | double rsi[]; 6 | 7 | CTrade trade; 8 | ulong trade_ticket = 0; 9 | bool time_passed = true; 10 | 11 | int OnInit() { 12 | rsi_h = iRSI(_Symbol, _Period, 14, PRICE_CLOSE); 13 | ArraySetAsSeries(rsi, true); 14 | return (INIT_SUCCEEDED); 15 | } 16 | 17 | void OnTick() { 18 | CopyBuffer(rsi_h, 0, 1, 3, rsi); 19 | 20 | if (PositionSelectByTicket(trade_ticket) == false) trade_ticket = 0; 21 | 22 | if (rsi[0] < 30 && trade_ticket <= 0 && time_passed == true) { // compras 23 | double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK), _Digits); 24 | 25 | trade.Buy(0.1, _Symbol, Ask, Ask-40*_Point, Ask+80*_Point, NULL); 26 | trade_ticket = trade.ResultOrder(); 27 | time_passed = false; 28 | 29 | EventSetTimer(PeriodSeconds(PERIOD_CURRENT)*15); 30 | } else if (rsi[0] > 70 && trade_ticket <= 0 && time_passed == true) { // Ventas 31 | double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits); 32 | 33 | trade.Sell(0.1, _Symbol, Bid, Bid+40*_Point, Bid-80*_Point, NULL); 34 | trade_ticket = trade.ResultOrder(); 35 | time_passed = false; 36 | 37 | EventSetTimer(PeriodSeconds(PERIOD_CURRENT)*15); 38 | } 39 | } 40 | 41 | void OnTimer() { 42 | time_passed = true; 43 | } -------------------------------------------------------------------------------- /MQL5_PYTHON/client_closes.mq5: -------------------------------------------------------------------------------- 1 | string address = "localhost"; 2 | int port = 8466; 3 | short num_msg = 0; 4 | bool closed = false; 5 | int socket; 6 | MqlRates candles[]; 7 | 8 | void OnInit() { 9 | 10 | // Initializing candles 11 | ArraySetAsSeries(candles, true); 12 | 13 | // Initializing the socket 14 | socket = SocketCreate(); 15 | if (socket == INVALID_HANDLE) Print("Error - 1: SocketCreate failure. ", GetLastError()); 16 | else { 17 | if (SocketConnect(socket, address, port, 10000)) Print("[INFO]\tConnection stablished"); 18 | else Print("Error - 2: SocketConnect failure. ", GetLastError()); 19 | } 20 | } 21 | 22 | void OnTick() { 23 | CopyRates(_Symbol, _Period, 0, 1, candles); 24 | 25 | if (num_msg < 10) { 26 | Print("[INFO]\tSending close"); 27 | num_msg++; 28 | string msg; 29 | StringConcatenate(msg, _Symbol, " CLOSE: ", candles[0].close); 30 | 31 | char req[]; 32 | int len = StringToCharArray(msg, req)-1; 33 | SocketSend(socket, req, len); 34 | } else { 35 | if (!closed) { 36 | // Creating the message 37 | char req[]; 38 | int len = StringToCharArray("END CONNECTION\0", req)-1; 39 | 40 | SocketSend(socket, req, len); 41 | 42 | SocketClose(socket); 43 | closed = true; 44 | } 45 | } 46 | 47 | } -------------------------------------------------------------------------------- /mql5/martingala.mq5: -------------------------------------------------------------------------------- 1 | #include 2 | CTrade trade; 3 | ulong trade_ticket = 0; 4 | 5 | MqlRates candles[]; 6 | 7 | bool time_flag = true; 8 | 9 | int multiplier = 1; 10 | 11 | double get_lotage() { 12 | 13 | HistorySelect(TimeCurrent()-(12*60*60), TimeCurrent()); 14 | 15 | ulong prev_trade_ticket = HistoryDealGetTicket(HistoryDealsTotal()-1); 16 | double profit = HistoryDealGetDouble(prev_trade_ticket, DEAL_PROFIT); 17 | 18 | if (profit < 0) multiplier *= 5; 19 | else multiplier = 1; 20 | 21 | double balance = AccountInfoDouble(ACCOUNT_BALANCE); 22 | double lotage = NormalizeDouble((balance/1000)*0.01*multiplier, 2); 23 | return lotage <= 50 ? lotage : 50; 24 | } 25 | 26 | void OnInit() { 27 | ArraySetAsSeries(candles, true); 28 | } 29 | 30 | bool alcista(int pos, double len=0) { 31 | return candles[pos].close-candles[pos].open > len; 32 | } 33 | 34 | void OnTick() { 35 | CopyRates(_Symbol, _Period, 0, 3, candles); 36 | 37 | if (PositionSelectByTicket(trade_ticket) == false) trade_ticket = 0; 38 | 39 | if (alcista(1) && !alcista(0) && trade_ticket <= 0) { 40 | 41 | double bid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits); 42 | 43 | trade.Sell(get_lotage(), _Symbol, bid, bid+2000*_Point, bid-2000*_Point); 44 | trade_ticket = trade.ResultOrder(); 45 | } 46 | } -------------------------------------------------------------------------------- /tutoriales/C/Linked list/test.c: -------------------------------------------------------------------------------- 1 | #include "linked_list.h" 2 | 3 | int main() { 4 | 5 | Linked_list *l = linked_list_init(); 6 | if (l == NULL) { 7 | fprintf(stderr, "Error creating the linked list.\n"); 8 | return -1; 9 | } 10 | 11 | if (linked_list_add_node(l, 1) == -1) { 12 | fprintf(stderr, "Error adding a node.\n"); 13 | linked_list_destroy(l); 14 | return -1; 15 | } 16 | if (linked_list_add_node(l, 2589) == -1) { 17 | fprintf(stderr, "Error adding a node.\n"); 18 | linked_list_destroy(l); 19 | return -1; 20 | } 21 | if (linked_list_add_node(l, 3) == -1) { 22 | fprintf(stderr, "Error adding a node.\n"); 23 | linked_list_destroy(l); 24 | return -1; 25 | } 26 | if (linked_list_add_node(l, 348) == -1) { 27 | fprintf(stderr, "Error adding a node.\n"); 28 | linked_list_destroy(l); 29 | return -1; 30 | } 31 | 32 | if (linked_list_add_node(l, 30) == -1) { 33 | fprintf(stderr, "Error adding a node.\n"); 34 | linked_list_destroy(l); 35 | return -1; 36 | } 37 | if (linked_list_add_node(l, 18) == -1) { 38 | fprintf(stderr, "Error adding a node.\n"); 39 | linked_list_destroy(l); 40 | return -1; 41 | } 42 | 43 | linked_list_print(l); 44 | linked_list_destroy(l); 45 | } -------------------------------------------------------------------------------- /Django_tutorial/tutorial/catalog/management/commands/populate.py: -------------------------------------------------------------------------------- 1 | from django.core.management.base import BaseCommand 2 | from catalog.models import Actor, Film, Comment 3 | import random 4 | 5 | 6 | film_names = ["Spiderman", "Spiderman 2", "Spiderman 3", 7 | "The Amazing Spiderman", "The Amazing Spiderman 2", 8 | "Doctor Strange", "Avengers", "Avengers Age of ultron", "Avengers Endgame", "Avengers Infinity war"] 9 | 10 | actor_names = ["Tom Holland", "Tom hardy", "Robert dw jn", "Scarlett Johanson", "Benedict cumber", "Chris Evans", "Chris hemsworth", "Zendaya"] 11 | 12 | class Command(BaseCommand): 13 | 14 | def handle(self, *args, **kwargs): 15 | for actor in actor_names: 16 | a = Actor(name=actor, age=random.randint(18, 50)) 17 | a.save() 18 | 19 | for film in film_names: 20 | f = Film() 21 | f.title = film 22 | f.price = 10.99 23 | f.score = random.randint(0,10) 24 | f.save() 25 | 26 | actors_in_movie = [] 27 | for _ in range(random.randint(1, 5)): 28 | index = random.randint(0, len(actor_names)-1) 29 | while index in actors_in_movie: 30 | index = random.randint(0, len(actor_names)-1) 31 | actors_in_movie.append(index) 32 | 33 | f.actor.add(Actor.objects.all()[index]) 34 | 35 | for i in range(10): 36 | c = Comment(text="Comment "+str(i), film=Film.objects.all()[random.randint(0, len(film_names)-1)]) 37 | c.save() 38 | 39 | -------------------------------------------------------------------------------- /mql5/high_lows.mq5: -------------------------------------------------------------------------------- 1 | int MAX_CANDLES = 100; 2 | 3 | MqlRates candles[]; 4 | double closes[]; 5 | 6 | 7 | int OnInit() { 8 | 9 | ArraySetAsSeries(candles, true); 10 | ArraySetAsSeries(closes, true); 11 | 12 | // Loading the candles 13 | CopyRates(_Symbol, _Period, 0, MAX_CANDLES, candles); 14 | 15 | // Setting the lines 16 | ObjectCreate(0, "CustomHigh", OBJ_HLINE, 0, 0, candles[0].close); 17 | ObjectCreate(0, "CustomLow", OBJ_HLINE, 0, 0, candles[0].close); 18 | 19 | return INIT_SUCCEEDED; 20 | } 21 | 22 | 23 | void OnTick(void) { 24 | 25 | // Loading the candles 26 | CopyRates(_Symbol, _Period, 0, MAX_CANDLES, candles); 27 | 28 | // Getting all the closes 29 | CopyClose(_Symbol, _Period, 0, MAX_CANDLES, closes); 30 | 31 | int index_highest = ArrayMaximum(closes, 0, 50); 32 | int index_lowest = ArrayMinimum(closes, 0, 50); 33 | 34 | // Setting the color 35 | ObjectSetInteger(0, "CustomHigh", OBJPROP_COLOR, clrDarkOliveGreen); 36 | ObjectSetInteger(0, "CustomLow", OBJPROP_COLOR, clrAqua); 37 | 38 | // Setting the width 39 | ObjectSetInteger(0, "CustomHigh", OBJPROP_WIDTH, 2); 40 | ObjectSetInteger(0, "CustomLow", OBJPROP_WIDTH, 2); 41 | 42 | // Moving the line to the last close 43 | ObjectMove(0, "CustomHigh", 0, 0, candles[index_highest].close); 44 | ObjectMove(0, "CustomLow", 0, 0, candles[index_lowest].close); 45 | } -------------------------------------------------------------------------------- /tutoriales/Python/sems_exercise/sem.py: -------------------------------------------------------------------------------- 1 | import threading 2 | from random import randint 3 | from time import sleep 4 | 5 | NUM_KIDS = 10 6 | AVAILABLE_PIECES = 3 7 | 8 | mutex = threading.Semaphore(1) 9 | 10 | 11 | def call_mum_for_cakes(): 12 | global AVAILABLE_PIECES 13 | 14 | sleep(5) 15 | AVAILABLE_PIECES = 3 16 | print("I'm mum, and I have brought a new cake") 17 | 18 | def kid(n): 19 | global AVAILABLE_PIECES 20 | 21 | sleep(randint(1, 9)) 22 | 23 | for _ in range(randint(1, 4)): 24 | # Go to the queue 25 | mutex.acquire() 26 | 27 | # If there are no pieces every one waits until there's a new cake 28 | if AVAILABLE_PIECES <= 0: 29 | call_mum_for_cakes() 30 | 31 | # Since we are taking a piece we must delete one 32 | AVAILABLE_PIECES -= 1 33 | 34 | # Kid N is takes his piece of cake 35 | print("I'm the kid", n, "and I'm taking my peace of cake. There are", AVAILABLE_PIECES, "left") 36 | sleep(randint(1, 3)) 37 | 38 | # Kid got his food 39 | mutex.release() 40 | 41 | # Kid N is going to eat 42 | print("I'm the kid", n, "and I'm eating") 43 | sleep(randint(3, 6)) 44 | 45 | 46 | threads = [] 47 | for i in range(NUM_KIDS): 48 | threads.append(threading.Thread(target=kid, args=(i+1,))) 49 | threads[-1].start() 50 | 51 | for t in threads: 52 | t.join() -------------------------------------------------------------------------------- /mql5/sound.mq5: -------------------------------------------------------------------------------- 1 | // https://www.mql5.com/es/articles/748 2 | 3 | #include 4 | #resource "\\Files\\sound.wav" 5 | 6 | /* Handler */ 7 | int MACD_h; 8 | 9 | /* Arrays where the indicator data is stored */ 10 | double MACD[]; 11 | double SIGNAL[]; 12 | 13 | /* For openning operations */ 14 | CTrade trade; 15 | ulong trade_ticket = 0; 16 | bool time_passed = true; 17 | 18 | 19 | int OnInit() { 20 | 21 | PlaySound("::Files\\sound.wav"); 22 | /* Initializing the handlers */ 23 | MACD_h = iMACD(_Symbol, _Period, 12, 26, 9, PRICE_CLOSE); 24 | 25 | ArraySetAsSeries(MACD, true); 26 | ArraySetAsSeries(SIGNAL, true); 27 | 28 | return(INIT_SUCCEEDED); 29 | } 30 | 31 | void OnTick() { 32 | /* Saving the data of the indicator */ 33 | CopyBuffer(MACD_h, 0, 1, 4, MACD); 34 | CopyBuffer(MACD_h, 1, 1, 4, SIGNAL); 35 | 36 | /* Checking if there's an open operation */ 37 | if (PositionSelectByTicket(trade_ticket) == false) { 38 | // Reseting the trade flags 39 | trade_ticket = 0; 40 | } 41 | 42 | 43 | if ( // Buy 44 | MACD[1] < SIGNAL[1] && MACD[0] > SIGNAL[0] // Cross 45 | ) { 46 | PlaySound("::Files\\sound.wav"); 47 | } else if ( // venta 48 | MACD[1] > SIGNAL[1] && MACD[0] < SIGNAL[0] // Cross 49 | ) { 50 | PlaySound("::Files\\sound.wav"); 51 | } 52 | } 53 | 54 | void OnTimer() { 55 | time_passed = true; 56 | } -------------------------------------------------------------------------------- /Python trading bot/backtesting/csv_log_parser.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import matplotlib.pyplot as plt 3 | import sys 4 | 5 | # Parser from metatrader 5 csv format to our format 6 | # Getting the information 7 | FILENAME = sys.argv[1] 8 | SAVEFILE = sys.argv[2] 9 | 10 | # Opening the file 11 | f = open(FILENAME, 'r') 12 | 13 | # Opening saving file 14 | f2 = open(SAVEFILE, 'w') 15 | 16 | # Calculando epoch 17 | epoch = datetime.datetime.utcfromtimestamp(0) 18 | 19 | # Moving through the lines 20 | i = 0 21 | for line in f: 22 | if i == 0: 23 | i+=1 24 | continue 25 | # Removing comas and splitting the line 26 | splitted = line.replace(',', '').split('\t') 27 | if splitted[2] == '': 28 | continue 29 | 30 | # Adding the right date 31 | time = splitted[0].split('.') 32 | hour = splitted[1].split(':') 33 | date = datetime.datetime(int(time[0]), # Year 34 | int(time[1]), # Month 35 | int(time[2]), # Day 36 | int(hour[0]), # Hour 37 | int(hour[1]), # Minute 38 | int(float(hour[2])), # second 39 | int( ( float(hour[2])-int(float(hour[2])) )*1000000 ) ) # Microsecond 40 | date = date.timestamp() 41 | f2.write(str(date)+'\t'+str(splitted[2])+'\n') 42 | 43 | # Closing the files 44 | f2.close() 45 | f.close() -------------------------------------------------------------------------------- /MQL5_PYTHON/MACD_BOT/MACD.py: -------------------------------------------------------------------------------- 1 | from http import server 2 | import socket 3 | 4 | 5 | def socket_ini(): 6 | """Function to initialice a server to receive the MACD info. 7 | 8 | Returns: 9 | Connection object 10 | """ 11 | server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 12 | 13 | server_socket.bind(("localhost", 8888)) 14 | server_socket.listen(10) 15 | 16 | connection, addr = server_socket.accept() 17 | print("[INFO]\tConnected with:", addr) 18 | 19 | return connection, server_socket 20 | 21 | def thread_macd(stop_event, data): 22 | """Function executed by a thread. Loads the MACD indicator 23 | directly from MT5 24 | 25 | Args: 26 | stop_event (thread.Event): Event to stop the thread. 27 | data (dict): Dictionary where the data is going to be stored. 28 | """ 29 | msg = "" 30 | 31 | connection, server_socket = socket_ini() 32 | 33 | while not stop_event.wait(0.00001): 34 | # Taking the ticks 35 | msg = connection.recv(1024).decode() 36 | 37 | if "END CONNECTION" in msg: 38 | break 39 | macds, signals = msg.split("|") 40 | macds, signals = macds.split(","), signals.split(",") 41 | 42 | data["MACD"] = [float(m) for m in reversed(macds)] 43 | data["SIGNAL"] = [float(s) for s in reversed(signals)] 44 | 45 | connection.close() 46 | server_socket.close() 47 | 48 | -------------------------------------------------------------------------------- /tutoriales/C/Semaphores/named.c: -------------------------------------------------------------------------------- 1 | /* FOR SEMAPHORE */ 2 | #include 3 | #include /* For O_* constants */ 4 | #include /* For mode constants */ 5 | 6 | #include 7 | #include 8 | 9 | /* FOR FORK */ 10 | #include 11 | #include 12 | 13 | /* FOR KILLING THE CHILD PROCESS */ 14 | #include 15 | 16 | #define SEM_NAME_1 "/sem_1" 17 | #define SEM_NAME_2 "/sem_2" 18 | 19 | void main() { 20 | sem_t *sem1 = NULL, *sem2 = NULL; 21 | 22 | /* If O_CREAT and O_EXCL are here then if the semaphore exists it will give us an error */ 23 | sem1 = sem_open(SEM_NAME_1, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, 0); 24 | sem2 = sem_open(SEM_NAME_2, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, 0); 25 | 26 | if (fork() == 0) { // child 27 | printf("1\n"); 28 | sem_post(sem1); 29 | sem_wait(sem2); 30 | printf("3\n"); 31 | sem_post(sem1); 32 | 33 | /* Every process closes the sems */ 34 | sem_close(sem1); 35 | sem_close(sem2); 36 | } else { // father 37 | sem_wait(sem1); 38 | printf("2\n"); 39 | sem_post(sem2); 40 | sem_wait(sem1); 41 | printf("4\n"); 42 | 43 | wait(NULL); 44 | 45 | /* Every process closes the sems */ 46 | sem_close(sem1); 47 | sem_close(sem2); 48 | 49 | /* Only the father 'destroys' the sems */ 50 | sem_unlink(SEM_NAME_1); 51 | sem_unlink(SEM_NAME_2); 52 | } 53 | 54 | } -------------------------------------------------------------------------------- /MQL5_PYTHON/INDEX_BOT/index_client.mq5: -------------------------------------------------------------------------------- 1 | #define PORT 8676 2 | #define ADDR "localhost" 3 | #define MAX_BUFF_LEN 1024 4 | #define TIMEOUT 10000 5 | 6 | /* Socket variables */ 7 | int socket; // Socket handle 8 | 9 | /* Candle variables */ 10 | MqlRates candles[]; 11 | 12 | 13 | void OnInit() { 14 | ArraySetAsSeries(candles, true); 15 | 16 | // Initializing the socket 17 | socket = SocketCreate(); 18 | if (socket == INVALID_HANDLE) Print("Error - 1: SocketCreate failure. ", GetLastError()); 19 | else { 20 | if (SocketConnect(socket, ADDR, PORT, TIMEOUT)) Print("[INFO]\tConnection stablished"); 21 | else Print("Error - 2: SocketConnect failure. ", GetLastError()); 22 | } 23 | } 24 | 25 | 26 | void OnDeinit(const int reason) { 27 | /* Closing the socket */ 28 | // Creating the message 29 | char req[]; 30 | 31 | Print("[INFO]\tClosing the socket."); 32 | 33 | int len = StringToCharArray("END CONNECTION\0", req)-1; 34 | SocketSend(socket, req, len); 35 | SocketClose(socket); 36 | } 37 | 38 | 39 | void OnTick() { 40 | // Loading the candles values 41 | CopyRates(_Symbol, _Period, 0, 2, candles); 42 | 43 | // Sending RSI data 44 | Print("[INFO]\tSending Candles"); 45 | string msg; 46 | StringConcatenate(msg, "{\"0\": [", candles[0].close, ", ", candles[0].open, "], " 47 | "\"1\": [", candles[1].close, ", ", candles[1].open, "]}"); 48 | 49 | char req[]; 50 | int len = StringToCharArray(msg, req)-1; 51 | SocketSend(socket, req, len); 52 | } -------------------------------------------------------------------------------- /tutoriales/C/sockets/server.c: -------------------------------------------------------------------------------- 1 | /* SOCKETS */ 2 | #include 3 | #include 4 | 5 | /* Descriptor functions (read and close) */ 6 | #include 7 | 8 | /* Classic tyvole */ 9 | #include 10 | #include 11 | 12 | /* For htons */ 13 | #include // man inet 14 | 15 | void main() { 16 | int server_descriptor = 0, client_descriptor = 0; 17 | 18 | struct sockaddr_in address; 19 | address.sin_family = AF_INET; // SOCKET IS FOR IPv4 20 | address.sin_addr.s_addr = INADDR_ANY; 21 | address.sin_port = htons( 5001 ); // CREDITS FOR RODRI!! HE FOUND THIS FUNCTION 22 | 23 | printf("I'm the server, my address is: %d\n", address.sin_addr.s_addr); 24 | 25 | /* Creating one TCP socket, IPv4 TCP */ 26 | server_descriptor = socket(AF_INET, SOCK_STREAM, 0); 27 | 28 | /* Binding a name to a socket */ 29 | bind(server_descriptor, (struct sockaddr *)&address, sizeof(address)); 30 | 31 | /* Listening for connections on the socket */ 32 | listen(server_descriptor, 5); 33 | 34 | /* SOCKET SET FINISHED */ 35 | /* ACCEPTING CONNECTIONs */ 36 | printf("I'm the server and I'm ready to receive connections :-)\n"); 37 | printf("I'm going to wait for a connection\n"); 38 | 39 | client_descriptor = accept(server_descriptor, NULL, NULL); 40 | 41 | printf("Someone connected, I'm looking for a message\n"); 42 | 43 | char msg[100] = ""; 44 | 45 | read(client_descriptor, msg, 100); 46 | printf("This is what I received: %s\n", msg); 47 | 48 | close(server_descriptor); 49 | } -------------------------------------------------------------------------------- /MQL5_PYTHON/RSI_BOT/RSI_client.mq5: -------------------------------------------------------------------------------- 1 | #define PORT 8688 2 | #define ADDR "localhost" 3 | #define MAX_BUFF_LEN 1024 4 | #define TIMEOUT 10000 5 | 6 | /* Socket variables */ 7 | int socket; // Socket handle 8 | 9 | /* RSI variables */ 10 | int rsi_h; // RSI handle 11 | double rsi[]; // RSI array 12 | 13 | 14 | void OnInit() { 15 | rsi_h = iRSI(_Symbol, _Period, 14, PRICE_CLOSE); 16 | if (rsi_h == INVALID_HANDLE) Print("Error - 3: iRSI failure. ", GetLastError()); 17 | 18 | // Initializing the socket 19 | socket = SocketCreate(); 20 | if (socket == INVALID_HANDLE) Print("Error - 1: SocketCreate failure. ", GetLastError()); 21 | else { 22 | if (SocketConnect(socket, ADDR, PORT, TIMEOUT)) Print("[INFO]\tConnection stablished"); 23 | else Print("Error - 2: SocketConnect failure. ", GetLastError()); 24 | } 25 | } 26 | 27 | 28 | void OnDeinit(const int reason) { 29 | /* Closing the socket */ 30 | // Creating the message 31 | char req[]; 32 | 33 | Print("[INFO]\tClosing the socket."); 34 | 35 | int len = StringToCharArray("END CONNECTION\0", req)-1; 36 | SocketSend(socket, req, len); 37 | SocketClose(socket); 38 | } 39 | 40 | 41 | void OnTick() { 42 | // Loading the macd values 43 | CopyBuffer(rsi_h, 0, 0, 2, rsi); 44 | 45 | // Sending RSI data 46 | Print("[INFO]\tSending RSI"); 47 | string msg; 48 | StringConcatenate(msg, rsi[0], ",", rsi[1]); 49 | 50 | char req[]; 51 | int len = StringToCharArray(msg, req)-1; 52 | SocketSend(socket, req, len); 53 | } -------------------------------------------------------------------------------- /mql5/MAs.mq5: -------------------------------------------------------------------------------- 1 | #include 2 | CTrade trade; 3 | 4 | /* Moving average handlers */ 5 | int ma_15_h = 0; 6 | int ma_9_h = 0; 7 | 8 | ulong trade_ticket = 0; 9 | bool time_passed = true; 10 | 11 | double ma_15_array[]; 12 | double ma_9_array[]; 13 | 14 | int OnInit() { 15 | 16 | ma_15_h = iMA(_Symbol, _Period, 15, 0, MODE_SMA, PRICE_CLOSE); 17 | ma_9_h = iMA(_Symbol, _Period, 9, 0, MODE_SMA, PRICE_CLOSE); 18 | 19 | return(INIT_SUCCEEDED); 20 | } 21 | 22 | 23 | 24 | void OnTick() { 25 | CopyBuffer(ma_15_h, 0, 1, 3, ma_15_array); 26 | CopyBuffer(ma_9_h, 0, 1, 3, ma_9_array); 27 | 28 | if (PositionSelectByTicket(trade_ticket) == false) { 29 | trade_ticket = false; 30 | } 31 | 32 | if (trade_ticket <= 0 && ma_9_array[1] > ma_15_array[1] && ma_9_array[0] < ma_15_array[0] && time_passed == true) { 33 | double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK), _Digits); 34 | 35 | trade.Buy(0.01, _Symbol, Ask, Ask-20*_Point, Ask+60*_Point, NULL); 36 | trade_ticket = trade.ResultOrder(); 37 | time_passed = false; 38 | 39 | EventSetTimer(60*30*5); 40 | } else if (trade_ticket <= 0 && ma_9_array[1] < ma_15_array[1] && ma_9_array[0] > ma_15_array[0] && time_passed == true) { 41 | double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits); 42 | 43 | trade.Sell(0.01, _Symbol, Bid, Bid+20*_Point, Bid-60*_Point, NULL); 44 | trade_ticket = trade.ResultOrder(); 45 | time_passed = false; 46 | 47 | EventSetTimer(60*30*5); 48 | } 49 | } 50 | 51 | void OnTimer() { 52 | time_passed = true; 53 | } -------------------------------------------------------------------------------- /mql5/trailing_stops_several_positions.mq5: -------------------------------------------------------------------------------- 1 | #define TOP_RSI_LEVEL 55 2 | #define SL 5000*_Point 3 | #define TP SL*3 4 | 5 | #define MARGIN_SL 2000*_Point 6 | 7 | /* For openning operations */ 8 | #include 9 | CTrade trade; 10 | bool time_flag = true; 11 | 12 | /* Array of candles */ 13 | MqlRates candles[]; 14 | 15 | /* For the rsi */ 16 | int rsi_h; 17 | double rsi[]; 18 | 19 | bool is_rsi_above_top() { return rsi[0] > TOP_RSI_LEVEL; } 20 | 21 | void trailing_stop(ulong ticket) { 22 | double cur_sl = PositionGetDouble(POSITION_SL); 23 | double cur_price = candles[0].close; 24 | 25 | if (cur_sl - MARGIN_SL > cur_price) 26 | trade.PositionModify(ticket, cur_price+MARGIN_SL, 0); 27 | } 28 | 29 | void trailing_stop_all() { 30 | for(int i = 0; i < PositionsTotal(); i++) { 31 | ulong ticket = PositionGetTicket(i); 32 | PositionGetSymbol(i); 33 | PositionSelectByTicket(ticket); 34 | 35 | trailing_stop(ticket); 36 | } 37 | } 38 | 39 | void OnInit() { 40 | rsi_h = iRSI(_Symbol, _Period, 14, PRICE_CLOSE); 41 | 42 | ArraySetAsSeries(candles, true); 43 | } 44 | 45 | void OnTick() { 46 | CopyRates(_Symbol, _Period, 0, 3, candles); 47 | CopyBuffer(rsi_h, 0, 1, 3, rsi); 48 | 49 | trailing_stop_all(); 50 | 51 | if (is_rsi_above_top() && time_flag) { 52 | 53 | double bid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits); 54 | 55 | trade.Sell(0.1, _Symbol, bid, bid+SL); 56 | 57 | time_flag = false; 58 | EventSetTimer(PeriodSeconds()); 59 | } 60 | } 61 | 62 | void OnTimer() { 63 | time_flag = true; 64 | EventKillTimer(); 65 | } 66 | -------------------------------------------------------------------------------- /NodeJS/Notes-app/helpers/inquirer.js: -------------------------------------------------------------------------------- 1 | const inquirer = require('inquirer'); 2 | 3 | const { read, write } = require('./file'); 4 | 5 | const options = [ 6 | { 7 | type: 'list', 8 | name: 'option', 9 | message: 'What do you want to do?', 10 | choices: [ 11 | { 12 | value: 1, 13 | name: 'Add a new note' 14 | }, { 15 | value: 2, 16 | name: 'Delete a note' 17 | }, { 18 | value: 3, 19 | name: 'Exit' 20 | } 21 | ] 22 | } 23 | ] 24 | 25 | 26 | const iMenu = async() => { 27 | console.clear(); 28 | 29 | const { option } = await inquirer.prompt(options); 30 | 31 | return option; 32 | } 33 | 34 | const readInput = async(msg) => { 35 | const question = [ 36 | { 37 | type: 'input', 38 | name: 'input', 39 | message: msg 40 | } 41 | ]; 42 | 43 | const { input } = await inquirer.prompt(question); 44 | return input; 45 | } 46 | 47 | const addNote = async(notes) => { 48 | console.clear() 49 | 50 | const title = await readInput('Title: '); 51 | const text = await readInput('Text: '); 52 | 53 | notes[title] = text; 54 | 55 | write(notes); 56 | } 57 | 58 | const delNote = async(notes) => { 59 | console.clear() 60 | 61 | const title = await readInput('Title: '); 62 | 63 | if (notes[title]) { 64 | delete notes[title] 65 | write(notes); 66 | } else await readInput(`The note ${title} doesn't exist\nPRESS ENTER: `); 67 | } 68 | 69 | 70 | module.exports = { iMenu, addNote, delNote } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Trading_BOT 2 | 3 | __ENG__: This is the repository for the code I use in my youtube channel! 4 | * **Python trading bot**: This folder is the one developed in the (Python trading bot playlist). 5 | * **Python trading bot/src/**: This folder contains the first bot I created in our channel (Python trading bot playlist). 6 | * **Python trading bot/backtesting/**: This folder contains the code for backtesting data using the bot strategy. 7 | * **mql5**: In this folder there's the code for the MQL5 different bots I have created. 8 | * **ta**: This folder contains bots using the _ta_ library, the **to_candle** file to load candles, and notebooks where you will see how to load different indicators in python. 9 | * **tutoriales**: This folders contains the code I use in my different tutorials of programming languages. 10 | 11 | __ESP__: ¡Este es el repositorio para el código que uso en mi canal! 12 | * **Python trading bot**: Esta es la carpeta donde desarrollamos el bot de python (Bot de trading playlist). 13 | * **Python trading bot/src/**: Esta carpeta contiene el primer bot que creé en nuestro canal (Bot de trading playlist). 14 | * **Python trading bot/backtesting/**: Esta carpeta contiene el código para hacer backtesting de datos usando la estrategia del bot. 15 | * **mql5**: En esta carpeta está el código para los diferentes bots que hemos hecho en MQL5. 16 | * **ta**: Esta carpeta contiene bots usando la librería _ta_, el archivo **to_candle** para cargar velas, y el notebooks donde se puede ver como cargar los diferentes indicadores en python. 17 | * **tutoriales**: Esta carpeta contiene el código que uso en mis diferentes tutoriales de programación. 18 | 19 | https://www.youtube.com/channel/UCWpGnaeyh0nmB-ltvp6FxIg 20 | -------------------------------------------------------------------------------- /MQL5_PYTHON/MACD_BOT/macd_client.mq5: -------------------------------------------------------------------------------- 1 | /* Socket variables */ 2 | string address = "localhost"; 3 | int port = 8686; 4 | int socket; // Socket handle 5 | int MAX_BUFF_LEN = 1024; // Max size for reading in the buffer 6 | 7 | /* MACD variables */ 8 | int macd_h; // MACD handle 9 | double macd[]; 10 | double signal[]; 11 | 12 | 13 | void OnInit() { 14 | macd_h = iMACD(_Symbol, _Period, 12, 26, 9, PRICE_CLOSE); 15 | if (macd_h == INVALID_HANDLE) Print("Error - 3: iMACD failure. ", GetLastError()); 16 | 17 | // Initializing the socket 18 | socket = SocketCreate(); 19 | if (socket == INVALID_HANDLE) Print("Error - 1: SocketCreate failure. ", GetLastError()); 20 | else { 21 | if (SocketConnect(socket, address, port, 10000)) Print("[INFO]\tConnection stablished"); 22 | else Print("Error - 2: SocketConnect failure. ", GetLastError()); 23 | } 24 | } 25 | 26 | 27 | void OnDeinit(const int reason) { 28 | /* Closing the socket */ 29 | // Creating the message 30 | char req[]; 31 | 32 | Print("[INFO]\tClosing the socket."); 33 | 34 | int len = StringToCharArray("END CONNECTION\0", req)-1; 35 | SocketSend(socket, req, len); 36 | SocketClose(socket); 37 | } 38 | 39 | 40 | void OnTick() { 41 | // Loading the macd values 42 | CopyBuffer(macd_h, MAIN_LINE, 0, 2, macd); 43 | CopyBuffer(macd_h, SIGNAL_LINE, 0, 2, signal); 44 | 45 | // Sending MACD data 46 | Print("[INFO]\tSending MACD and SIGNAL"); 47 | string msg; 48 | StringConcatenate(msg, macd[0], ",", macd[1], "|", signal[0], ",", signal[1]); 49 | 50 | char req[]; 51 | int len = StringToCharArray(msg, req)-1; 52 | SocketSend(socket, req, len); 53 | } -------------------------------------------------------------------------------- /ta/RSI/BOT/RSI.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | from to_candle import from_list_to_df, Candle 3 | from ta.momentum import RSIIndicator 4 | import time 5 | import datetime 6 | 7 | def thread_rsi(pill2kill, data: dict, time_period: int): 8 | """Function executed by a thread that loads the rsi values. 9 | 10 | Args: 11 | pill2kill (Threading.Event): Event to stop the execution of the thread. 12 | data (dict): Dictionary with the data of the bot. Here we store the candles. 13 | (Only 2 are stored, the last one and the previous one) 14 | time_period (int): Time period of the bot. 15 | """ 16 | # Waiting until the candle thread loads data 17 | print('[Thread RSI] - Waiting for candles...') 18 | while not data["candles_ready"]: 19 | time.sleep(1) 20 | 21 | # Indicator object 22 | candle_df = from_list_to_df(data["candles"]) 23 | rsi_object = RSIIndicator(candle_df["CLOSE"], window=14, fillna=True) 24 | rsi_series = rsi_object.rsi() 25 | data["RSI"] = [rsi_series.iloc[-2], rsi_series.iloc[-3]] 26 | data["rsi_ready"] = True 27 | 28 | # For sinchronizing 29 | print("[Thread RSI] - Sinchronizing...") 30 | ep = datetime.datetime(1970,1,1,0,0,0) 31 | time_sec = 1 32 | while time_sec % time_period != 0 and not pill2kill.wait(0.5): 33 | time.sleep(0.1) 34 | time_sec = int((datetime.datetime.utcnow()- ep).total_seconds()) 35 | 36 | print('[Thread RSI] - Loading RSI...') 37 | while not pill2kill.wait(time_period): 38 | candle_df = from_list_to_df(data["candles"]) 39 | 40 | # Indicator object 41 | rsi_object = RSIIndicator(candle_df["CLOSE"], window=14, fillna=True) 42 | rsi_series = rsi_object.rsi() 43 | data["RSI"] = [rsi_series.iloc[-2], rsi_series.iloc[-3]] 44 | 45 | -------------------------------------------------------------------------------- /Django_tutorial/tutorial/catalog/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from django.template.defaultfilters import slugify 3 | from django.urls import reverse 4 | 5 | 6 | class Actor(models.Model): 7 | name = models.CharField(max_length=100) 8 | age = models.IntegerField() 9 | slug = models.SlugField(null=True, blank=True) 10 | 11 | class Meta: 12 | ordering = ['age', 'name'] 13 | 14 | def save(self, *args, **kwargs): 15 | self.slug = slugify(self.name+" "+str(self.age)) 16 | return super().save(*args, **kwargs) 17 | 18 | def __str__(self): 19 | return "Name: "+self.name+", Age: "+str(self.age) 20 | 21 | def display_films(self): 22 | return ', '.join(str(film) for film in Film.objects.filter(actor=self)) 23 | 24 | def get_films(self): 25 | return Film.objects.filter(actor=self) 26 | 27 | 28 | 29 | class Film(models.Model): 30 | title = models.CharField(max_length=100) 31 | price = models.DecimalField(decimal_places=2, max_digits=4) 32 | score = models.DecimalField(decimal_places=2, max_digits=4) 33 | slug = models.SlugField(null=True, blank=True) 34 | actor = models.ManyToManyField(Actor) 35 | 36 | class Meta: 37 | ordering = ['score', 'price', 'title'] 38 | 39 | def save(self, *args, **kwargs): 40 | self.slug = slugify(self.title) 41 | return super().save(*args, **kwargs) 42 | 43 | def __str__(self): 44 | return self.title 45 | 46 | def display_actors(self): 47 | return ' | '.join(str(actor) for actor in self.actor.all()) 48 | 49 | def set_score(self, score): 50 | self.score = score 51 | self.save() 52 | 53 | def get_absolute_url(self): 54 | return reverse('film', kwargs={'slug': self.slug}) 55 | 56 | 57 | class Comment(models.Model): 58 | text = models.CharField(max_length=1000) 59 | film = models.ForeignKey(Film, on_delete=models.SET_NULL, null=True, blank=True) 60 | 61 | def __str__(self): 62 | return "Comment: "+self.text -------------------------------------------------------------------------------- /tutoriales/Pandas/pandas_example.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | dataframe = pd.read_csv("data.csv") 4 | 5 | # Checking the data 6 | print(dataframe.head(5)) 7 | 8 | # Getting the shape of the data 9 | print("\nData shape (rows, columns):", dataframe.shape) 10 | 11 | column_types = [] 12 | 13 | # Iterating through types 14 | for type in dataframe.dtypes: 15 | column_types.append(type) 16 | 17 | print("\nDataframe types:", column_types, "\n") 18 | 19 | # Iterating through columns 20 | for i, col in enumerate(dataframe.iteritems()): 21 | column_name = col[0] 22 | print("Column "+str(i+1)+": "+column_name, end=" ") 23 | 24 | # Getting the unique values of each column 25 | column_unique_values = list(dataframe[column_name].unique()).copy() 26 | print("- Unique values:", column_unique_values, end=" ") 27 | 28 | column_unique_values.sort() 29 | print("- sorted ->", column_unique_values) 30 | 31 | # Iterating through rows 32 | for i, row in enumerate(dataframe.iterrows()): 33 | print("\nRow "+str(i)+": "+str(row)) 34 | 35 | # Iterating through columns in the row 36 | for j, col in enumerate(row[1].items()): 37 | print(str(j)+": "+str(col), end=" | ") 38 | 39 | # Adding rows 40 | dataframe = dataframe.append({'C1': 'y', 'C3': 'x', 'C4': 0.5}, ignore_index=True) 41 | print(dataframe.tail(5)) 42 | 43 | # Editing rows 44 | dataframe.at[9, 'C2'] = 12 45 | dataframe.at[9, 'C5'] = 'z' 46 | dataframe.at[9, 'Class'] = 'D' 47 | print("\n", dataframe.tail(5)) 48 | 49 | # Deleting rows 50 | dataframe = dataframe.drop([0, 1]) 51 | print("\n", dataframe.head(5)) 52 | 53 | # Add column 54 | dataframe.insert(1, "New col", [1,2,3,4,5,6,7,8]) 55 | print("\n", dataframe.head(5)) 56 | 57 | # New empty column 58 | import numpy as np 59 | dataframe["empty col"] = np.nan 60 | 61 | # Delete a column 62 | dataframe = dataframe.drop(columns="New col") 63 | print("\n", dataframe.head(5)) 64 | 65 | -------------------------------------------------------------------------------- /mql5/CloseOnCross.mq5: -------------------------------------------------------------------------------- 1 | #include 2 | CTrade trade; 3 | ulong trade_ticket; 4 | 5 | 6 | int ema_fast_h; 7 | int ema_slow_h; 8 | 9 | double ema_fast[]; 10 | double ema_slow[]; 11 | 12 | 13 | bool cruce_compra() { 14 | return ema_fast[1] < ema_slow[1] && ema_fast[0] > ema_slow[0]; 15 | } 16 | 17 | bool cruce_venta() { 18 | return ema_fast[1] > ema_slow[1] && ema_fast[0] < ema_slow[0]; 19 | } 20 | 21 | 22 | int bars; 23 | bool nueva_vela() { 24 | int current_bars = Bars(_Symbol, _Period); 25 | if (current_bars != bars) { 26 | bars = current_bars; 27 | return true; 28 | } 29 | 30 | return false; 31 | } 32 | 33 | bool operacion_cerrada() { 34 | return !PositionSelectByTicket(trade_ticket); 35 | } 36 | 37 | 38 | int OnInit() { 39 | ema_fast_h = iMA(_Symbol, _Period, 15, 0, MODE_EMA, PRICE_CLOSE); 40 | ema_slow_h = iMA(_Symbol, _Period, 100, 0, MODE_EMA, PRICE_CLOSE); 41 | 42 | if (ema_fast_h == INVALID_HANDLE || ema_slow_h == INVALID_HANDLE) { 43 | Print("Error loading the indicators"); 44 | return INIT_FAILED; 45 | } 46 | 47 | ArraySetAsSeries(ema_fast, true); 48 | ArraySetAsSeries(ema_slow, true); 49 | 50 | return INIT_SUCCEEDED; 51 | } 52 | 53 | void OnDeinit(const int reason) { 54 | if (ema_fast_h != INVALID_HANDLE) IndicatorRelease(ema_fast_h); 55 | if (ema_slow_h != INVALID_HANDLE) IndicatorRelease(ema_slow_h); 56 | } 57 | 58 | void OnTick() { 59 | CopyBuffer(ema_fast_h, 0, 1, 2, ema_fast); 60 | CopyBuffer(ema_slow_h, 0, 1, 2, ema_slow); 61 | 62 | if (operacion_cerrada()) { 63 | if (cruce_compra()) { 64 | trade.Buy(0.01); 65 | trade_ticket = trade.ResultOrder(); 66 | } else if (cruce_venta()) { 67 | trade.Sell(0.01); 68 | trade_ticket = trade.ResultOrder(); 69 | } 70 | } else if (nueva_vela()) { 71 | if (cruce_compra() || cruce_venta()) 72 | trade.PositionClose(trade_ticket); 73 | } 74 | } -------------------------------------------------------------------------------- /tutoriales/C/Semaphores/unnamed.c: -------------------------------------------------------------------------------- 1 | /* FOR SEMAPHORE */ 2 | #include 3 | 4 | /* SHARED MEMORY */ 5 | #include 6 | #include /* For mode constants */ 7 | #include /* For O_* constants */ 8 | 9 | #include 10 | #include 11 | 12 | /* FOR FORK */ 13 | #include 14 | #include 15 | 16 | /* FOR KILLING THE CHILD PROCESS */ 17 | #include 18 | 19 | #define SHM_SEMS "sems_shared_memory" 20 | 21 | typedef struct { 22 | sem_t sem1; 23 | sem_t sem2; 24 | } Sems; 25 | 26 | void main() { 27 | 28 | /* Opening the shared memory */ 29 | int fd_shm = shm_open(SHM_SEMS, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); 30 | 31 | ftruncate(fd_shm, sizeof(Sems)); 32 | 33 | Sems *sems = mmap(NULL, sizeof(Sems), PROT_READ | PROT_WRITE, MAP_SHARED, fd_shm, 0); 34 | 35 | // 1 to share between processes Initial value of the sem 36 | sem_init(&sems->sem1, 1, 0); 37 | sem_init(&sems->sem2, 1, 0); 38 | 39 | if (fork() == 0) { // child 40 | printf("1\n"); 41 | sem_post(&sems->sem1); 42 | sem_wait(&sems->sem2); 43 | printf("3\n"); 44 | sem_post(&sems->sem1); 45 | 46 | /* Unmapping the sems */ 47 | munmap(sems, sizeof(Sems)); 48 | 49 | } else { // father 50 | sem_wait(&sems->sem1); 51 | printf("2\n"); 52 | sem_post(&sems->sem2); 53 | sem_wait(&sems->sem1); 54 | printf("4\n"); 55 | 56 | wait(NULL); 57 | 58 | /* Only the father destroys the sems */ 59 | sem_destroy(&sems->sem1); 60 | sem_destroy(&sems->sem2); 61 | 62 | /* Unmapping the sems */ 63 | munmap(sems, sizeof(Sems)); 64 | 65 | /* Destroying the shared memory (only the father) */ 66 | shm_unlink(SHM_SEMS); 67 | } 68 | } -------------------------------------------------------------------------------- /Django_tutorial/tutorial/catalog/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.6 on 2021-12-26 09:53 2 | 3 | from django.db import migrations, models 4 | import django.db.models.deletion 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | initial = True 10 | 11 | dependencies = [ 12 | ] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name='Actor', 17 | fields=[ 18 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 19 | ('name', models.CharField(max_length=100)), 20 | ('age', models.IntegerField()), 21 | ('slug', models.SlugField(blank=True, null=True)), 22 | ], 23 | options={ 24 | 'ordering': ['age', 'name'], 25 | }, 26 | ), 27 | migrations.CreateModel( 28 | name='Film', 29 | fields=[ 30 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 31 | ('title', models.CharField(max_length=100)), 32 | ('price', models.DecimalField(decimal_places=2, max_digits=4)), 33 | ('score', models.DecimalField(decimal_places=2, max_digits=4)), 34 | ('slug', models.SlugField(blank=True, null=True)), 35 | ('actor', models.ManyToManyField(to='catalog.Actor')), 36 | ], 37 | options={ 38 | 'ordering': ['score', 'price', 'title'], 39 | }, 40 | ), 41 | migrations.CreateModel( 42 | name='Comment', 43 | fields=[ 44 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 45 | ('text', models.CharField(max_length=1000)), 46 | ('film', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='catalog.film')), 47 | ], 48 | ), 49 | ] 50 | -------------------------------------------------------------------------------- /mql5/VolatilityIndexBot.mq5: -------------------------------------------------------------------------------- 1 | #include 2 | CTrade trade; 3 | ulong trade_ticket; 4 | 5 | 6 | int ema_fast_h; 7 | int ema_slow_h; 8 | 9 | double ema_fast[]; 10 | double ema_slow[]; 11 | 12 | 13 | bool buy_cross() { 14 | return ema_slow[1] > ema_fast[1] && ema_slow[0] < ema_fast[0]; 15 | } 16 | 17 | bool sell_cross() { 18 | return ema_slow[1] < ema_fast[1] && ema_slow[0] > ema_fast[0]; 19 | } 20 | 21 | int bars; 22 | bool new_candle() { 23 | int current_bars = Bars(_Symbol, _Period); 24 | if (current_bars != bars) { 25 | bars = current_bars; 26 | return true; 27 | } 28 | 29 | return false; 30 | } 31 | 32 | bool operation_closed() { 33 | return !PositionSelectByTicket(trade_ticket); 34 | } 35 | 36 | 37 | int OnInit() { 38 | ema_fast_h = iMA(_Symbol, _Period, 14, 0, MODE_EMA, PRICE_CLOSE); 39 | ema_slow_h = iMA(_Symbol, _Period, 100, 0, MODE_EMA, PRICE_CLOSE); 40 | if (ema_fast_h == INVALID_HANDLE ||ema_slow_h == INVALID_HANDLE) { 41 | Print("[ERROR] - Indicators not loaded"); 42 | return INIT_FAILED; 43 | } 44 | 45 | ArraySetAsSeries(ema_fast, true); 46 | ArraySetAsSeries(ema_slow, true); 47 | 48 | return INIT_SUCCEEDED; 49 | } 50 | 51 | void OnDeinit(const int reason) { 52 | if (ema_fast_h != INVALID_HANDLE) IndicatorRelease(ema_fast_h); 53 | if (ema_slow_h != INVALID_HANDLE) IndicatorRelease(ema_slow_h); 54 | } 55 | 56 | void OnTick() { 57 | CopyBuffer(ema_fast_h, 0, 1, 2, ema_fast); 58 | CopyBuffer(ema_slow_h, 0, 1, 2, ema_slow); 59 | 60 | if (buy_cross() && new_candle() && operation_closed()) { 61 | double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK), _Digits); 62 | 63 | trade.Buy(1, _Symbol, Ask, Ask-50*_Point, Ask+120*_Point); 64 | trade_ticket = trade.ResultOrder(); 65 | } else if (sell_cross() && new_candle() && operation_closed()) { 66 | double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits); 67 | 68 | trade.Sell(1, _Symbol, Bid, Bid+50*_Point, Bid-120*_Point); 69 | trade_ticket = trade.ResultOrder(); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /mql5/MACD.mq5: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* Handler */ 4 | int MACD_h; 5 | 6 | /* Arrays where the indicator data is stored */ 7 | double MACD[]; 8 | double SIGNAL[]; 9 | 10 | /* For openning operations */ 11 | CTrade trade; 12 | ulong trade_ticket = 0; 13 | bool time_passed = true; 14 | 15 | 16 | int OnInit() { 17 | /* Initializing the handlers */ 18 | MACD_h = iMACD(_Symbol, _Period, 12, 26, 9, PRICE_CLOSE); 19 | 20 | ArraySetAsSeries(MACD, true); 21 | ArraySetAsSeries(SIGNAL, true); 22 | 23 | return(INIT_SUCCEEDED); 24 | } 25 | 26 | void OnTick() { 27 | /* Saving the data of the indicator */ 28 | CopyBuffer(MACD_h, 0, 1, 4, MACD); 29 | CopyBuffer(MACD_h, 1, 1, 4, SIGNAL); 30 | 31 | /* Checking if there's an open operation */ 32 | if (PositionSelectByTicket(trade_ticket) == false) { 33 | // Reseting the trade flags 34 | trade_ticket = 0; 35 | } 36 | 37 | 38 | if ( // Buy 39 | MACD[1] < SIGNAL[1] && MACD[0] > SIGNAL[0] // Cross 40 | && MACD[0] < -0.0002 41 | && trade_ticket <= 0 && time_passed == true 42 | ) { 43 | /* Precio actual */ 44 | double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK), _Digits); 45 | 46 | //--- Abrir compra 47 | trade.Buy(0.1, _Symbol, Ask, Ask-40*_Point, Ask+50*_Point, NULL); 48 | trade_ticket = trade.ResultOrder(); 49 | 50 | time_passed = false; 51 | 52 | EventSetTimer(PeriodSeconds(PERIOD_CURRENT)*3); 53 | 54 | } else if ( // venta 55 | MACD[1] > SIGNAL[1] && MACD[0] < SIGNAL[0] // Cross 56 | && MACD[0] > 0.0002 57 | && trade_ticket <= 0 && time_passed == true 58 | ) { 59 | /* Precio actual */ 60 | double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits); 61 | 62 | //--- Abrir venta 63 | trade.Sell(0.1, _Symbol, Bid, Bid+40*_Point, Bid-50*_Point, NULL); 64 | trade_ticket = trade.ResultOrder(); 65 | 66 | time_passed = false; 67 | 68 | EventSetTimer(PeriodSeconds(PERIOD_CURRENT)*3); 69 | } 70 | } 71 | 72 | void OnTimer() { 73 | time_passed = true; 74 | } -------------------------------------------------------------------------------- /MQL5_PYTHON/RSI_BOT/bot.py: -------------------------------------------------------------------------------- 1 | import MetaTrader5 as mt5 2 | import RSI, threading, orders 3 | 4 | class Bot: 5 | 6 | def __init__(self, lotage: float, time_period: int, market: str): 7 | """Constructor of the bot. It justs fills the needed informartion for the bot. 8 | 9 | Args: 10 | lotage (float): Lotage to be used by the bot. 11 | time_period (int): Time period of the bot, 1 minute, 15 minutes... (in seconds) 12 | market (str): Market to operate in. 13 | """ 14 | self.threads = [] 15 | self.data = {'RSI': None} 16 | self.pill2kill = threading.Event() 17 | self.trading_data = {} 18 | self.trading_data['lotage'] = lotage 19 | self.trading_data['time_period'] = time_period 20 | self.trading_data['market'] = market 21 | 22 | def thread_rsi(self): 23 | """Function to launch the data thread.""" 24 | t = threading.Thread(target=RSI.thread_rsi, 25 | args=(self.pill2kill, self.data)) 26 | self.threads.append(t) 27 | t.start() 28 | print('Thread - DATA. LAUNCHED') 29 | 30 | def thread_orders(self): 31 | """Function to launch the thread for sending orders.""" 32 | t = threading.Thread(target=orders.thread_orders, 33 | args=(self.pill2kill, self.data, self.trading_data)) 34 | self.threads.append(t) 35 | t.start() 36 | print('Thread - ORDERS. LAUNCHED') 37 | 38 | def kill_threads(self): 39 | """Function to kill all the loaded threads.""" 40 | print('Threads - Stopping threads') 41 | self.pill2kill.set() 42 | for thread in self.threads: 43 | thread.join() 44 | 45 | def start(self): 46 | """Function to start all the threads""" 47 | self.thread_rsi() 48 | self.thread_orders() 49 | 50 | def wait(self): 51 | """Function to make the thread wait.""" 52 | # Input para detener a los hilos 53 | print('\nPress ENTER to stop the bot\n') 54 | input() 55 | self.kill_threads() 56 | mt5.shutdown() -------------------------------------------------------------------------------- /mql5/volatility_index.mq5: -------------------------------------------------------------------------------- 1 | #include 2 | CTrade trade; 3 | 4 | 5 | input int UMBRAL_PUNTOS = 10; // Umbral de puntos a superar 6 | input int RITMO = 1; // Cada cuantos segundos comprobamos el precio 7 | input int TP = 30; // Puntos hasta el TP 8 | input int SL = 30; // Puntos hasta el SL 9 | input int DISTANCIA_TS = 15; // Puntos entre el precio y el trailing stop 10 | 11 | 12 | // Variables para guardar los precios a comparar 13 | double precioAnterior = 0; 14 | double precioActual = 0; 15 | 16 | // Array donde guardar los closes 17 | double closes[]; 18 | 19 | 20 | void trailing_stop() { 21 | for (int i = 0; i < PositionsTotal(); i++) { 22 | ulong ticket = PositionGetTicket(i); 23 | PositionSelectByTicket(ticket); 24 | 25 | double sl_anterior = PositionGetDouble(POSITION_SL); 26 | double tp = PositionGetDouble(POSITION_TP); 27 | double current_price = PositionGetDouble(POSITION_PRICE_CURRENT); 28 | if (current_price > sl_anterior+DISTANCIA_TS*_Point) { 29 | trade.PositionModify(ticket, current_price-DISTANCIA_TS*_Point, tp); 30 | } 31 | } 32 | } 33 | 34 | 35 | void OnInit() { 36 | // Inicializamos el array 37 | ArraySetAsSeries(closes, true); 38 | 39 | // Inicializamos los precios 40 | CopyClose(_Symbol, _Period, 0, 1, closes); 41 | precioActual = closes[0]; 42 | precioAnterior = precioActual; 43 | 44 | // Inicializamos el temporizador 45 | EventSetTimer(RITMO); 46 | } 47 | 48 | void OnTick() { 49 | trailing_stop(); 50 | } 51 | 52 | void OnTimer() { 53 | // Actualizamos los precios 54 | CopyClose(_Symbol, _Period, 0, 1, closes); 55 | precioAnterior = precioActual; 56 | precioActual = closes[0]; 57 | 58 | // Guardamos cuanto se ha movido el precio en puntos 59 | double movimiento = (precioActual - precioAnterior)/_Point; 60 | 61 | // Si el precio se ha movido por encima del umbral abrimos una compra 62 | if (movimiento > UMBRAL_PUNTOS) { 63 | double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK), _Digits); 64 | trade.Buy(0.1, _Symbol, Ask, Ask-SL*_Point, Ask+TP*_Point); 65 | } 66 | } -------------------------------------------------------------------------------- /MQL5_PYTHON/MACD_BOT/bot.py: -------------------------------------------------------------------------------- 1 | import MetaTrader5 as mt5 2 | import MACD, threading, orders 3 | 4 | class Bot: 5 | 6 | def __init__(self, lotage: float, time_period: int, market: str): 7 | """Constructor of the bot. It justs fills the needed informartion for the bot. 8 | 9 | Args: 10 | lotage (float): Lotage to be used by the bot. 11 | time_period (int): Time period of the bot, 1 minute, 15 minutes... (in seconds) 12 | market (str): Market to operate in. 13 | """ 14 | self.threads = [] 15 | self.data = {'MACD': None, 'SIGNAL': None} 16 | self.pill2kill = threading.Event() 17 | self.trading_data = {} 18 | self.trading_data['lotage'] = lotage 19 | self.trading_data['time_period'] = time_period 20 | self.trading_data['market'] = market 21 | 22 | def thread_macd(self): 23 | """Function to launch the data thread.""" 24 | t = threading.Thread(target=MACD.thread_macd, 25 | args=(self.pill2kill, self.data)) 26 | self.threads.append(t) 27 | t.start() 28 | print('Thread - DATA. LAUNCHED') 29 | 30 | def thread_orders(self): 31 | """Function to launch the thread for sending orders.""" 32 | t = threading.Thread(target=orders.thread_orders, 33 | args=(self.pill2kill, self.data, self.trading_data)) 34 | self.threads.append(t) 35 | t.start() 36 | print('Thread - ORDERS. LAUNCHED') 37 | 38 | def kill_threads(self): 39 | """Function to kill all the loaded threads.""" 40 | print('Threads - Stopping threads') 41 | self.pill2kill.set() 42 | for thread in self.threads: 43 | thread.join() 44 | 45 | def start(self): 46 | """Function to start all the threads""" 47 | self.thread_macd() 48 | self.thread_orders() 49 | 50 | def wait(self): 51 | """Function to make the thread wait.""" 52 | # Input para detener a los hilos 53 | print('\nPress ENTER to stop the bot\n') 54 | input() 55 | self.kill_threads() 56 | mt5.shutdown() -------------------------------------------------------------------------------- /MQL5_PYTHON/INDEX_BOT/bot.py: -------------------------------------------------------------------------------- 1 | import MetaTrader5 as mt5 2 | import CANDLE, threading, orders 3 | 4 | class Bot: 5 | 6 | def __init__(self, lotage: float, time_period: int, market: str): 7 | """Constructor of the bot. It justs fills the needed informartion for the bot. 8 | 9 | Args: 10 | lotage (float): Lotage to be used by the bot. 11 | time_period (int): Time period of the bot, 1 minute, 15 minutes... (in seconds) 12 | market (str): Market to operate in. 13 | """ 14 | self.threads = [] 15 | self.data = {'0': None, '1': None} 16 | self.pill2kill = threading.Event() 17 | self.trading_data = {} 18 | self.trading_data['lotage'] = lotage 19 | self.trading_data['time_period'] = time_period 20 | self.trading_data['market'] = market 21 | 22 | def thread_candles(self): 23 | """Function to launch the data thread.""" 24 | t = threading.Thread(target=CANDLE.thread_candle, 25 | args=(self.pill2kill, self.data)) 26 | self.threads.append(t) 27 | t.start() 28 | print('Thread - DATA. LAUNCHED') 29 | 30 | def thread_orders(self): 31 | """Function to launch the thread for sending orders.""" 32 | t = threading.Thread(target=orders.thread_orders, 33 | args=(self.pill2kill, self.data, self.trading_data)) 34 | self.threads.append(t) 35 | t.start() 36 | print('Thread - ORDERS. LAUNCHED') 37 | 38 | def kill_threads(self): 39 | """Function to kill all the loaded threads.""" 40 | print('Threads - Stopping threads') 41 | self.pill2kill.set() 42 | for thread in self.threads: 43 | thread.join() 44 | 45 | def start(self): 46 | """Function to start all the threads""" 47 | self.thread_candles() 48 | self.thread_orders() 49 | 50 | def wait(self): 51 | """Function to make the thread wait.""" 52 | # Input para detener a los hilos 53 | print('\nPress ENTER to stop the bot\n') 54 | input() 55 | self.kill_threads() 56 | mt5.shutdown() -------------------------------------------------------------------------------- /mql5/maxperdida-ganancia.mq5: -------------------------------------------------------------------------------- 1 | #include 2 | CTrade trade; 3 | ulong trade_ticket; 4 | 5 | 6 | input int SECOND_TO_CLOSE = 58; // Segundo de la vela en el que cerrar la operación 7 | 8 | 9 | MqlRates velas[]; 10 | 11 | int dia = 0; 12 | double profit = 0; 13 | input double MAX_WIN = 100; // Máximas ganancias 14 | input double MAX_LOSS = 100; // Máximas pérdidas 15 | 16 | 17 | bool ganancias_perdidas_alcanzadas() { 18 | // Vemos si el día ha cambiado 19 | MqlDateTime time; 20 | TimeCurrent(time); 21 | if (time.day != dia) { 22 | // Actualizamos el día y reseteamos el profit 23 | dia = time.day; 24 | profit = 0; 25 | } 26 | 27 | return profit >= MAX_WIN || profit <= MAX_LOSS*-1; 28 | } 29 | 30 | 31 | bool es_boom() { 32 | return velas[0].open < velas[0].close; 33 | } 34 | 35 | int bars; 36 | bool nueva_vela() { 37 | int current_bars = Bars(_Symbol, _Period); 38 | if (current_bars != bars) { 39 | bars = current_bars; 40 | return true; 41 | } 42 | 43 | return false; 44 | } 45 | 46 | bool operacion_cerrada() { 47 | return !PositionSelectByTicket(trade_ticket); 48 | } 49 | 50 | 51 | void OnTick() { 52 | 53 | // Si se han alcanzado las ganancias o las pérdidas no hacemos nada 54 | if (ganancias_perdidas_alcanzadas()) return; 55 | 56 | CopyRates(_Symbol, _Period, 0, 1, velas); 57 | 58 | if (es_boom() && nueva_vela() && operacion_cerrada()) { 59 | double bid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits); 60 | trade.Sell(0.1, _Symbol, bid); 61 | trade_ticket = trade.ResultOrder(); 62 | 63 | // Obtenemos el segunddo actual en el que estamos 64 | MqlDateTime time; 65 | TimeCurrent(time); 66 | 67 | // Calculamos cuantos segundos han de pasar hasta cerrar la operación 68 | int seconds_until_close = SECOND_TO_CLOSE - time.sec; 69 | if (seconds_until_close <= 0) seconds_until_close += 60; 70 | 71 | // Establecemos el temporizador para cerrar operaciones 72 | EventSetTimer(seconds_until_close); 73 | } 74 | } 75 | 76 | void OnTimer() { 77 | trade.PositionClose(trade_ticket); 78 | EventKillTimer(); 79 | } -------------------------------------------------------------------------------- /tutoriales/C/Shared memory/shared_mem.c: -------------------------------------------------------------------------------- 1 | /* FOR SEMAPHORE */ 2 | #include 3 | 4 | /* SHARED MEMORY */ 5 | #include 6 | #include /* For mode constants */ 7 | #include /* For O_* constants */ 8 | 9 | #include 10 | #include 11 | 12 | /* FOR FORK */ 13 | #include 14 | #include 15 | 16 | /* FOR KILLING THE CHILD PROCESS */ 17 | #include 18 | 19 | #define SHM_SEMS "sems_shared_memory" 20 | 21 | typedef struct { 22 | int shared_var; 23 | sem_t sem1; 24 | sem_t semaphore2; 25 | } Sems; 26 | 27 | void main() { 28 | 29 | /* Opening the shared memory */ 30 | int fd_shm = shm_open(SHM_SEMS, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); 31 | 32 | ftruncate(fd_shm, sizeof(Sems)); 33 | 34 | Sems *sems = mmap(NULL, sizeof(Sems), PROT_READ | PROT_WRITE, MAP_SHARED, fd_shm, 0); 35 | 36 | 37 | // 1 to share between processes Initial value of the sem 38 | sem_init(&sems->sem1, 1, 0); 39 | sem_init(&sems->semaphore2, 1, 0); 40 | 41 | for (int i = 0; i < 190; i++) 42 | 43 | if (fork() == 0) { // child 44 | printf("CHILD: %d\n", sems->shared_var); 45 | printf("CHILD: I'm going to change the value to 1\n"); 46 | sems->shared_var = 1; 47 | sems->shared_var = 0; 48 | printf("CHILD: %d\n", sems->shared_var); 49 | sem_post(&sems->sem1); 50 | 51 | 52 | 53 | /* Unmapping the sems */ 54 | munmap(sems, sizeof(Sems)); 55 | 56 | } else { // father 57 | printf("FATHER: %d\n", sems->shared_var); 58 | sem_wait(&sems->sem1); 59 | printf("FATHER: %d\n", sems->shared_var); 60 | 61 | wait(NULL); 62 | 63 | /* Only the father destroys the sems */ 64 | sem_destroy(&sems->sem1); 65 | sem_destroy(&sems->semaphore2); 66 | 67 | /* Unmapping the sems */ 68 | munmap(sems, sizeof(Sems)); 69 | 70 | /* Destroying the shared memory (only the father) */ 71 | shm_unlink(SHM_SEMS); 72 | } 73 | 74 | } -------------------------------------------------------------------------------- /mql5/MACD_lotaje_dinamico.mq5: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* Handler */ 4 | int MACD_h; 5 | 6 | /* Arrays where the indicator data is stored */ 7 | double MACD[]; 8 | double SIGNAL[]; 9 | 10 | /* For openning operations */ 11 | CTrade trade; 12 | ulong trade_ticket = 0; 13 | bool time_passed = true; 14 | 15 | double get_lotage() { 16 | double balance = AccountInfoDouble(ACCOUNT_BALANCE); 17 | return NormalizeDouble((balance/1000)*0.05, 2); 18 | } 19 | 20 | int OnInit() { 21 | /* Initializing the handlers */ 22 | MACD_h = iMACD(_Symbol, _Period, 12, 26, 9, PRICE_CLOSE); 23 | 24 | ArraySetAsSeries(MACD, true); 25 | ArraySetAsSeries(SIGNAL, true); 26 | 27 | return(INIT_SUCCEEDED); 28 | } 29 | 30 | void OnTick() { 31 | /* Saving the data of the indicator */ 32 | CopyBuffer(MACD_h, 0, 1, 4, MACD); 33 | CopyBuffer(MACD_h, 1, 1, 4, SIGNAL); 34 | 35 | /* Checking if there's an open operation */ 36 | if (PositionSelectByTicket(trade_ticket) == false) { 37 | // Reseting the trade flags 38 | trade_ticket = 0; 39 | } 40 | 41 | 42 | if ( // Buy 43 | MACD[1] < SIGNAL[1] && MACD[0] > SIGNAL[0] // Cross 44 | && MACD[0] < -0.0002 45 | && trade_ticket <= 0 && time_passed == true 46 | ) { 47 | /* Precio actual */ 48 | double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK), _Digits); 49 | 50 | //--- Abrir compra 51 | double lotaje = get_lotage(); 52 | trade.Buy(lotaje, _Symbol, Ask, Ask-40*_Point, Ask+50*_Point, NULL); 53 | trade_ticket = trade.ResultOrder(); 54 | 55 | time_passed = false; 56 | 57 | EventSetTimer(PeriodSeconds(PERIOD_CURRENT)*3); 58 | 59 | } else if ( // venta 60 | MACD[1] > SIGNAL[1] && MACD[0] < SIGNAL[0] // Cross 61 | && MACD[0] > 0.0002 62 | && trade_ticket <= 0 && time_passed == true 63 | ) { 64 | /* Precio actual */ 65 | double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits); 66 | 67 | //--- Abrir venta 68 | double lotaje = get_lotage(); 69 | trade.Sell(lotaje, _Symbol, Bid, Bid+40*_Point, Bid-50*_Point, NULL); 70 | trade_ticket = trade.ResultOrder(); 71 | 72 | time_passed = false; 73 | 74 | EventSetTimer(PeriodSeconds(PERIOD_CURRENT)*3); 75 | } 76 | } 77 | 78 | void OnTimer() { 79 | time_passed = true; 80 | } -------------------------------------------------------------------------------- /mql5/resistances.mq5: -------------------------------------------------------------------------------- 1 | #define SIZE 800 2 | #define MARGIN 20 3 | #define MARGIN_POINTS 500000*_Point 4 | #define REQ_LOWS_FOR_SUPPORT 1 5 | 6 | MqlRates candles[]; 7 | 8 | double lows[]; 9 | 10 | bool isMin(int index, double value) { 11 | int i = index >= MARGIN ? index - MARGIN : 0; 12 | int end = index + MARGIN > SIZE - 1 ? SIZE - 1 : index + MARGIN; 13 | 14 | for(; i < end; i++) 15 | if (candles[i].close < value) 16 | return false; 17 | 18 | return true; 19 | } 20 | 21 | void findMins() { 22 | for(int i = 0; i < SIZE; i++) { 23 | if (isMin(i, candles[i].close)) { 24 | int size = ArraySize(lows); 25 | ArrayResize(lows, size+1); 26 | lows[size] = candles[i].close; 27 | } 28 | } 29 | } 30 | 31 | bool support_drawn(double value, double& lines_drawn[]) { 32 | int size = ArraySize(lines_drawn); 33 | 34 | if (size == 0) return false; 35 | 36 | for(int i = 0; i < size; i++) 37 | if (lines_drawn[i] + MARGIN_POINTS > value 38 | && lines_drawn[i] - MARGIN_POINTS < value) return true; 39 | 40 | return false; 41 | } 42 | 43 | void draw_supports() { 44 | 45 | findMins(); 46 | 47 | double val_lines_drawn[]; 48 | 49 | for(int i = 0; i < ArraySize(lows); i++) { 50 | 51 | int lows_in = 0; 52 | 53 | for(int n = 0; n < ArraySize(lows); n++) { 54 | if (n == i) continue; 55 | else if (lows[i] + MARGIN_POINTS > lows[n] 56 | && lows[i] - MARGIN_POINTS < lows[n]) lows_in++; 57 | } 58 | 59 | if (lows_in >= REQ_LOWS_FOR_SUPPORT) { 60 | if (!support_drawn(candles[i].close, val_lines_drawn)) { 61 | ObjectCreate(0, "support"+IntegerToString(ArraySize(val_lines_drawn)), OBJ_HLINE, 0, 0, candles[i].close); 62 | ObjectSetInteger(0, "support"+IntegerToString(ArraySize(val_lines_drawn)), OBJPROP_COLOR, clrRed); 63 | ObjectSetInteger(0, "support"+IntegerToString(ArraySize(val_lines_drawn)), OBJPROP_WIDTH, 4); 64 | 65 | int size = ArraySize(val_lines_drawn); 66 | ArrayResize(val_lines_drawn, size+1); 67 | val_lines_drawn[size] = candles[i].close; 68 | } 69 | } 70 | } 71 | } 72 | 73 | void OnInit() { 74 | 75 | ArraySetAsSeries(candles, true); 76 | 77 | CopyRates(_Symbol, _Period, 0, SIZE, candles); 78 | 79 | draw_supports(); 80 | 81 | } -------------------------------------------------------------------------------- /Python trading bot/src/RSI.py: -------------------------------------------------------------------------------- 1 | # Global variables 2 | N_for_RSI = 14 3 | RSI_value = None 4 | 5 | 6 | def check_buy() -> bool: 7 | """Function to check if the RSI allows 8 | a buy operation. 9 | 10 | Returns: 11 | bool: True if RSI allows, false if not. 12 | """ 13 | if RSI_value is None: 14 | return False 15 | else: 16 | if RSI_value >= 65: 17 | return True 18 | return False 19 | 20 | 21 | def check_sell() -> bool: 22 | """Function to check if the RSI 23 | allows a sell operation. 24 | 25 | Returns: 26 | bool: True if RSI allows, false if not. 27 | """ 28 | if RSI_value is None: 29 | return False 30 | else: 31 | if RSI_value <= 35: 32 | return True 33 | return False 34 | 35 | 36 | def RS(ticks: list) -> float: 37 | """Function to get the RS. 38 | 39 | Args: 40 | ticks (list): List with prices. 41 | 42 | Returns: 43 | float: Value of the RS. 44 | """ 45 | up = 0 46 | down = 0 47 | i = 0 48 | 49 | while i < len(ticks)-2: 50 | if ticks[i] < ticks[i+1]: 51 | up += ticks[i+1]-ticks[i] 52 | elif ticks[i] > ticks[i+1]: 53 | down += ticks[i]-ticks[i+1] 54 | i+=1 55 | 56 | up /= len(ticks) 57 | down /= len(ticks) 58 | 59 | return up/down 60 | 61 | 62 | def RSI(ticks: list) -> float: 63 | """Function to compute the value of the RSI. 64 | 65 | Args: 66 | ticks (list): List with prices. 67 | 68 | Returns: 69 | float: Value of the RSI. 70 | """ 71 | return 100 - ( 100/( 1+RS(ticks) ) ) 72 | 73 | 74 | def thread_RSI(pill2kill, ticks: list, indicators: dict): 75 | """Function executed by a thread. Calculates the RSI and 76 | stores it in the dictionary. 77 | 78 | Args: 79 | pill2kill (Threading.event): Event for stopping the threads executuion. 80 | ticks (list): List with prices. 81 | indicators (dict): Dictionary where the values are stored. 82 | """ 83 | global RSI_value 84 | 85 | # If the list hasn't enough values we wait. 86 | while len(ticks) < N_for_RSI and not pill2kill.wait(1.5): 87 | print("[THREAD - RSI] - Waiting for ticks") 88 | 89 | print("[THREAD - RSI] - Computing values") 90 | 91 | while not pill2kill.wait(1): 92 | RSI_value = RSI(ticks[-N_for_RSI:]) 93 | indicators['RSI'] = RSI_value -------------------------------------------------------------------------------- /mql5/time_bot.mq5: -------------------------------------------------------------------------------- 1 | input int HOUR = 8; // Hour 2 | input int MINUTE = 0; // Minute 3 | 4 | #include 5 | CTrade trade; 6 | ulong trade_ticket = 0; 7 | 8 | // Documentation of time: 9 | // https://www.mql5.com/en/docs/dateandtime/timecurrent 10 | 11 | // Documentación del tiempo: 12 | // https://www.mql5.com/es/docs/dateandtime/timecurrent 13 | 14 | 15 | void OnInit() { 16 | MqlDateTime time; 17 | TimeLocal(time); 18 | 19 | // Second way: Computing when how much time do we have left until the specified time 20 | // The most consistent way. 21 | 22 | // Segunda solución: Calculando cuanto tiempo nos queda hasta la hora especificada 23 | // El método más consistente. 24 | 25 | // Computing the seconds left until the time established 26 | // Calculando los segundos que quedan hasta la hora establecida 27 | int hours_left = time.hour <= HOUR ? HOUR - time.hour : 24 - (time.hour - HOUR); 28 | int minutes_left = time.min <= MINUTE ? MINUTE - time.min : 60 - (time.min - MINUTE); 29 | 30 | int seconds_left = hours_left*60*60 + minutes_left*60; 31 | 32 | EventSetTimer(seconds_left); 33 | } 34 | 35 | void OnTick() { 36 | /* REMOVE THIS LINE IF YOU WANT IT TO WORK - QUITA ESTA LÍNEA SI QUIERES QUE EL BOT FUNCIONE 37 | MqlDateTime time; 38 | TimeLocal(time); 39 | 40 | // Reseting the trade ticket 41 | if (!PositionSelectByTicket(trade_ticket)) trade_ticket = 0; 42 | 43 | // First way: Checking time on every tick. We depend that there's a tick at the specified time 44 | // This is not the best way 45 | 46 | // Solución uno: Comprobar el tiempo en cada tick. Dependemos de que haya un tick en la hora específica 47 | // Esta no es la mejor forma 48 | if ((time.min == MINUTE || time.hour == HOUR) && trade_ticket == 0) { 49 | double bid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits); 50 | 51 | trade.Sell(0.1, _Symbol, bid, bid+2000*_Point, bid-2000*_Point); 52 | trade_ticket = trade.ResultOrder(); 53 | } 54 | REMOVE THIS LINE IF YOU WANT IT TO WORK - QUITA ESTA LÍNEA SI QUIERES QUE EL BOT FUNCIONE */ 55 | } 56 | 57 | void OnTimer() { 58 | double bid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits); 59 | 60 | trade.Sell(0.1, _Symbol, bid, bid+10000*_Point, bid-10000*_Point); 61 | trade_ticket = trade.ResultOrder(); 62 | 63 | EventKillTimer(); 64 | EventSetTimer(24*60*60); 65 | } 66 | -------------------------------------------------------------------------------- /MQL5_PYTHON/INDEX_BOT/test_order.py: -------------------------------------------------------------------------------- 1 | import MetaTrader5 as mt5 2 | 3 | # mostramos los datos sobre el paquete MetaTrader5 4 | print("MetaTrader5 package author: ", mt5.__author__) 5 | print("MetaTrader5 package version: ", mt5.__version__) 6 | 7 | # establecemos la conexión con el terminal MetaTrader 5 8 | if not mt5.initialize(): 9 | print("initialize() failed, error code =",mt5.last_error()) 10 | quit() 11 | 12 | # preparamos la estructura de la solicitud de compra 13 | symbol = "BTCEUR" 14 | symbol_info = mt5.symbol_info(symbol) 15 | if symbol_info is None: 16 | print(symbol, "not found, can not call order_check()") 17 | mt5.shutdown() 18 | quit() 19 | 20 | # si el símbolo no está disponible en MarketWatch, lo añadimos 21 | if not symbol_info.visible: 22 | print(symbol, "is not visible, trying to switch on") 23 | if not mt5.symbol_select(symbol,True): 24 | print("symbol_select({}}) failed, exit",symbol) 25 | mt5.shutdown() 26 | quit() 27 | 28 | lot = 0.1 29 | point = mt5.symbol_info(symbol).point 30 | price = mt5.symbol_info_tick(symbol).ask 31 | deviation = 20 32 | request = { 33 | "action": mt5.TRADE_ACTION_DEAL, 34 | "symbol": symbol, 35 | "volume": lot, 36 | "type": mt5.ORDER_TYPE_BUY, 37 | "price": price, 38 | "sl": price - 100 * point, 39 | "tp": price + 100 * point, 40 | "deviation": deviation, 41 | "magic": 234000, 42 | "comment": "python script open", 43 | "type_time": mt5.ORDER_TIME_GTC, 44 | "type_filling": mt5.ORDER_FILLING_FOK, 45 | } 46 | 47 | # enviamos la solicitud comercial 48 | result = mt5.order_send(request) 49 | # comprobamos el resultado de la ejecución 50 | print("1. order_send(): by {} {} lots at {} with deviation={} points".format(symbol,lot,price,deviation)); 51 | if result.retcode != mt5.TRADE_RETCODE_DONE: 52 | print("2. order_send failed, retcode={}".format(result.retcode)) 53 | # solicitamos el resultado en forma de diccionario y lo mostramos elemento por elemento 54 | result_dict=result._asdict() 55 | for field in result_dict.keys(): 56 | print(" {}={}".format(field,result_dict[field])) 57 | # si se trata de la estructura de una solicitud comercial, también la mostramos elemento por elemento 58 | if field=="request": 59 | traderequest_dict=result_dict[field]._asdict() 60 | for tradereq_filed in traderequest_dict: 61 | print(" traderequest: {}={}".format(tradereq_filed,traderequest_dict[tradereq_filed])) 62 | print("shutdown() and quit") 63 | mt5.shutdown() 64 | quit() -------------------------------------------------------------------------------- /MQL5_PYTHON/MACD_BOT/test_order.py: -------------------------------------------------------------------------------- 1 | import MetaTrader5 as mt5 2 | 3 | # mostramos los datos sobre el paquete MetaTrader5 4 | print("MetaTrader5 package author: ", mt5.__author__) 5 | print("MetaTrader5 package version: ", mt5.__version__) 6 | 7 | # establecemos la conexión con el terminal MetaTrader 5 8 | if not mt5.initialize(): 9 | print("initialize() failed, error code =",mt5.last_error()) 10 | quit() 11 | 12 | # preparamos la estructura de la solicitud de compra 13 | symbol = "BTCEUR" 14 | symbol_info = mt5.symbol_info(symbol) 15 | if symbol_info is None: 16 | print(symbol, "not found, can not call order_check()") 17 | mt5.shutdown() 18 | quit() 19 | 20 | # si el símbolo no está disponible en MarketWatch, lo añadimos 21 | if not symbol_info.visible: 22 | print(symbol, "is not visible, trying to switch on") 23 | if not mt5.symbol_select(symbol,True): 24 | print("symbol_select({}}) failed, exit",symbol) 25 | mt5.shutdown() 26 | quit() 27 | 28 | lot = 0.1 29 | point = mt5.symbol_info(symbol).point 30 | price = mt5.symbol_info_tick(symbol).ask 31 | deviation = 20 32 | request = { 33 | "action": mt5.TRADE_ACTION_DEAL, 34 | "symbol": symbol, 35 | "volume": lot, 36 | "type": mt5.ORDER_TYPE_BUY, 37 | "price": price, 38 | "sl": price - 100 * point, 39 | "tp": price + 100 * point, 40 | "deviation": deviation, 41 | "magic": 234000, 42 | "comment": "python script open", 43 | "type_time": mt5.ORDER_TIME_GTC, 44 | "type_filling": mt5.ORDER_FILLING_FOK, 45 | } 46 | 47 | # enviamos la solicitud comercial 48 | result = mt5.order_send(request) 49 | # comprobamos el resultado de la ejecución 50 | print("1. order_send(): by {} {} lots at {} with deviation={} points".format(symbol,lot,price,deviation)); 51 | if result.retcode != mt5.TRADE_RETCODE_DONE: 52 | print("2. order_send failed, retcode={}".format(result.retcode)) 53 | # solicitamos el resultado en forma de diccionario y lo mostramos elemento por elemento 54 | result_dict=result._asdict() 55 | for field in result_dict.keys(): 56 | print(" {}={}".format(field,result_dict[field])) 57 | # si se trata de la estructura de una solicitud comercial, también la mostramos elemento por elemento 58 | if field=="request": 59 | traderequest_dict=result_dict[field]._asdict() 60 | for tradereq_filed in traderequest_dict: 61 | print(" traderequest: {}={}".format(tradereq_filed,traderequest_dict[tradereq_filed])) 62 | print("shutdown() and quit") 63 | mt5.shutdown() 64 | quit() -------------------------------------------------------------------------------- /MQL5_PYTHON/RSI_BOT/test_order.py: -------------------------------------------------------------------------------- 1 | import MetaTrader5 as mt5 2 | 3 | # mostramos los datos sobre el paquete MetaTrader5 4 | print("MetaTrader5 package author: ", mt5.__author__) 5 | print("MetaTrader5 package version: ", mt5.__version__) 6 | 7 | # establecemos la conexión con el terminal MetaTrader 5 8 | if not mt5.initialize(): 9 | print("initialize() failed, error code =",mt5.last_error()) 10 | quit() 11 | 12 | # preparamos la estructura de la solicitud de compra 13 | symbol = "BTCEUR" 14 | symbol_info = mt5.symbol_info(symbol) 15 | if symbol_info is None: 16 | print(symbol, "not found, can not call order_check()") 17 | mt5.shutdown() 18 | quit() 19 | 20 | # si el símbolo no está disponible en MarketWatch, lo añadimos 21 | if not symbol_info.visible: 22 | print(symbol, "is not visible, trying to switch on") 23 | if not mt5.symbol_select(symbol,True): 24 | print("symbol_select({}}) failed, exit",symbol) 25 | mt5.shutdown() 26 | quit() 27 | 28 | lot = 0.1 29 | point = mt5.symbol_info(symbol).point 30 | price = mt5.symbol_info_tick(symbol).ask 31 | deviation = 20 32 | request = { 33 | "action": mt5.TRADE_ACTION_DEAL, 34 | "symbol": symbol, 35 | "volume": lot, 36 | "type": mt5.ORDER_TYPE_BUY, 37 | "price": price, 38 | "sl": price - 100 * point, 39 | "tp": price + 100 * point, 40 | "deviation": deviation, 41 | "magic": 234000, 42 | "comment": "python script open", 43 | "type_time": mt5.ORDER_TIME_GTC, 44 | "type_filling": mt5.ORDER_FILLING_FOK, 45 | } 46 | 47 | # enviamos la solicitud comercial 48 | result = mt5.order_send(request) 49 | # comprobamos el resultado de la ejecución 50 | print("1. order_send(): by {} {} lots at {} with deviation={} points".format(symbol,lot,price,deviation)); 51 | if result.retcode != mt5.TRADE_RETCODE_DONE: 52 | print("2. order_send failed, retcode={}".format(result.retcode)) 53 | # solicitamos el resultado en forma de diccionario y lo mostramos elemento por elemento 54 | result_dict=result._asdict() 55 | for field in result_dict.keys(): 56 | print(" {}={}".format(field,result_dict[field])) 57 | # si se trata de la estructura de una solicitud comercial, también la mostramos elemento por elemento 58 | if field=="request": 59 | traderequest_dict=result_dict[field]._asdict() 60 | for tradereq_filed in traderequest_dict: 61 | print(" traderequest: {}={}".format(tradereq_filed,traderequest_dict[tradereq_filed])) 62 | print("shutdown() and quit") 63 | mt5.shutdown() 64 | quit() -------------------------------------------------------------------------------- /MQL5_PYTHON/INDEX_BOT/orders.py: -------------------------------------------------------------------------------- 1 | import MetaTrader5 as mt5 2 | import datetime 3 | 4 | 5 | CANDLES_BETWEEN_OPERATIONS = 3 6 | STOPLOSS = 15000 7 | TAKEPROFIT = 15000 8 | 9 | 10 | def open_position(market: str, lotage: float, type_op): 11 | """Function to open a position. 12 | Args: 13 | market (string) 14 | lotage (float) 15 | type_op: Type of the operation 16 | """ 17 | point = mt5.symbol_info(market).point 18 | price = mt5.symbol_info_tick(market).ask 19 | 20 | if type_op == mt5.ORDER_TYPE_BUY: 21 | sl = price-STOPLOSS*point 22 | tp = price+TAKEPROFIT*point 23 | else: 24 | sl = price+STOPLOSS*point 25 | tp = price-TAKEPROFIT*point 26 | 27 | deviation = 20 28 | operation = { 29 | "action": mt5.TRADE_ACTION_DEAL, 30 | "symbol": market, 31 | "volume": lotage, 32 | "type": type_op, 33 | "price": price, 34 | "sl": sl, 35 | "tp": tp, 36 | "deviation": deviation, 37 | "magic": 234000, 38 | "comment": "python script open", 39 | "type_time": mt5.ORDER_TIME_GTC, 40 | "type_filling": mt5.ORDER_FILLING_FOK, 41 | } 42 | 43 | # Sending the buy 44 | result = mt5.order_send(operation) 45 | print("[Thread - orders] 1. order_send(): by {} {} lots at {} with deviation={} points".format(market,lotage,price,deviation)) 46 | if result.retcode != mt5.TRADE_RETCODE_DONE: 47 | print("[Thread - orders] Failed operation: retcode={}".format(result.retcode)) 48 | return None 49 | 50 | def thread_orders(stop_event, data, trading_data): 51 | """Function executed by a thread. It checks if the conditions to open orders 52 | are okay. 53 | Args: 54 | stop_event (thread.Event): Event to stop the thread. 55 | data (dict): Dictionary with candles and the indicator. 56 | trading_data (dict): Dictionary with the lotage and the market. 57 | """ 58 | last_operation_time = 0 59 | ep = datetime.datetime(1970,1,1,0,0,0) 60 | 61 | while data["0"] is None and data["1"] is None: 62 | pass 63 | 64 | print("[INFO]\tOrders running") 65 | 66 | while not stop_event.is_set(): 67 | cur_time = int((datetime.datetime.utcnow()- ep).total_seconds()) 68 | 69 | if data["1"][0] < data["1"][1] \ 70 | and cur_time > last_operation_time+trading_data["time_period"]*CANDLES_BETWEEN_OPERATIONS: # Open sell 71 | last_operation_time = cur_time 72 | open_position(trading_data["market"], trading_data["lotage"], mt5.ORDER_TYPE_SELL) -------------------------------------------------------------------------------- /tutoriales/C/sems_exercise/sem.c: -------------------------------------------------------------------------------- 1 | /* FOR SEMAPHORE */ 2 | #include 3 | 4 | /* SHARED MEMORY */ 5 | #include 6 | #include /* For mode constants */ 7 | #include /* For O_* constants */ 8 | 9 | #include 10 | #include 11 | 12 | /* FOR FORK */ 13 | #include 14 | #include 15 | 16 | /* FOR WAITING THE CHILD PROCESS */ 17 | #include 18 | 19 | /* for srand */ 20 | #include 21 | 22 | 23 | #define SHM_SEMS "sems_shared_memory3" 24 | #define NUM_KIDS 10 25 | 26 | 27 | typedef struct { 28 | sem_t mutex; 29 | short available_pieces; 30 | } Shared_Variables; 31 | 32 | void call_mum_for_cakes(Shared_Variables *sh) { 33 | sleep((rand() % 5) + 2); 34 | 35 | sh->available_pieces = 3; 36 | printf("I'm mum, and I have brought a new cake\n"); 37 | } 38 | 39 | void main() { 40 | 41 | srand(time(NULL)); 42 | 43 | /* Opening the shared memory */ 44 | int fd_shm = shm_open(SHM_SEMS, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); 45 | 46 | ftruncate(fd_shm, sizeof(Shared_Variables)); 47 | 48 | Shared_Variables *sh = mmap(NULL, sizeof(Shared_Variables), PROT_READ | PROT_WRITE, MAP_SHARED, fd_shm, 0); 49 | 50 | // Initializing values 51 | // 1 to share between processes Initial value of the sem 52 | sem_init(&sh->mutex, 1, 1); 53 | sh->available_pieces = 3; 54 | 55 | for(int i = 0; i < NUM_KIDS; i++) { 56 | if (fork() == 0) { // Child 57 | sleep((rand() % 9) + 1); 58 | printf("Kid %d entered\n", i+1); 59 | for (int n = 0; n < (rand() % 4) + 1; n++) { 60 | 61 | 62 | sem_wait(&sh->mutex); 63 | 64 | if (sh->available_pieces <= 0) 65 | call_mum_for_cakes(sh); 66 | 67 | sh->available_pieces -= 1; 68 | 69 | printf("I'm the kid %d and I'm taking my peace of cake. There are %d left\n", i+1, sh->available_pieces); 70 | sleep((rand() % 4) + 1); 71 | 72 | sem_post(&sh->mutex); 73 | 74 | printf("I'm the kid %d and I'm eating\n", i+1); 75 | sleep((rand() % 3) + 3); 76 | 77 | } 78 | 79 | munmap(sh, sizeof(Shared_Variables)); 80 | return; 81 | } 82 | } 83 | 84 | /* Waiting for the children */ 85 | for (int i = 0; i < NUM_KIDS; i++) 86 | while (wait(NULL) == -1); 87 | 88 | munmap(sh, sizeof(Shared_Variables)); 89 | shm_unlink(SHM_SEMS); 90 | } -------------------------------------------------------------------------------- /MQL5_PYTHON/MACD_client.mq5: -------------------------------------------------------------------------------- 1 | /* 2 | MESSAGES TO SEND IMPLEMENTED: 3 | macd value 0,macd value 1,macd value 2|signal value 0,signal value 1,signal value 2 4 | Example: 5 | 0.000032,0.000031,0.000028|0.000032,0.000031,0.000028 6 | 7 | 8 | MESSAGES TO RECEIVE NOT IMPLEMENTED: 9 | BUY|LOTAGE (double 2 decimals)|STOP_LOSS POINTS (int)|TAKE_PROFIT POINTS (int) 10 | Example: 11 | BUY|0.01|30|90 12 | This opens a buy operation in the current market of 0.01 lotage, with 13 | a stop loss 30 points below the opening price and a take profit 90 points 14 | above the opening price. 15 | 16 | SELL|LOTAGE (double 2 decimals)|STOP_LOSS POINTS (int)|TAKE_PROFIT POINTS (int) 17 | Example: 18 | SELL|0.01|30|90 19 | This opens a sell operation in the current market of 0.01 lotage, with 20 | a stop loss 30 points above the opening price and a take profit 90 points 21 | below the opening price. 22 | */ 23 | 24 | #include 25 | CTrade trade; 26 | 27 | 28 | /* Socket variables */ 29 | string address = "localhost"; 30 | int port = 8888; 31 | int socket; // Socket handle 32 | int MAX_BUFF_LEN = 1024; // Max size for reading in the buffer 33 | 34 | /* MACD variables */ 35 | int macd_h; // MACD handle 36 | double macd[]; 37 | double signal[]; 38 | 39 | 40 | void OnInit() { 41 | macd_h = iMACD(_Symbol, _Period, 12, 26, 9, PRICE_CLOSE); 42 | if (macd_h == INVALID_HANDLE) Print("Error - 3: iMACD failure. ", GetLastError()); 43 | 44 | // Initializing the socket 45 | socket = SocketCreate(); 46 | if (socket == INVALID_HANDLE) Print("Error - 1: SocketCreate failure. ", GetLastError()); 47 | else { 48 | if (SocketConnect(socket, address, port, 10000)) Print("[INFO]\tConnection stablished"); 49 | else Print("Error - 2: SocketConnect failure. ", GetLastError()); 50 | } 51 | } 52 | 53 | 54 | void OnDeinit(const int reason) { 55 | /* Closing the socket */ 56 | // Creating the message 57 | char req[]; 58 | 59 | Print("[INFO]\tClosing the socket."); 60 | 61 | int len = StringToCharArray("END CONNECTION\0", req)-1; 62 | SocketSend(socket, req, len); 63 | SocketClose(socket); 64 | } 65 | 66 | 67 | void OnTick() { 68 | // Loading the macd values 69 | CopyBuffer(macd_h, MAIN_LINE, 0, 3, macd); 70 | CopyBuffer(macd_h, SIGNAL_LINE, 0, 3, signal); 71 | 72 | // Sending MACD data 73 | Print("[INFO]\tSending MACD and SIGNAL"); 74 | string msg; 75 | StringConcatenate(msg, macd[0], ",", macd[1], ",", macd[2], " | ", signal[0], ",", signal[1], ",", signal[2]); 76 | 77 | char req[]; 78 | int len = StringToCharArray(msg, req)-1; 79 | SocketSend(socket, req, len); 80 | } 81 | -------------------------------------------------------------------------------- /ta/RSI/BOT/orders.py: -------------------------------------------------------------------------------- 1 | import MetaTrader5 as mt5 2 | import datetime 3 | 4 | RSI_BUY_THRESHOLD = 70 5 | RSI_SELL_THRESHOLD = 30 6 | CANDLES_BETWEEN_OPERATIONS = 3 7 | 8 | STOPLOSS = 10 9 | TAKEPROFIT = 20 10 | 11 | def open_position(market, lotage, type_op): 12 | """Function to open a position. 13 | 14 | Args: 15 | market (string) 16 | lotage (float) 17 | type_op (string): Type of the operation 18 | """ 19 | point = mt5.symbol_info(market).point 20 | price = mt5.symbol_info_tick(market).ask 21 | 22 | if type_op == "buy": 23 | sl = price-STOPLOSS*point 24 | tp = price+TAKEPROFIT*point 25 | else: 26 | sl = price+STOPLOSS*point 27 | tp = price-TAKEPROFIT*point 28 | 29 | deviation = 20 30 | operation = { 31 | "action": mt5.TRADE_ACTION_DEAL, 32 | "symbol": market, 33 | "volume": lotage, 34 | "type": mt5.ORDER_TYPE_BUY if type_op == "buy" else mt5.ORDER_TYPE_SELL, 35 | "price": price, 36 | "sl": sl, 37 | "tp": tp, 38 | "deviation": deviation, 39 | "magic": 234000, 40 | "comment": "python script open", 41 | "type_time": mt5.ORDER_TIME_GTC, 42 | "type_filling": mt5.ORDER_FILLING_IOC, 43 | } 44 | 45 | # Sending the buy 46 | result = mt5.order_send(operation) 47 | print("[Thread - orders] 1. order_send(): by {} {} lots at {} with deviation={} points".format(market,lotage,price,deviation)) 48 | if result.retcode != mt5.TRADE_RETCODE_DONE: 49 | print("[Thread - orders] Failed operation: retcode={}".format(result.retcode)) 50 | return None 51 | 52 | def thread_orders(stop_event, data, trading_data): 53 | """Function executed by a thread. It checks if the conditions to open orders 54 | are okay. 55 | 56 | Args: 57 | stop_event (thread.Event): Event to stop the thread. 58 | data (dict): Dictionary with candles and the indicator. 59 | trading_data (dict): Dictionary with the lotage and the market. 60 | """ 61 | last_operation_time = 0 62 | ep = datetime.datetime(1970,1,1,0,0,0) 63 | 64 | while not data["rsi_ready"]: 65 | pass 66 | 67 | while not stop_event.wait(10): 68 | cur_time = int((datetime.datetime.utcnow()- ep).total_seconds()) 69 | if data["RSI"][0] > RSI_BUY_THRESHOLD and cur_time > last_operation_time+trading_data["time_period"]*CANDLES_BETWEEN_OPERATIONS: # Open buy 70 | last_operation_time = cur_time 71 | open_position(trading_data["market"], trading_data["lotage"], "buy") 72 | elif data["RSI"][0] < RSI_SELL_THRESHOLD and cur_time > last_operation_time+trading_data["time_period"]*CANDLES_BETWEEN_OPERATIONS: # Open sell 73 | last_operation_time = cur_time 74 | open_position(trading_data["market"], trading_data["lotage"], "sell") -------------------------------------------------------------------------------- /mql5/break_even.mq5: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* Handler */ 4 | int MACD_h; 5 | 6 | /* Arrays where the indicator data is stored */ 7 | double MACD[]; 8 | double SIGNAL[]; 9 | 10 | /* For openning operations */ 11 | CTrade trade; 12 | ulong trade_ticket = 0; 13 | bool time_passed = true; 14 | double open_price = 0; 15 | 16 | 17 | // 500€ -> 0.02 18 | // 1000€ -> 0.05 19 | // 2000€ -> 0.1 20 | // 1500€ -> 0.07 21 | double get_lotage() { 22 | double balance = AccountInfoDouble(ACCOUNT_BALANCE); 23 | return NormalizeDouble((balance/1000)*0.01, 2); 24 | } 25 | 26 | 27 | int OnInit() { 28 | /* Initializing the handlers */ 29 | MACD_h = iMACD(_Symbol, _Period, 12, 26, 9, PRICE_CLOSE); 30 | 31 | ArraySetAsSeries(MACD, true); 32 | ArraySetAsSeries(SIGNAL, true); 33 | 34 | return(INIT_SUCCEEDED); 35 | } 36 | 37 | void OnTick() { 38 | /* Saving the data of the indicator */ 39 | CopyBuffer(MACD_h, 0, 1, 4, MACD); 40 | CopyBuffer(MACD_h, 1, 1, 4, SIGNAL); 41 | 42 | /* Checking if there's an open operation */ 43 | if (PositionSelectByTicket(trade_ticket) == false && trade_ticket != 0) { 44 | // Reseting the trade flags 45 | trade_ticket = 0; 46 | open_price = 0; 47 | } 48 | 49 | /* BREAK EVEN */ 50 | else if (trade_ticket != 0 && open_price != 0) { 51 | double profit = PositionGetDouble(POSITION_PROFIT); 52 | 53 | if (profit >= 0.5) { 54 | trade.PositionModify(trade_ticket, open_price, 0); 55 | open_price = 0; 56 | } 57 | } 58 | /* BREAK EVEN */ 59 | 60 | 61 | if ( // Buy 62 | MACD[1] < SIGNAL[1] && MACD[0] > SIGNAL[0] // Cross 63 | && trade_ticket <= 0 && time_passed == true 64 | ) { 65 | /* Precio actual */ 66 | double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK), _Digits); 67 | open_price = Ask; 68 | 69 | //--- Abrir compra 70 | double lotage = get_lotage(); 71 | trade.Buy(lotage, _Symbol, Ask, Ask-100*_Point, 0, NULL); 72 | trade_ticket = trade.ResultOrder(); 73 | 74 | time_passed = false; 75 | 76 | EventSetTimer(PeriodSeconds(PERIOD_CURRENT)*3); 77 | 78 | } else if ( // venta 79 | MACD[1] > SIGNAL[1] && MACD[0] < SIGNAL[0] // Cross 80 | && trade_ticket <= 0 && time_passed == true 81 | ) { 82 | /* Precio actual */ 83 | double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits); 84 | open_price = Bid; 85 | 86 | //--- Abrir venta 87 | double lotage = get_lotage(); 88 | trade.Sell(lotage, _Symbol, Bid, Bid+100*_Point, 0, NULL); 89 | trade_ticket = trade.ResultOrder(); 90 | 91 | time_passed = false; 92 | 93 | EventSetTimer(PeriodSeconds(PERIOD_CURRENT)*3); 94 | } 95 | } 96 | 97 | void OnTimer() { 98 | time_passed = true; 99 | } -------------------------------------------------------------------------------- /MQL5_PYTHON/RSI_BOT/orders.py: -------------------------------------------------------------------------------- 1 | import MetaTrader5 as mt5 2 | import datetime 3 | 4 | 5 | CANDLES_BETWEEN_OPERATIONS = 3 6 | STOPLOSS = 100 7 | TAKEPROFIT = 200 8 | 9 | RSI_TOP = 70 10 | RSI_BOTTOM = 50 11 | 12 | 13 | def open_position(market: str, lotage: float, type_op): 14 | """Function to open a position. 15 | Args: 16 | market (string) 17 | lotage (float) 18 | type_op: Type of the operation 19 | """ 20 | point = mt5.symbol_info(market).point 21 | price = mt5.symbol_info_tick(market).ask 22 | 23 | if type_op == mt5.ORDER_TYPE_BUY: 24 | sl = price-STOPLOSS*point 25 | tp = price+TAKEPROFIT*point 26 | else: 27 | sl = price+STOPLOSS*point 28 | tp = price-TAKEPROFIT*point 29 | 30 | deviation = 20 31 | operation = { 32 | "action": mt5.TRADE_ACTION_DEAL, 33 | "symbol": market, 34 | "volume": lotage, 35 | "type": type_op, 36 | "price": price, 37 | "sl": sl, 38 | "tp": tp, 39 | "deviation": deviation, 40 | "magic": 234000, 41 | "comment": "python script open", 42 | "type_time": mt5.ORDER_TIME_GTC, 43 | "type_filling": mt5.ORDER_FILLING_FOK, 44 | } 45 | 46 | # Sending the buy 47 | result = mt5.order_send(operation) 48 | print("[Thread - orders] 1. order_send(): by {} {} lots at {} with deviation={} points".format(market,lotage,price,deviation)) 49 | if result.retcode != mt5.TRADE_RETCODE_DONE: 50 | print("[Thread - orders] Failed operation: retcode={}".format(result.retcode)) 51 | return None 52 | 53 | def thread_orders(stop_event, data, trading_data): 54 | """Function executed by a thread. It checks if the conditions to open orders 55 | are okay. 56 | Args: 57 | stop_event (thread.Event): Event to stop the thread. 58 | data (dict): Dictionary with candles and the indicator. 59 | trading_data (dict): Dictionary with the lotage and the market. 60 | """ 61 | last_operation_time = 0 62 | ep = datetime.datetime(1970,1,1,0,0,0) 63 | 64 | while data["RSI"] is None: 65 | pass 66 | 67 | print("[INFO]\tOrders running") 68 | 69 | while not stop_event.is_set(): 70 | cur_time = int((datetime.datetime.utcnow()- ep).total_seconds()) 71 | 72 | if data["RSI"][0] < RSI_BOTTOM \ 73 | and cur_time > last_operation_time+trading_data["time_period"]*CANDLES_BETWEEN_OPERATIONS: # Open buy 74 | last_operation_time = cur_time 75 | open_position(trading_data["market"], trading_data["lotage"], mt5.ORDER_TYPE_BUY) 76 | 77 | elif data["RSI"][0] > RSI_TOP \ 78 | and cur_time > last_operation_time+trading_data["time_period"]*CANDLES_BETWEEN_OPERATIONS: # Open sell 79 | last_operation_time = cur_time 80 | open_position(trading_data["market"], trading_data["lotage"], mt5.ORDER_TYPE_SELL) --------------------------------------------------------------------------------