Code : #
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
sys.path.insert(0,'/home/ubuntu')
print(sys.path)
from tradingbox.trading_ig_config import config as config
from tradingbox.trading_ig_config import config_interface
from trading_ig import IGService, IGStreamService
from trading_ig.lightstreamer import Subscription
from threading import Thread
import json
import requests
class Stop(Thread):
def __init__(self):
Thread.__init__(self)
def launch_stop(self, params):
stop = ac.ig_service.update_open_position(limit_level=None,
stop_level=params['stop_level'],
deal_id=params['deal_id'],)
class Account_connection(Thread):
def __init__(self):
Thread.__init__(self)
self.ig_service = IGService(username=config.username,
password=config.password,
api_key=config.api_key,
acc_type=config.acc_type)
print("Account_connection:", config.username, config.acc_type)
self.ig_service.create_session()
self.protection = False
self.epic_params = {
dax : dax_ballot.mini_distance_stop,
dow : dow_ballot.mini_distance_stop,
}
self.levels_protections = {}
def stream_init(self):
ig_service = IGService(config.username, config.password, config.api_key, config.acc_type)
self.ig_stream_service = IGStreamService(ig_service)
ig_session = self.ig_stream_service.create_session()
accounts = ig_session[u'accounts']
for account in accounts:
if account[u'accountId'] == config.acc_number:
self.accountId = account[u'accountId']
else:
print('Account not found: {0}'.format(config.acc_number))
self.accountId = None
self.ig_stream_service.connect(self.accountId)
def run(self):
self.stream_init()
account_str = 'TRADE:{}'.format(config.acc_number)
self.subcription_trades = Subscription(
mode="DISTINCT",
items=[account_str],
fields=["CONFIRMS","OPU","WOU"],)
self.subcription_trades.addlistener(self.on_account_update)
sub_key_trades = self.ig_stream_service.ls_client.subscribe(self.subcription_trades)
input("{0:-^80}\n".format("HIT CR TO UNSUBSCRIBE AND DISCONNECT FROM LIGHTSTREAMER"))
self.ig_stream_service.disconnect()
def get_account_balance(self):
self.ig_service.create_session()
balance = self.ig_service.ig_session['accountInfo']['balance']
# account_detail = self.ig_service.fetch_accounts()
# balance = account_detail['accounts'][0]['balance']['balance']
# if account_detail['accounts'][0]['currency'] == 'EUR':
# currency = '€'
# else:
# currency = '€'
currency = '€'
return balance, currency
def get_epic_value(self, epic):
res = self.ig_service.fetch_market_by_epic(epic)
if res['instrument']['marketId'] == 'DE30':
n = 'DAX'
else:
n = 'DOW'
if res['instrument']['currencies'][0]['name'] == 'EUR':
c = "€"
else:
c = res['instrument']['currencies'][0]['name']
return {'high' : res['snapshot']['high'],
'minDealSize' : res['dealingRules']['minDealSize']['value'],
'name': n,
'currency': c}
def position_epic_button(self, epic):
return self.get_epic_value(epic)
def update_account_raspi(self, epic=False):
balance, currency = self.get_account_balance()
epic_value = self.position_epic_button(epic) #TODO depend position of GPIO raspi
pos_size = round((balance / (epic_value['high'] * (1 + (config_interface.marge_max_epic/100)))) * config_interface.levier,2)
res = {
'balance': balance,
'pos_size': pos_size,
}
datas = {"datas_new_account": "update"}
datas.update(res)
requests.get(
"{}/api/v1/receveid_information/account_balance".format(config_interface.ip_raspi), params=datas)
return res
def update_protection_list(self, epic, deal_id):
if self.levels_protections != {}:
protections = self.levels_protections[epic]
if deal_id in protections['deal_id']:
# self.levels_protections[epic] = {}
self.levels_protections = {}
return False
def on_account_update(self, item_update):
print("on_account_update:", item_update)
if item_update['pos']:
try:
js = json.loads(item_update['values']['CONFIRMS'])
except:
js = json.loads(item_update['values']['OPU'])
if js['dealStatus'] == 'ACCEPTED' and js['status'] == 'OPEN' and js['epic'] in self.epic_params:
level = js['level']
epic = js['epic']
direction = js['direction']
deal_id = js['dealId']
if direction == 'BUY':
real_stop_level = level + self.epic_params[epic] + 1
real_stop_level_distance = level + 1
self.levels_protections[epic] = {
'direction': 'BUY',
'level': level,
'real_stop_level': real_stop_level,
'real_stop_level_distance':real_stop_level_distance,
'deal_id':deal_id,}
else:
real_stop_level = level - self.epic_params[epic] - 1
real_stop_level_distance = level - 1
self.levels_protections[epic] = {
'direction': 'SELL',
'level': level,
'real_stop_level': real_stop_level,
'real_stop_level_distance':real_stop_level_distance,
'deal_id':deal_id,}
# LA PARTIE UPDATE DE RAPSPI interface account_balance + size_position.
elif js['dealStatus'] == 'ACCEPTED' and js['status'] in ['AMENDED','DELETED']:
deal_id = js['dealId']
epic = js['epic']
self.update_protection_list(epic, deal_id)
res = self.update_account_raspi(epic)
print()
print(res)
print()
class Epic_Connection(Thread):
def __init__(self, epic):
Thread.__init__(self)
self.price = dict()
self.epic = epic
self.deal_ids = []
self.ig_service = IGService(username=config.username,
password=config.password,
api_key=config.api_key,
acc_type=config.acc_type)
self.ig_service.create_session()
self.mini_distance_stop = self.get_info_on_epic(epic)
print(epic, self.get_info_on_epic(epic))
self.stop = Stop()
print("Epic_Connection:", config.username, config.acc_type, epic)
def stream_init(self):
ig_service = IGService(config.username, config.password, config.api_key, config.acc_type)
self.ig_stream_service = IGStreamService(ig_service)
ig_session = self.ig_stream_service.create_session()
accounts = ig_session[u'accounts']
for account in accounts:
if account[u'accountId'] == config.acc_number:
self.accountId = account[u'accountId']
else:
print('Account not found: {0}'.format(config.acc_number))
self.accountId = None
self.ig_stream_service.connect(self.accountId)
def run(self):
self.stream_init()
self.subcription_trades = Subscription(
mode="MERGE",
items=["MARKET:" + self.epic],
fields=["BID", "OFFER"],)
self.subcription_trades.addlistener(self.on_epic_update)
sub_key_trades = self.ig_stream_service.ls_client.subscribe(self.subcription_trades)
input("{0:-^80}\n".format("HIT CR TO UNSUBSCRIBE AND DISCONNECT FROM LIGHTSTREAMER"))
self.ig_stream_service.disconnect()
def on_epic_update(self, item_update):
# ON verifie l epic
print("on_epic_update:", item_update)
print("-->", ac.levels_protections)
market = item_update['name'].replace('MARKET:','')
buy_price = float(item_update['values']['BID'])
sell_price = float(item_update['values']['OFFER'])
if market in ac.levels_protections:
real_stop_level = ac.levels_protections[market]['real_stop_level'] # level d'execution du SL+1 (+5 sur dax)
real_stop_level_distance = ac.levels_protections[market]['real_stop_level_distance'] # level SL+1
deal_id = ac.levels_protections[market]['deal_id']
if buy_price >= real_stop_level and ac.levels_protections[market]['direction'] == 'BUY':
print("!! on met un vrai stop BUY !!")
params = {'deal_id': deal_id,
'stop_level': real_stop_level_distance}
self.stop.launch_stop(params=params)
ac.levels_protections.pop(market, False)
elif sell_price <= real_stop_level and ac.levels_protections[market]['direction'] == 'SELL':
print("!! on met un vrai stop SELL !!")
params = {'deal_id': deal_id,
'stop_level': real_stop_level_distance}
self.stop.launch_stop(params=params)
ac.levels_protections.pop(market, False)
def get_info_on_epic(self, epic):
epic_info = self.ig_service.fetch_market_by_epic(epic)
mini_distance_stop = epic_info['dealingRules']['minNormalStopOrLimitDistance']['value']
return mini_distance_stop
dax = "IX.D.DAX.IFMM.IP"
dow = "IX.D.DOW.IFE.IP"
dax_ballot = Epic_Connection(dax)
dow_ballot = Epic_Connection(dow)
ac = Account_connection()
dax_ballot.start()
dow_ballot.start()
ac.start()