Skip to content

Instantly share code, notes, and snippets.

@juniorpb
Created February 16, 2023 14:34
Show Gist options
  • Save juniorpb/55de9e5fd6959ed645af58e21ec8cec5 to your computer and use it in GitHub Desktop.
Save juniorpb/55de9e5fd6959ed645af58e21ec8cec5 to your computer and use it in GitHub Desktop.
Estratégia de scalping usando a API [Chat GPT]
'''
faça um código implementando uma Estratégia de scalping usando a API da binace usando RSI e o MACD para identificar
condições de sobrecompra e sobrevenda alavancado em 20x e, em seguida,
abra uma posição na direção oposta ao movimento. Feche a posição com lucro após alguns minutos ou segundos.
'''
import pandas as pd
import numpy as np
import talib
from binance.client import Client
import time
# Configurar a API da Binance
api_key = 'SUA_API_KEY'
api_secret = 'SUA_API_SECRET'
client = Client(api_key, api_secret)
# Definir as configurações da estratégia de scalping
symbol = 'BTCUSDT'
leverage = 20
quantity = 0.001
stop_loss_distance = 0.01
take_profit_distance = 0.02
interval = Client.KLINE_INTERVAL_1MINUTE
# Definir a janela de tempo para calcular o RSI e o MACD
rsi_window = 14
macd_fast = 12
macd_slow = 26
macd_signal = 9
# Definir o número de ticks para manter a posição aberta
tick_limit = 10
# Iniciar a posição
position = None
ticks = 0
while True:
# Coletar dados históricos do BTCUSDT
klines = client.futures_historical_klines(symbol=symbol, interval=interval, start_str='1 day ago UTC')
# Converter os dados em um dataframe
df = pd.DataFrame(klines, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_asset_volume', 'number_of_trades', 'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore'])
# Converter as colunas em números de ponto flutuante
df[['open', 'high', 'low', 'close', 'volume']] = df[['open', 'high', 'low', 'close', 'volume']].astype(float)
# Definir a coluna timestamp como índice do dataframe e convertê-la em um objeto datetime
df = df.set_index('timestamp')
df.index = pd.to_datetime(df.index, unit='ms')
# Calcular o RSI e o MACD
rsi = talib.RSI(df['close'], timeperiod=rsi_window)
macd, macdsignal, macdhist = talib.MACD(df['close'], fastperiod=macd_fast, slowperiod=macd_slow, signalperiod=macd_signal)
# Obter o preço atual
current_price = df['close'][-1]
# Verificar se a posição está aberta
if position is not None:
# Verificar se a posição deve ser fechada
if position['type'] == 'long' and ticks >= tick_limit:
# Fechar a posição
client.futures_create_order(symbol=symbol, side=Client.SIDE_SELL, type=Client.ORDER_TYPE_MARKET, quantity=quantity)
position = None
ticks = 0
print('Posição longa fechada com lucro!')
time.sleep(10)
elif position['type'] == 'short' and ticks >= tick_limit:
# Fechar a posição
client.futures_create_order(symbol=symbol, side=Client.SIDE_BUY, type=Client.ORDER_TYPE_MARKET, quantity=quantity)
position = None
ticks = 0
print('Posição curta fechada com lucro!')
time.sleep(10)
else:
# Verificar se devemos abrir uma posição longa
if rsi[-1] < 30 and macd[-1] > macdsignal[-1]:
# Calcular o stop loss e o take profit
stop_loss = current_price - (current_price * stop_loss_distance)
take_profit = current_price + (current_price * take_profit_distance)
# Abrir a posição longa
order = client.futures_create_order(symbol=symbol, side=Client.SIDE_BUY, type=Client.ORDER_TYPE_MARKET, quantity=quantity, leverage=leverage)
# Definir a posição e o número de ticks
position = {'type': 'long', 'entry_price': order['avgPrice'], 'stop_loss': stop_loss, 'take_profit': take_profit}
ticks = 0
print('Posição longa aberta!')
time.sleep(10)
# Verificar se devemos abrir uma posição curta
elif rsi[-1] > 70 and macd[-1] < macdsignal[-1]:
# Calcular o stop loss e o take profit
stop_loss = current_price + (current_price * stop_loss_distance)
take_profit = current_price - (current_price * take_profit_distance)
# Abrir a posição curta
order = client.futures_create_order(symbol=symbol, side=Client.SIDE_SELL, type=Client.ORDER_TYPE_MARKET, quantity=quantity, leverage=leverage)
# Definir a posição e o número de ticks
position = {'type': 'short', 'entry_price': order['avgPrice'], 'stop_loss': stop_loss, 'take_profit': take_profit}
ticks = 0
print('Posição curta aberta!')
time.sleep(10)
# Verificar se a posição está aberta e atualizar o stop loss e o take profit
if position is not None:
if position['type'] == 'long':
position['stop_loss'] = max(position['stop_loss'], current_price - (current_price * stop_loss_distance))
position['take_profit'] = min(position['take_profit'], current_price + (current_price * take_profit_distance))
else:
position['stop_loss'] = min(position['stop_loss'], current_price + (current_price * stop_loss_distance))
position['take_profit'] = max(position['take_profit'], current_price - (current_price * take_profit_distance))
# Verificar se a posição está aberta e atualizar o número de ticks
if position is not None:
ticks += 1
# Aguardar 5 segundos antes de coletar novos dados
time.sleep(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment