Les + populaires

BTC ETH SOL XRP BNB USDC USDT

Suivez-nous

Grille Trading Bot en Python. Dans cet article, nous allons créer un… | de Craig Mariani | Coinmons | juin 2022

IAavec
Graphique ETHUSD sur 5 minutes
from websocket import create_connection
import simplejson as json
from secret import Secret
import pandas as pd
class Stream_Data:
def __init__(self) -> None:
self.url = 'wss://stream.data.alpaca.markets/v1beta1/crypto?exchanges=CBSE' def bar_data(self):
ws = create_connection(self.url)
auth_message = {"action":"auth","key": Secret.paper_api_key, "secret": Secret.paper_secret_key}

ws.send(json.dumps(auth_message))

subscription = {"action":"subscribe","bars":["ETHUSD"]}
ws.send(json.dumps(subscription))

while True:
data = json.loads(ws.recv())
yield data[0]
class Rules:
def __init__(self, current_price) -> None:
self.line_count = 5
self.grid_space = 100
self.current_price = current_price

def calculate_grid_lines(self):
line_count = self.line_count
grid_space = self.grid_space
price = self.current_price

stop_loss = price - ((line_count + 1) * grid_space)
take_profit = price + ((line_count + 1) * grid_space)
buy_lines = []
sell_lines = []

for i in range(line_count):
buy_lines.append(price - ((line_count * grid_space)))
sell_lines.append(price + ((line_count * grid_space)))

return stop_loss, take_profit, buy_lines, sell_lines

# risk no more than 10 percent of our account on a single trade
# when the stoploss is triggered we should only lose 10 percent
def calculate_position_size(self, account_size):
line_count = self.line_count
grid_space = self.grid_space

risk = account_size * .1
tick_value = 1
ticks_at_risk = (line_count + 1) * grid_space
position_size = risk / (ticks_at_risk * tick_value)
position_size = round(position_size, 2)
return position_size

import alpaca_trade_api as tradeapi
from more_itertools import first
from stream_data import Stream_Data as stream
from secret import Secret
import numpy as np
import pandas as pd
from pprint import pprint
from rules import Rules
class Bot:
def __init__(self):
api_key = Secret.paper_api_key
secret_key = Secret.paper_secret_key
alp_base_url = 'https://paper-api.alpaca.markets'
api = tradeapi.REST(api_key, secret_key, alp_base_url, api_version='v2')
self.data_url = 'https://data.alpaca.markets/v1beta1/crypto'
self.header = {
'APCA-API-KEY-ID' : Secret.paper_api_key,
'APCA-API-SECRET-KEY' : Secret.paper_secret_key}
self.api_key = api_key
self.secret_key = secret_key
self.api = api

def current_profit_loss(self):
api = self.api
account = api.get_account()
# Check our current balance vs. our balance at the last market close
balance_change = float(account.equity) - float(account.last_equity)
print(f'Today\'s portfolio balance change: ${balance_change}')

def start_bot(self):
api = self.api
s = stream()
bars = s.bar_data()

# initial buy
for _ in range(3):
print(next(bars))

first_close = next(bars)['c']
r = Rules(first_close)
account = api.get_account()
available_funds = int(account.buying_power)
print(available_funds)

# position size is the total amount of our account that we are risking
position_size =
r.calculate_position_size(account_size=available_funds)
print('position_size {}'.format(position_size))
# the amount of the position we buy or sell off at each line
partial_position = position_size / 7
print('First Purchase of {} at {}'.format(position_size, first_close))
api.submit_order(
symbol='ETHUSD',
side='buy',
type='market',
qty=position_size,
)

# set up grid lines
stop_loss, take_profit, buy_lines, sell_lines = r.calculate_grid_lines()

for bar in bars:
close = bar['c']
if close in buy_lines:
api.submit_order(
symbol='ETHUSD',
side='buy',
type='market',
qty=partial_position,
)
if close in sell_lines:
api.submit_order(
symbol='ETHUSD',
side='sell',
type='market',
qty=partial_position,
)

if take_profit == close:
print('exit all positions at profit')
api.close_all_positions()
b.current_profit_loss()
b.start_bot()
if stop_loss == close:
print('exit all positions at a loss')
api.close_all_positions()
b.current_profit_loss()
b.start_bot()

if __name__ == '__main__':
b = Bot()
b.start_bot()

Rejoignez Coinmonks Telegram Channel et Youtube Channel pour en savoir plus sur le trading et l’investissement cryptographiques

Source medium.com

Gérez vos cryptos
Bitvavo
Trading sans frais jusqu'à 10 k€

Donnez votre avis

Soyez le 1er à noter cet article


Partagez cet article maintenant !

Envoyez simplement nos contenus crypto et finance à vos proches.