Você está na página 1de 10

(https://www.quantnews.com) (https://www.quantnews.com/feed/) (https://twitter.

com/QuantNews_com)

Negociação quantitativa, negociação algorítmica,


negociação de sistema, negociação de robôs e muito
mais.

ARTIGOS (HTTPS://WWW.QUANTNEWS.COM/ARTICLES/)

MANCHETES (/FEED_TYPE/HEADLINE/)

PESQUISA (HTTPS://WWW.QUANTNEWS.COM/RESEARCH/)
NEW

RECURSOS (HTTPS://WWW.QUANTNEWS.COM/RESOURCES/) NEGOCIAÇÃO DE CFD

Pesquisar…

ACESSE DADOS AO
VIVO GRATUITOS
VIA API REST

Página inicial (https://www.quantnews.com/) » Artigos


(https://www.quantnews.com/articles/) » Algo Trading com API REST e
(https://www.quantnews.com/acti
Python - Desenvolvendo uma estratégia de tendência de crossover da
rest-api-easy-123/)
SMA

Algo Trading com API REST NOVO SEMINÁRIO


ON-LINE:
e Python - Desenvolvendo INTRODUÇÃO ÀS

uma estratégia de ESTRATÉGIAS


AUTOMATIZADAS
tendências SMA Crossover
11 de janeiro de 2019 Por Rob Pasche
(https://www.quantnews.com/author/rpasche/)
(https://www.quantnews.com/intro
automated-strategies/)
/
(Para baixar uma cópia já concluída da estratégia Python desenvolvida
CATEGORIAS
neste guia, visite nosso GitHub
(https://github.com/fxcm/RestAPI/blob/master/Python-Live-Trading-
Examples/SMA%20Crossover%20Strategy.py) .) Peça do colaborador
(https://www.quantnews
Neste artigo, codificaremos uma estratégia de crossover Average Moving piece/) (2)
Average (SMA) de barra fechada usando Python e a API Rest da FXCM. Entrevista
Essa estratégia comprará quando o Fast SMA cruzar com o Slow SMA e (https://www.quantnews
venderá quando o Fast SMA cruzar com o Slow SMA. Os parâmetros (21)
incluirão símbolo / instrumento, período de tempo, Períodos SMA rápidos e
Boletim De Notícias
lentos, fechamento do interruptor de sinal oposto, tamanho do lote e
(https://www.quantnews
distância de parada / limite.
(11)
Gravação
ETAPA 1. FAÇA O DOWNLOAD DO ARQUIVO "PYTHON
(https://www.quantnews
STRATEGY TEMPLATE.PY". (20)
Se você já possui uma cópia do “Python Strategy Template.py”, pode ir
Pesquisa
para a Etapa 2. Em um artigo (https://www.quantnews.com/algo-
(https://www.quantnews
trading-with-rest-api-and-python-part-5/) anterior , desenvolvemos um
(26)
modelo de estratégia que facilita muito o desenvolvimento futuro da
Seminário
estratégia. Recomendamos que os leitores consultem este artigo pelo
(https://www.quantnews
menos uma vez para entender como ele funciona.
(3)

Você também pode fazer o download do nosso modelo no GitHub Estratégia


(https://github.com/fxcm) . (https://www.quantnews
(9)

ETAPA 2. IMPORTE A LÓGICA SMA DO PYTI. Tutorial


Em nosso modelo, já importamos os módulos fxcmpy, time e datetime. (https://www.quantnews
Para essa estratégia, também precisamos importar a lógica Média Móvel (17)
Simples usando um módulo chamado pyti Sem categoria
(https://github.com/kylejusticemagnuson/pyti) . Se você nunca usou o (https://www.quantnews
pyti antes, verifique se este módulo está instalado em sua máquina, (6)
abrindo um prompt de comando e executando o comando “pip install pyti”.
Seminário
A captura de tela abaixo mostra que eu já tenho o pyti instalado.
(https://www.quantnews
on- line
(https://www.quantnews
(7)

WEBINAR: CRIANDO
UM SISTEMA ALGO

(https://www.quantnews.com/wp-
content/uploads/2018/11/pyticommand.png)
/
# hon
pyt Returns true if stream1 crossed over stream2 in most rec
def crossesOver(stream1, stream2): Tweets by
@FXCM_MarketData
# If stream2 is an int or float, check if stream1 has
if isinstance(stream2, int) or isinstance(stream2, flo
if stream1[len(stream1)-1] <= stream2:
FXCM Market D
@FXCM_Market
return False
else:
#USDJPY SSI is
at 1.98
if stream1[len(stream1)-2] > stream2:
return False
Risk Warning:
elif stream1[len(stream1)-2] < stream2:
Losses can
return True
exceed deposits.
else: Disclaimer: Past
x = 2 performance is
while stream1[len(stream1)-x] == stream2: not indicative of
x = x + 1 future results.
if stream1[len(stream1)-x] < stream2:
return True
else:
return False
# Check if stream1 has crossed over stream2
else:
if stream1[len(stream1)-1] <= stream2[len(stream2)
return False
else: Jul 9, 2020

if stream1[len(stream1)-2] > stream2[len(strea


return False
elif stream1[len(stream1)-2] < stream2[len(str FXCM Market D
return True @FXCM_Market
else: #USDCAD SSI is
x = 2 at 1.05
while stream1[len(stream1)-x] == stream2[l
x = x + 1 Risk Warning:
if stream1[len(stream1)-x] < stream2[len(s Losses can
return True exceed deposits.
else:
Disclaimer: Past
performance is
return False
not indicative of
future results.
The crossesUnder() Function

This function is the mirror opposite of crossesOver(). It returns a True value


if the first data stream crossed under the second; returns false if it did not
crossunder.

/
# hon
pyt Returns true if stream1 crossed under stream2 in most re
def crossesUnder(stream1, stream2):
# If stream2 is an int or float, check if stream1 has
if isinstance(stream2, int) or isinstance(stream2, flo
if stream1[len(stream1)-1] >= stream2:
return False
else:
if stream1[len(stream1)-2] < stream2:
return False
elif stream1[len(stream1)-2] > stream2:
return True
else:
x = 2
while stream1[len(stream1)-x] == stream2:
x = x + 1
if stream1[len(stream1)-x] > stream2:
return True
else:
return False
# Check if stream1 has crossed under stream2
else:
if stream1[len(stream1)-1] >= stream2[len(stream2)
return False
else:
if stream1[len(stream1)-2] < stream2[len(strea
return False
elif stream1[len(stream1)-2] > stream2[len(str
return True
else:
x = 2
while stream1[len(stream1)-x] == stream2[l
x = x + 1
if stream1[len(stream1)-x] > stream2[len(s
return True
else:
return False

The countOpenTrades() Function

The final utility function we will add is the counOpenTrades() function. As


the name suggests, this function counts how many open positions we have
in our account for the strategy’s symbol. Calling countOpenTrades(“B”)
returns the number of open buy trades/tickets, countOpenTrades(“S”)
returns the number of open sell trades/tickets, countOpenTrades() returns
the number of all open trades/tickets.

/
# hon
pyt Returns number of Open Positions for symbol in the direc
def countOpenTrades(BuySell=None):
openpositions = con.get_open_positions(kind='list')
isbuy = True
counter = 0
if BuySell == "S":
isbuy = False
for position in openpositions:
if position['currency'] == symbol:
if BuySell is None or position['isBuy'] == isb
counter+=1
return counter

STEP 5. WRITING OUR TRADING LOGIC INSIDE THE UPDATE()


FUNCTION
The Update() function is processed every time a candle/bar closes and will
determine when we open a trade as well as when they are closed. The first
thing we want to do is calculate our Fast SMA and Slow SMA streams. We
can easily do this by calling our sma calculation module (that we imported
via pyti). We will also print the most recent close price and SMA values so
we can visually confirm that our strategy is updating properly.

# hon
pyt This function is run every time a candle closes
def Update():
print(str(dt.datetime.now()) + " " + timeframe + "

# Calculate Indicators
iFastSMA = sma(pricedata['bidclose'], fast_sma_periods
iSlowSMA = sma(pricedata['bidclose'], slow_sma_periods

# Print Price/Indicators
print("Close Price: " + str(pricedata['bidclose'][len(
print("Fast SMA: " + str(iFastSMA[len(iFastSMA)-1]))
print("Slow SMA: " + str(iSlowSMA[len(iSlowSMA)-1]))

Next, we need to code our entry logic. If the Fast SMA crosses over the
Slow SMA, we buy. If the Fast SMA crosses under the Slow SMA, we sell.
We will use our crossesOver(), crossesUnder() and enter() functions. Also,
note that we want to exit opposing positions if close_on_opposing_signal
equals True and an opposing position exists. We use the
countOpenTrades() function to see if we have any opposing positions and
the exit() function to close them out if we do.

/
Agora precisamos importar a lógica do SMA para o nosso código.
Adicionaremos isso logo abaixo de nossas outras declarações de Best Practices fo
importação. 00:00 59:30

import
python fxcmpy
import time
SEMINÁRIO ON-
import datetime as dt
from pyti.simple_moving_average import simple_moving_avera LINE: USANDO
DADOS PREMIUM

ETAPA 3. ADICIONAR PARÂMETROS DO USUÁRIO


Algo Trading | Us
Precisamos adicionar 6 parâmetros adicionais para fornecer à nossa
estratégia de crossover da SMA todas as informações necessárias. Para
nossa lógica SMA, precisaremos de períodos SMA rápidos e lentos, além
de um comutador chamado “close_on_opposing_signal” que permitirá
escolher como queremos que a estratégia lide com as negociações
quando ocorrer um sinal oposto. Também queremos adicionar parâmetros
00:00 57:06
para tamanho de negociação, distância de stoploss e distância limite.

######
python USER PARAMETERS ######
token = 'INSERT-TOKEN-HERE' INTRODUÇÃO AO
symbol = 'GBP/USD'
SEMINÁRIO ON-
timeframe = "m1" # (m1,m5,m15,m30,H1,H2,H3,H4,H6,H8,D1,W1,
fast_sma_periods = 10 LINE DE
slow_sma_periods = 20 APRENDIZADO DE
close_on_opposing_signal = True
amount = 1 MÁQUINA
stop = -10
limit = 30
#############################
Algo Trading | Int

ETAPA 4. ADICIONE AS FUNÇÕES ENTER (), EXIT (),


CROSSOVER (), CROSSESUNDER () E COUNTOPENTRADES ().
Antes de escrevermos nossa lógica de negociação dentro da função
00:00 01:16:34
Update (), há algumas funções de 'utilidade' que precisamos adicionar ao
nosso código que tornarão a escrita da lógica da nossa estratégia muito
mais simples.
VÍDEO DO WEBINAR
A função enter () SOBRE NEGOCIAÇÃO
ALGO: PT 3
Primeiro, vamos adicionar a função enter (). Quando chamada, a função
enter () coloca uma ordem de mercado. Para fazer um pedido de compra
no mercado, use enter ("B"). Para uma ordem de mercado de venda, use
enter ("S"). A função já está codificada para aceitar os parâmetros de
quantidade, parada e limite que criamos em nossa seção Parâmetros do
usuário.

/
# hon
pyt TRADING LOGIC
# If Fast SMA crosses over Slow SMA, Open Buy Trade
if crossesOver(iFastSMA,iSlowSMA):
print(" BUY SIGNAL!")
if close_on_opposing_signal and countOpenTrades("S") >
print(" Closing Sell Trade(s)...")
exit("S")
print(" Opening Buy Trade...")
enter("B")
# If Fast SMA crosses under Slow SMA, Open Sell Trade
if crossesUnder(iFastSMA,iSlowSMA):
print(" SELL SIGNAL!")
if close_on_opposing_signal and countOpenTrades("B") >
print(" Closing Buy Trade(s)...")
exit("B")
print(" Opening Sell Trade...")
enter("S")

print(str(dt.datetime.now()) + " " + timeframe + " Upd

STEP 6. RUN OUR STRATEGY INSIDE OUR COMMAND


CONSOLE.
The last step is to run our strategy inside our command console. The
python file we created I saved on to my desktop, so I execute the strategy
by calling it like this:

(https://www.quantnews.com/wp-content/uploads/2019/01/SMA-
Crossover-Strategy-Command-Start.png)

The strategy is now up and running and will open and close trades per our
rules!

/
(https://www.quantnews.com/wp-content/uploads/2019/01/SMA-
Crossover-Strategy-Running.png)

WHAT NEXT?
This SMA Crossover strategy is a classic trend trading strategy, but there
are definitely ways it can be expanded upon and improved. Please edit and
make this strategy your own! Also, make sure to check out our other
Python strategies we have available at https://github.com/fxcm/RestAPI
(https://github.com/fxcm/RestAPI)

Risk Warning: The FXCM Group does not guarantee accuracy and will not accept
liability for any loss or damage which arise directly or indirectly from use of or
reliance on information contained within the webinars. The FXCM Group may
provide general commentary which is not intended as investment advice and
must not be construed as such. FX/CFD trading carries a risk of losses in excess
of your deposited funds and may not be suitable for all investors. Please ensure
that you fully understand the risks involved.

Quantnews is the education website of FXCM Group. Quantnews will not accept liability for any loss or damage including,
without limitation, to any loss of profit which may arise directly or indirectly from use of or reliance on such information.
Quantnews assumes no liability for errors, inaccuracies or omissions; does not warrant the accuracy, completeness of
information, text, graphics, links or other items contained within these materials. Any opinions, news, research, analyses,
prices, other information, or links to third-party sites contained on this website are provided as general market
commentary and do not constitute investment advice. The market commentary has not been prepared in accordance with
legal requirements designed to promote the independence of investment research, and it is therefore not subject to any
prohibition on dealing ahead of dissemination. Links to third-party sites are provided for your convenience. Such sites are
not within our control and Quantnews does not endorse nor is responsible for the security, content or availability of the
information contained within third-party sites.

Market Opinions: Any opinions, news, research, analyses, prices, other information, or links to third-party sites contained
on this website are provided as general market commentary and do not constitute investment advice. The market
commentary has not been prepared in accordance with legal requirements designed to promote the independence of
investment research, and it is therefore not subject to any prohibition on dealing ahead of dissemination. Quantnews will
/
not accept liability for any loss or damage including, without limitation, to any loss of profit which may arise directly or
indirectly from use of or reliance on such information. Quantnews assumes no liability for errors, inaccuracies or omissions;
does not warrant the accuracy, completeness of information, text, graphics, links or other items contained within these
materials.

© Copyright 2020 Quantnews.com

/
# hon
pyt This function places a market order in the direction Buy 00:00 01:26:36
def enter(BuySell): Algo Trading We
direction = True;
if BuySell == "S":
direction = False; VÍDEO DO
try: SEMINÁRIO ON-
opentrade = con.open_trade(symbol=symbol, is_buy=d
except:
LINE ALGO
print(" Error Opening Trade.") TRADING: PT 2
else:
print(" Trade Opened Successfully.")
Algo Trading We

A função exit ()

Em seguida, vamos adicionar a função exit (). Funciona de maneira muito


semelhante à função enter. Para encerrar todas as operações de compra
do nosso símbolo negociado, ligue para exit ("B"). Para encerrar todas as
00:00 01:20:38
operações de venda do nosso símbolo negociado, ligue para exit ("S"). Se
queremos fechar negócios de compra e venda, chamamos exit () sem
argumentos.
VÍDEO DO WEBINAR
# hon
pyt This function closes all positions that are in the direc SOBRE NEGOCIAÇÃO
def exit(BuySell=None):
ALGO: PT 1
openpositions = con.get_open_positions(kind='list')
isbuy = True
if BuySell == "S":
Algo Trading We
isbuy = False
for position in openpositions:
if position['currency'] == symbol:
if BuySell is None or position['isBuy'] == isb
print(" Closing tradeID: " + position['t
try:
closetrade = con.close_trade(trade_id=
00:00 01:17:57
except:
print(" Error Closing Trade.")
else:
print(" Trade Closed Successfully.") SIGA
@FXCM_MARKETDATA
A função crossesOver ()

The next function is a workhorse for many different strategies.


crossesOver() checks to see if one data stream’s value crossed over
another data stream’s value in the previous candle/bar. When we execute
the crossesOver() function with Fast SMA’s data stream as stream1 and the
Slow SMA’s data stream as stream2, the function will return a True value if
the Fast SMA crossed over the Slow SMA in the prevous candle. It will
return false if it did not crossover.

Você também pode gostar