//+------------------------------------------------------------------+ //| SuperCharlie_Aldridge_Dev_v0.mq5| //| HEDGING HORN CAPITAL | //| https://www.hhcapital.com.br | //+------------------------------------------------------------------+ #property copyright "HEDGING HORN CAPITAL" #property link "https://www.hhcapítal.com.br" #property version "DEV_v0" #property description "INDICE" //INDICE //+===================================================================================================================================================================================+ //| 1 - SESSAO DE CABECALHO / ADMISSAO //+===================================================================================================================================================================================+ //+------------------------------------------------------------------+ //| 1.1 - IMPORTACOES | //+------------------------------------------------------------------+ //--- Importacoes #include #include #include #include "MarketBook.mqh" #include //+------------------------------------------------------------------+ //| 1.2 - ENTRADAS DE USUARIO | //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| 1.2.1 - INPUTS DE GERENCIAMENTO DE INVENTARIO | //+------------------------------------------------------------------+ input group "Gerenciamento de Inventário--------------------------------------------------------------------------------------------------" input int inventario = 10; //Inventario máximo q {1}[1, +inf[ input int loteEnvio = 1; //Quantidade por ordem η {1}[1, +inf[ input double premioOperacao = 3; //Premio por trade liquido ρ {0.64}[0.0, 1.0[ input double custoOperacao = 2; //Custo por operacao ζ {1.86}[0.0, 2.0[ input double tickMin = 5; //Tick minimo do ativo Δ {0.5}[0.01, +inf[ //+------------------------------------------------------------------+ //| 1.2.2 - INPUTS DE GERENCIAMENTO DE OPERACOES | //+------------------------------------------------------------------+ input group "Gerenciamento de Operacões---------------------------------------------------------------------------------------------------" input ushort horaInicial = 545; //Horário inicial 09:05 -> Τ0 em minutos {600}[600, 985] input ushort horaFinal = 980; //Horário final 16:20 -> ΤF em minutos {700}[600, 985] input ushort horaEncerramento = 985; //Horário limite de after 16:25 -> ΤP em minutos {705}[600, 990] //+------------------------------------------------------------------+ //| 1.2.3 - INPUTS DE GERENCIAMENTO DE RISCOS | //+------------------------------------------------------------------+ input group "Gerenciamento de Riscos------------------------------------------------------------------------------------------------------" input double alvoFinanceiro = 1000.0; //3º Order Risk M.: Alvo financeiro no dia sup(Χ) input double stopFinanceiro = -1000.0; //3º Order Risk M.: Stop financeiro no dia inf(Χ) /* input group "Análise Quant - Tendência----------------------------------------------------------------------------------------------------" input double pesoAlpha = 0.5; //Peso de alpha α {0.5}[0.00, 1.00[ passo = 0.1 input double pesoBeta = 0.0; //Peso de beta β {0.0}[0.00, 1.00[ passo = 0.1 input double pesoGama = 0.1; //Peso de gama γ {0.1}[0.00, 1.00[ passo = 0.1 input double pesoEpsilon = 0.0; //Peso de epsilon ε {0.0}[0.00, 1.00[ passo = 0.1 input double pesoIota = 1.0; //Peso de iota i {1.0}[0.00, 1.00[ passo = 0.1 input double thresholdResistencia = 3.0; //Threshold de resistencia γ {3.0}[0.0, 3.0[ passo = 0.5 input double qtdBigPlayer = 8; //Tamanho de big player i {8}[2, 20] passo = 2 input double pontoCorteSoma = 0.5; //Ponto de corte da soma Σm {0.5}[0.0, 1.0] passo = 0.1 input int fatorMultTend1 = 1; //Fator multiplicativo da tendencia fτ1 {1}[0, 10[ input int fatorMultTend2 = 2; //Fator multiplicativo da tendencia fτ2 {2}[0, 10[ input int fatorMultTend3 = 3; //Fator multiplicativo da tendencia fτ3 {3}[0, 10[ input int fatorMultTend4 = 4; //Fator multiplicativo da tendencia fτ4 {4}[0, 10[ input int fatorMultTend5 = 5; //Fator multiplicativo da tendencia fτ5 {5}[0, 10[ input int fatorMultTend6 = 6; //Fator multiplicativo da tendencia fτ6 {6}[0, 10[ */ /* input group "Análise Quant - Volatilidade-------------------------------------------------------------------------------------------------" //input double fatorLinVol = 1.5; //Fator linear de log vol σ [1.0, 2.0[ input double pontoCorteDesvio = 0.0; //Ponto de corte do desvio padrao σm {0.0}[0.0, 1.0] passo = 0.1 input int fatorMultDesvio0 = 0; //Fator multiplicativo do desvio fσ0 {0}[0, 5[ input int fatorMultDesvio1 = 1; //Fator multiplicativo do desvio fσ1 {1}[0, 5[ input int fatorMultDesvio2 = 2; //Fator multiplicativo do desvio fσ2 {2}[0, 5[ input int fatorMultDesvio3 = 3; //Fator multiplicativo do desvio fσ3 {3}[0, 5[ */ /* //+------------------------------------------------------------------+ //| 1.2.5 - INPUTS DE ANALISE DE PROBABILIDADES | //+------------------------------------------------------------------+ input group "Análise de Probabilidades - Fill Rates---------------------------------------------------------------------------------------" input int posicaoFila = 350; //Tamanho médio de fila κ {300}[100, 1000[ //input double limite_prob_C = 0.80; //Limite inferior de Fill Rate Λc {0.8}[0.00, 1.00] //double limite_prob_V = limite_prob_C; //Limite inferior de Fill Rate Λv {0.8}[0.00, 1.00] input double fatorCancelamento = 1.0; //Fator de cancelamento χ (1 = 0% de cancelamento/0.9 = 10% de cancelamento) */ //+------------------------------------------------------------------+ //| 1.3 - VARIAVEIS GLOBAIS | //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| 1.3.1 - VARIAVEIS FINANCEIRAS | //+------------------------------------------------------------------+ double midPrice = 0.0; double buyPrice = 0.0; double sellPrice = 0.0; double stopBuyPrice = 0.0; double stopSellPrice = 0.0; double spreadBuy = 0.0; double spreadSell = 0.0; double stopBuySpread = 0.0; double stopSellSpread = 0.0; double qtdBuy = 0.0; double qtdSell = 0.0; double qtdCompraEnviada = 0.0; double qtdVendaEnviada = 0.0; double qtdCompraFilada = 0.0; double qtdVendaFilada = 0.0; double saldoInicialDia = 0.0; double saldoFinalDia = 0.0; double diferencaSaldo = 0.0; int spreadTotal = 0; //+------------------------------------------------------------------+ //| 1.3.2 - VARIAVEIS QUANTITATIVAS | //+------------------------------------------------------------------+ int iBid[4], iAsk[4]; double desvioPadrao = 0.0; double alpha = 0.0; double epsilon = 0.0; double soma = 0.0; double soma0 = 0.0; double soma1 = 0.0; double soma2 = 0.0; double filaMediaBuy = 0.0; double filaMediaSell = 0.0; int medianaLambdaAsk = 0; int medianaLambdaBid = 0; double MA[]; double handlerMA; int q = 0; // "Gerenciamento de Riscos------------------------------------------------------------------------------------------------------" double limiteSupDesvio = 500; //2º Order Risk M.: Limite sup de volatilidade σ {1.5}[0.00, 1.00[ double limiteInfDesvio = 0.00; //2º Order Risk M.: Limite inf de volatilidade σ [0.00, 0.005[ double limiteInfTend1 = 0.00; //2º Order Risk M.: Limite inf de var da media Δμ [0.00, 1.00[ passo = 0.1 double limiteSupTend1 = limiteInfTend1 + 100; //2º Order Risk M.: Limite sup de variacao da media movel Δμ [0.00, 1.00[ passo = 0.1 double fatorBaseStop = 10; //1º Order Risk M.: Stop base ω {5}[2, 10[ double fatorMultStop = 1.0; //1º Order Risk M.: Fator mult de log stop fω {1.0}[1.0, 10.0[ double constLinStop = 5.3; //1º Order Risk M.: Constante de log vol stop cω {5.3} int sleepTime = 0; //T de sleep para pós-stop em ms {0} //+------------------------------------------------------------------+ //| 1.3.3 - VARIAVEIS DE ANALISE QUANTITATIVA | //+------------------------------------------------------------------+ // "Análise Quant - Intervalos---------------------------------------------------------------------------------------------------" //int intervalo_temporal_resistencia = 100; //T resistencia γ temporal em segundos {100} [1, 100[ //int intervalo_lambda_temporal = 10; //T lambda λ temporal em segundos {10}[1, 10[ passo = 1 //int tempoTrade = 90; //T de trade N temporal em segundos {90}[0, 100[ int intervalo_desvio = 500; //Ticks da volatilidade σ atemporal {500}[1, 500[ double periodoMA = 10; //Ticks da media movel μ atemporal {10}[2, 20[ passo = 1 //input int intervalo_resistencia = 3000; //Ticks para resistencias γ atemporal {3000} [2, 3000[ int intervalo_lambda = 50; //Ticks lambda λ atemporal {50}[10, 100[ int k = 1; //Variavel k do modelo Stoikov {1} double gama = 0.5; //Variavel gama y Aversao a risco {0.5} [0, 1] double t = 0.5; //Variavel representando o tempo do dia {0.5} [0, 1] double sigma = 10; //Variavel sigma {10} //+------------------------------------------------------------------+ //| 1.3.4 - VARIAVEIS OPERACIONAIS | //+------------------------------------------------------------------+ int magic = 12345; MqlDateTime horario; MqlDateTime horario_inicio, horario_final, horario_encerramento, horario_atual, horario_comprado, horario_compra; ushort horarioAtual; datetime horaAtual; int diaAtual = 0; CSymbolInfo simbolo; CExpert extExpert; CMarketBook Book(_Symbol); CTrade negocio; MqlBookInfo ArrayBook[]; MqlTick ArrayTick[]; MqlTradeRequest request; MqlTradeResult result; MqlTradeTransaction transaction; MqlTradeCheckResult check_result; string handlerNormalizeDoubleSize; int normalizeDoubleSize; struct CustomMqlTick { int idTick; string tipoEvento; datetime timestamp; int flag; double last; int volume; double bid0; double ask0; int vb0; int va0; int bid1; int ask1; int vb1; int va1; }; //+------------------------------------------------------------------+ //| 1.3.5 - VARIAVEIS DE LOG E FEEDBACK | //+------------------------------------------------------------------+ int arqResultados = 0; int idResultados = 0; string headerRes = "ID_RESULTADO,TIMESTAMP,BID,PRECO_COMPRA,MIDPRICE,PRECO_VENDA,ASK,DESVIO,SOMA,ALPHA,EPSILON,RES_BRUTO,RES_LIQ,K_C,K_V,LAMBDA_C,LAMBDA_V,FILL_C,FILL_V,TRADES,ACERTOS,ERROS"; //+===================================================================================================================================================================================+ //| 2 - SESSAO DE INICIALIZACAO/ATUALIZACAO / IGNICAO //+===================================================================================================================================================================================+ //+------------------------------------------------------------------+ //| 2.1 - FUNCAO DE INICIALIZACAO DO ROBO | //+------------------------------------------------------------------+ int OnInit() { saldoInicialDia = AccountInfoDouble(ACCOUNT_BALANCE); TimeToStruct(TimeCurrent(), horario_atual); diaAtual = horario_atual.day; //Inicializa o Market Book if(!MarketBookAdd(_Symbol)) Print("Falha para inicializar o book"); //Inicializa o ArrayTick if(CopyTicks(Symbol(),ArrayTick,COPY_TICKS_TRADE,0,intervalo_lambda) != -1) ArraySetAsSeries(ArrayTick,true); else Print("Falha para inicializar o ArrayTicks"); handlerNormalizeDoubleSize = DoubleToString(tickMin); handlerNormalizeDoubleSize = StringReplace(handlerNormalizeDoubleSize,".",""); normalizeDoubleSize = (StringLen(handlerNormalizeDoubleSize))-1; handlerMA = iMA(_Symbol,PERIOD_M1,periodoMA,0,MODE_EMA,PRICE_OPEN); ArraySetAsSeries(MA, true); CopyBuffer(handlerMA,0,0,1,MA); Print("TAMANHO DO NORMALIZE DOUBLE: ",normalizeDoubleSize); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| 2.2 - FUNCAO EVENTO TICK / CORACAO | //+------------------------------------------------------------------+ void OnTick() { //Atualiza os ticks e variaveis AtualizaVariaveis(); handlerMA = iMA(_Symbol,PERIOD_M1,periodoMA,0,MODE_EMA,PRICE_OPEN); CopyBuffer(handlerMA,0,0,2,MA); //Chamar o motor if(VerificaHorarioOrdens()) FazTrades(); else if(VerificaHorarioFechamento()) { FechaPosicao(); CancelaOrdensAbertas(); } else return; return; } //+------------------------------------------------------------------+ //| 2.3 - FUNCAO EVENTO BOOK | //+------------------------------------------------------------------+ void OnBookEvent(const string &symbol) { if(MarketBookGet(_Symbol, ArrayBook)) { iBid[0] = Book.InfoGetInteger(MBOOK_BEST_BID_INDEX); iAsk[0] = Book.InfoGetInteger(MBOOK_BEST_ASK_INDEX); iBid[1] = iBid[0] + 1; iAsk[1] = iAsk[0] - 1; iBid[2] = iBid[0] + 2; iAsk[2] = iAsk[0] - 2; } else { // Print("Falha ao obter o Book"); } return; } //+------------------------------------------------------------------+ //| 2.4 - FUNCAO EVENTO TRADE | //+------------------------------------------------------------------+ void OnTrade() { static int previous_open_positions = 0; int current_open_positions = PositionsTotal(); double last_trade_profit = 0.0; if(current_open_positions < previous_open_positions) // a position just got closed: { previous_open_positions = current_open_positions; HistorySelect(TimeCurrent()-300, TimeCurrent()); // 5 minutes ago int All_Deals = HistoryDealsTotal(); if(All_Deals < 1) Print("Some nasty shit error has occurred :s"); // last deal (should be an DEAL_ENTRY_OUT type): ulong temp_Ticket = HistoryDealGetTicket(All_Deals-1); // here check some validity factors of the position-closing deal // (symbol, position ID, even MagicNumber if you care...) last_trade_profit = HistoryDealGetDouble(temp_Ticket , DEAL_PROFIT); if(last_trade_profit < 0) Sleep(sleepTime); // Print("Last Trade Profit : ", DoubleToString(last_trade_profit)); } else if(current_open_positions > previous_open_positions) // a position just got opened: previous_open_positions = current_open_positions; } //+------------------------------------------------------------------+ //| 2.5 - FUNCAO DE DESLIGAMENTO | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //Fecha os arquivos de log // FileClose(arqResultados); // Print("Fechou arquivos de log."); Print("OUTPUT PATH=",TerminalInfoString(TERMINAL_DATA_PATH)); //Falha na desinicializacao printf("Deinit reason: %d", reason); } //+------------------------------------------------------------------+ //| 2.6 - FUNCAO QUE ATUALIZA AS VARIAVEIS IMPORTANTES | //+------------------------------------------------------------------+ void AtualizaVariaveis() { //Atualiza o book e ticks if(!simbolo.RefreshRates()) return; if(MarketBookGet(_Symbol, ArrayBook)) { //Atualiza os indices do topo do book iBid[0] = Book.InfoGetInteger(MBOOK_BEST_BID_INDEX); iAsk[0] = Book.InfoGetInteger(MBOOK_BEST_ASK_INDEX); iBid[1] = iBid[0] + 1; iAsk[1] = iAsk[0] - 1; iBid[2] = iBid[0] + 2; iAsk[2] = iAsk[0] - 2; } else { // Print("Falha ao atualizar o Book"); } return; } //+===================================================================================================================================================================================+ //| 3 - SESSAO DE LOGICA / MOTOR //+===================================================================================================================================================================================+ //+------------------------------------------------------------------+ //| 3.1 - FUNCAO QUE FAZ NEGOCIACOES | //+------------------------------------------------------------------+ void FazTrades() { //Verifica os limites de compra e venda if(VerificaLimites()==0) { //Verifica se atingiu os riscos de VaR (3a camada de riscos} ou volatilidade (2a camada de riscos) if(VerificaRiscos()==true) { //Verifica a projecao instantanea de preco, preenche os precos e stops (1a camada de riscos) if(VerificaPreco()==0) { if(buyPrice > ArrayTick[0].bid) { // CompraMercado(stopBuyPrice, loteEnvio); } else { CompraLimite(buyPrice, stopBuyPrice, loteEnvio); } if(sellPrice < ArrayTick[0].ask) { // VendaMercado(stopSellPrice, loteEnvio); } else { VendaLimite(sellPrice, stopSellPrice, loteEnvio); } //Imprime na tela o feedback dos indicadores Comment("SpreadTotal = " + (sellPrice - buyPrice) + "\n" + "MidPrice = " + midPrice + "\n" + "SellPrice = " + sellPrice + "\n" + "BuyPrice = " + buyPrice + "\n" + "SpreadSell = " + spreadSell + "\n" + "SpreadBuy = " + spreadBuy + "\n" + "StopSellSpead = " + stopSellSpread + "\n" + "StopBuySpread = " + stopBuySpread + "\n" + "DesvioPadrao = " + NormalizeDouble(desvioPadrao,normalizeDoubleSize) + "\n" "Tendencia = " + NormalizeDouble(soma,normalizeDoubleSize)); //Sleep(1000); //Grava os resultados de trade no log // idResultados += 1; // TimeCurrent(horario); // horaAtual = StructToTime(horario); // FileWrite(arqResultados,idResultados + "," + horario.year+"."+horario.mon+"."+horario.day+" "+horario.hour+":"+horario.min+":"+horario.sec + "," + ArrayTick[0].bid + "," + buyPrice + "," + midPrice + "," + sellPrice + "," + ArrayTick[0].ask + "," + desvioPadrao + "," + soma + "," + alpha + "," + epsilon + "," + resultadoHom + "," + resultadoLiqHom + "," + posicaoFilaCompraHom + "," + posicaoFilaVendaHom + "," + lambda_C + "," + lambda_V + "," + probC + "," + probV + "," + tradesHom + "," + acertosHom + "," + errosHom); } } else{} } //se estiver com uma ordem aberta desparidade de compra ou venda else if(VerificaLimites() == 1) { if(OrdensCompraLimitadasAbertas() > OrdensVendaLimitadasAbertas()) { CancelaOrdemAbertaCompra(); } else { CancelaOrdemAbertaVenda(); } } //se não tiver limites de compra e venda else if(VerificaLimites() == 2) { //Verifica se tiver ordem de compra aberta if((OrdensCompraLimitadasAbertas() == 1) || (OrdensVendaLimitadasAbertas() == 1)) { //Verifica se precisa modificar ordens if(VerificaModificaOrdens() == 0) { // CalculaSpreadBuy(); // CalculaSpreadSell(); } } } return; } //+===================================================================================================================================================================================+ //| 4.1 - SESSAO DE HORARIOS / CRONOMETRO //+===================================================================================================================================================================================+ //+------------------------------------------------------------------+ //| 4.1.1 - FUNCAO DE ATUALIZAR HORARIO DE PREGAO | //+------------------------------------------------------------------+ bool VerificaHorarioOrdens() { TimeToStruct(TimeCurrent(), horario_atual); ushort horarioAtual = horario_atual.hour * 60 + horario_atual.min; if((horarioAtual > horaInicial)&&(horarioAtual < horaEncerramento)) { return true; } else return false; } //+------------------------------------------------------------------+ //| 4.1.2 - FUNCAO DE ATUALIZAR HORARIO DE FECHAMENTO | //+------------------------------------------------------------------+ bool VerificaHorarioFechamento() { if(horarioAtual > horaFinal) { return true; } else return false; } //+===================================================================================================================================================================================+ //| 4.2 - SESSAO DE LIMITES / FREIO MOTOR //+===================================================================================================================================================================================+ //+------------------------------------------------------------------+ //| 4.2.1 - FUNCAO QUE VERIFICA OS LIMITES DE COMPRA E VENDA | //+------------------------------------------------------------------+ int VerificaLimites() { if(VerificaLimiteCompra() != VerificaLimiteVenda()) { return 1; } else if ((VerificaLimiteCompra() == 0) && (VerificaLimiteVenda() == 0)) { return 2; } else { return 0; } } //+------------------------------------------------------------------+ //| 4.2.2 - FUNCAO QUE VERIFICA LIMITE DE ORDENS DE COMPRA | //+------------------------------------------------------------------+ int VerificaLimiteCompra() { int limite_Compra = inventario/loteEnvio; limite_Compra = limite_Compra - OrdensCompraLimitadasAbertas() - PosicoesCompraAbertas(); if(limite_Compra > 0) return 1; else return 0; } //+------------------------------------------------------------------+ //| 4.2.3 - FUNCAO QUE VERIFICA LIMITE DE ORDENS VENDA | //+------------------------------------------------------------------+ int VerificaLimiteVenda() { int limite_Venda = inventario/loteEnvio; limite_Venda = limite_Venda - OrdensVendaLimitadasAbertas() - PosicoesVendaAbertas(); if(limite_Venda > 0) return 1; else return 0; } //+------------------------------------------------------------------+ //| 4.2.4 - FUNCAO QUE VERIFICA LIMITE EM VOLUME DE ORDENS DE COMPRA | //+------------------------------------------------------------------+ int VerificaLimiteVolumeCompra() { int limite = loteEnvio; int returnCode = 1; if(qtdCompraEnviada == 0) return 0; if(qtdCompraEnviada == limite) return 1; return returnCode; } //+------------------------------------------------------------------+ //| 4.2.5 - FUNCAO QUE VERIFICA LIMITE EM VOLUME DE ORDENS VENDA | //+------------------------------------------------------------------+ int VerificaLimiteVolumeVenda() { int limite = loteEnvio; int returnCode = 1; if(qtdVendaEnviada == 0) return 0; if(qtdVendaEnviada == limite) return 1; return returnCode; } //+--------------------------------------------------------------------------+ //| 4.2.6 - FUNCAO DE CALCULO DO NUMERO DE ORDENS COMPRA LIMITADAS ABERTAS | //+--------------------------------------------------------------------------+ int OrdensCompraLimitadasAbertas() { int ordens = 0; //Percorre todas as ordens for(int i=OrdersTotal()-1; i>=0; i--) { ulong ticket = OrderGetTicket(i); string symbol = OrderGetString(ORDER_SYMBOL); ulong magicEA = OrderGetInteger(ORDER_MAGIC); //Verifica para cada ordem, se eh do simbolo corrente e do mesmo robo if((symbol == _Symbol) && (magicEA == magic)) { //Verifica se a ordem eh do tipo buy limit if(OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY_LIMIT) { ordens = ordens + 1; qtdCompraEnviada = OrderGetDouble(ORDER_VOLUME_INITIAL); qtdCompraFilada = qtdCompraEnviada - OrderGetDouble(ORDER_VOLUME_CURRENT); } } } return ordens; } //+--------------------------------------------------------------------------+ //| 4.2.7 - FUNCAO DE CALCULO DO NUMERO DE ORDENS VENDA LIMITADAS ABERTAS | //+--------------------------------------------------------------------------+ int OrdensVendaLimitadasAbertas() { int ordens = 0; //Percorre todas as ordens for(int i=OrdersTotal()-1; i>=0; i--) { ulong ticket = OrderGetTicket(i); string symbol = OrderGetString(ORDER_SYMBOL); ulong magicEA = OrderGetInteger(ORDER_MAGIC); //Verifica para cada ordem, se eh do simbolo corrente e do mesmo robo if((symbol == _Symbol) && (magicEA == magic)) { //Verifica se a ordem eh do tipo sell limit if(OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_SELL_LIMIT) { ordens = ordens + 1; qtdVendaEnviada = OrderGetDouble(ORDER_VOLUME_INITIAL); qtdVendaFilada = qtdVendaEnviada - OrderGetDouble(ORDER_VOLUME_CURRENT); } } } return ordens; } //+------------------------------------------------------------------+ //| 4.2.* - FUNCAO DE CALCULO DO q | //+------------------------------------------------------------------+ void AtualizaQuantidade() { q = 0; q = PosicoesCompraAbertas() - PosicoesVendaAbertas(); return; } //+------------------------------------------------------------------+ //| 4.2.8 - FUNCAO DE VERIFICACAO DE POSICAO DE COMPRA | //+------------------------------------------------------------------+ int PosicoesCompraAbertas() { int positions = 0; //Percorre todas as posicoes for(int i=PositionsTotal()-1; i>=0; i--) { ulong ticket = PositionGetTicket(i); string symbol = PositionGetString(POSITION_SYMBOL); ulong magicEA = PositionGetInteger(POSITION_MAGIC); //Verifica para cada posicao, se eh do simbolo corrente e do mesmo robo if((symbol == _Symbol) && (magicEA == magic)) { //Verifica se a posicao eh do tipo buy if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) { positions = positions + 1; } } } return positions; } //+------------------------------------------------------------------+ //| 4.2.9 - FUNCAO DE VERIFICACAO DE POSICAO DE VENDAS | //+------------------------------------------------------------------+ int PosicoesVendaAbertas() { int positions = 0; //Percorre todas as posicoes for(int i = PositionsTotal()-1; i>=0; i--) { ulong ticket = PositionGetTicket(i); string symbol = PositionGetString(POSITION_SYMBOL); ulong magicEA = PositionGetInteger(POSITION_MAGIC); //Verifica para cada posicao, se eh do simbolo corrente e do mesmo robo if((symbol == _Symbol) && (magicEA == magic)) { //Verifica se a posicao eh do tipo sell if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) { positions = positions + 1; } } } return positions; } //+---------------------------------------------------------------------------+ //| 4.2.10 - FUNCAO QUE VERIFICA A NECESSIDADE DE MODIFICAR ORDENS ENVIADAS | //+---------------------------------------------------------------------------+ int VerificaModificaOrdens() { return 0; } //+===================================================================================================================================================================================+ //| 4.3 - SESSAO DE RISCOS DE MERCADO/PORTFOLIO / FREIO DE MAO //+===================================================================================================================================================================================+ //+------------------------------------------------------------------+ //| 4.3.1 - FUNCAO QUE VERIFICA OS RISCOS DE MERCADO | //+------------------------------------------------------------------+ bool VerificaRiscos() { const int n = intervalo_desvio; double precos[]; double diferencaMA = 0.0; ArrayResize(precos, n); GetPrecosPassados(precos); desvioPadrao = MathStandardDeviation(precos); diferencaMA = MA[0] - MA[1]; saldoFinalDia = AccountInfoDouble(ACCOUNT_BALANCE); if(diaAtual == horario_atual.day) { diferencaSaldo = saldoFinalDia - saldoInicialDia; } else { Print("Dia anterior: ",diaAtual," Resultado: ", diferencaSaldo); diaAtual += 1; saldoInicialDia = AccountInfoDouble(ACCOUNT_BALANCE); diferencaSaldo = 0.0; } if(diferencaMA < 0) diferencaMA = -1*diferencaMA; //Verifica se atingiu o 5% VAR - 3º Order Risk Management if((diferencaSaldo < alvoFinanceiro) && (diferencaSaldo > stopFinanceiro)) { //Verifica se atingiu o volatility cutouts - 2º Order Risk Management if((desvioPadrao >= limiteInfDesvio) && (desvioPadrao <= limiteSupDesvio)) { //Verifica se atingiu o trends cutouts - 2º Order Risk Management if((diferencaMA >= limiteInfTend1) && (diferencaMA <= limiteSupTend1)) { return true; } else return false; } else return false; } else return false; } //+===================================================================================================================================================================================+ //| 5 - SESSAO DE PRECOS / DIRECAO //+===================================================================================================================================================================================+ //+------------------------------------------------------------------+ //| 5.1 - FUNCAO QUE VERIFICA O PRECO NAQUELE INSTANTE | //+------------------------------------------------------------------+ int VerificaPreco() { //Define os spreads das ordens const int n = intervalo_desvio; double precos[]; double diferencaMA = 0.0; ArrayResize(precos, n); GetPrecosPassados(precos); desvioPadrao = MathStandardDeviation(precos); AtualizaQuantidade(); // double t = 0.0; // t = (double)(horaEncerramento - horarioAtual)/(double)(horaEncerramento - horaInicial); // midPrice = ArrayTick[0].last - q*gama*pow(desvioPadrao,2)*(horaEncerramento - horarioAtual); midPrice = ArrayTick[0].last - q*gama*pow(sigma,2)*(t); spreadBuy = (CalculaSpreadTotal() * tickMin) /2; spreadSell = (CalculaSpreadTotal() * tickMin) /2; stopBuySpread = CalculaStopBuy(); stopSellSpread = CalculaStopSell(); // Print("Last: ", ArrayTick[0].last, " Reservation price: ", midPrice, " SpreadTotal: ", CalculaSpreadTotal()); //Preenche os precos de envio das ordens buyPrice = MathRound(midPrice - spreadBuy - 0.1); sellPrice = MathRound(midPrice + spreadSell + 0.1); stopBuyPrice = buyPrice + stopBuySpread; stopSellPrice = sellPrice + stopSellSpread; return 0; } //+------------------------------------------------------------------+ //| 5.* - FUNCAO QUE CALCULA SPREAD TOTAL | //+------------------------------------------------------------------+ int CalculaSpreadTotal() { spreadTotal = 0; double f1 = 0.0; double f2 = 0.0; double div = 0.0; // double t = 0.0; // t = (double)(horaEncerramento - horarioAtual)/(double)(horaEncerramento - horaInicial); // spreadTotal = (gama * pow(desvioPadrao,2) * (horaEncerramento - horarioAtual)) + ((2/(double)gama) * log1p(1+((double)gama/(double)k))); f1 = (gama * pow(sigma,2) * t); div = (double)gama/(double)k; f2 = (2/(double)gama) * log1p(div); spreadTotal = f1 + f2; // Print("f1: ", f1, " f2: ", f2, " div: ", div); return spreadTotal; } //+------------------------------------------------------------------+ //| 5.4 - FUNCAO QUE CALCULA SPREAD DE STOP DE COMPRA | //+------------------------------------------------------------------+ double CalculaStopBuy() { const int n = intervalo_desvio; double precos[]; ArrayResize(precos, n); double delta = - fatorBaseStop * tickMin; double volatilidade = 0.0; double spread = 0.0; GetPrecosPassados(precos); desvioPadrao = MathStandardDeviation(precos); volatilidade = - ((MathLog1p(desvioPadrao * fatorMultStop) + constLinStop) * tickMin); volatilidade = NormalizeDouble(volatilidade,0); spread = delta; return spread; } //+------------------------------------------------------------------+ //| 5.5 - FUNCAO QUE CALCULA SPREAD DE STOP DE VENDA | //+------------------------------------------------------------------+ double CalculaStopSell() { const int n = intervalo_desvio; double precos[]; ArrayResize(precos, n); double delta = fatorBaseStop * tickMin; double tendencia = 0.0; double volatilidade = 0.0; double spread = 0.0; GetPrecosPassados(precos); desvioPadrao = MathStandardDeviation(precos); volatilidade = ((MathLog1p(desvioPadrao * fatorMultStop) + constLinStop) * tickMin); volatilidade = NormalizeDouble(volatilidade,0); spread = delta; return spread; } //+------------------------------------------------------------------+ //| 5.6 - FUNCAO QUE CALCULA A MEDIA DE PRECOS | //+------------------------------------------------------------------+ void GetPrecosPassados(double &precos[]) { if(CopyTicks(Symbol(),ArrayTick,COPY_TICKS_TRADE,0,intervalo_desvio) != -1) { ArraySetAsSeries(ArrayTick,true); for(int i=0;i=0;i--){ ulong ticket = OrderGetTicket(i); negocio.OrderDelete(ticket); Print("Cancelou ordem aberta"); } return; } //+------------------------------------------------------------------+ //| 8.7 - FUNCAO DE FECHAMENTO DE ORDENS EXECUTADAS | //+------------------------------------------------------------------+ void FechaTrade() { double qtd = loteEnvio; if(!PositionSelect(_Symbol)) return; long tipoPosicao = PositionGetInteger(POSITION_TYPE); if(tipoPosicao == POSITION_TYPE_BUY) { negocio.Sell(qtd, NULL, 0, 0, 0, "Saida por fechamento Trade"); } else if(tipoPosicao==POSITION_TYPE_SELL) { negocio.Buy(qtd, NULL, 0, 0, 0, "Saida por fechamento Trade"); } return; } //+------------------------------------------------------------------+ //| 8.8 - FUNCAO DE FECHAMENTO DE TODAS AS POSICOES | //+------------------------------------------------------------------+ void FechaPosicao() { double qtd = loteEnvio; if(!PositionSelect(_Symbol)) return; long tipoPosicao = PositionGetInteger(POSITION_TYPE); if(tipoPosicao == POSITION_TYPE_BUY) { negocio.Sell(qtd, NULL, 0, 0, 0, "Saida por fechamento do dia"); } else if(tipoPosicao==POSITION_TYPE_SELL) { negocio.Buy(qtd, NULL, 0, 0, 0, "Saida por fechamento do dia"); } return; } //+------------------------------------------------------------------+ //| 8.9 - FUNCAO DE CANCELAMENTO DE ORDEM PENDENTE DE COMPRA | //+------------------------------------------------------------------+ void CancelaOrdemAbertaCompra() { //Percorre todas as ordens for(int i=OrdersTotal()-1; i>=0; i--) { ulong ticket = OrderGetTicket(i); string symbol = OrderGetString(ORDER_SYMBOL); ulong magicEA = OrderGetInteger(ORDER_MAGIC); //Verifica para cada ordem, se eh do simbolo corrente e do mesmo robo if((symbol == _Symbol) && (magicEA == magic)) { //Verifica se a ordem eh do tipo buy limit if(OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY_LIMIT) { negocio.OrderDelete(ticket); Print("Cancelou ordem aberta de compra"); break; } } } return; } //+------------------------------------------------------------------+ //| 8.9 - FUNCAO DE CANCELAMENTO DE ORDEM PENDENTE DE VENDA | //+------------------------------------------------------------------+ void CancelaOrdemAbertaVenda() { //Percorre todas as ordens for(int i=OrdersTotal()-1; i>=0; i--) { ulong ticket = OrderGetTicket(i); string symbol = OrderGetString(ORDER_SYMBOL); ulong magicEA = OrderGetInteger(ORDER_MAGIC); //Verifica para cada ordem, se eh do simbolo corrente e do mesmo robo if((symbol == _Symbol) && (magicEA == magic)) { //Verifica se a ordem eh do tipo sell limit if(OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_SELL_LIMIT) { negocio.OrderDelete(ticket); Print("Cancelou ordem aberta de venda"); break; } } } return; } //+===================================================================================================================================================================================+ //| FIM DO PROGRAMA //+===================================================================================================================================================================================+