Advertisement
Guest User

FULLY AUTOMATED TRADING PROGRAM

a guest
May 9th, 2018
4,315
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 27.77 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import numpy
  4. import pandas
  5. import matplotlib.pyplot as plt
  6. import matplotlib.dates as mdates
  7. # Scikit's LinearRegression model
  8. from sklearn.linear_model import LinearRegression
  9. from scipy import stats
  10. import math
  11. import os
  12. import requests
  13. import json
  14. import time
  15. import random
  16. import uuid
  17. from time import localtime, strftime
  18. import datetime
  19. import calendar
  20. import sys
  21. import operator
  22. import sched
  23. from random import shuffle
  24. import holidays
  25. import pytz
  26.  
  27. set(pytz.all_timezones_set)
  28. YEAR_var = 2018
  29.  
  30. # ALL EPICS
  31. main_epic_ids = [
  32.     'CS.D.AUDUSD.TODAY.IP',
  33.     'CS.D.EURCHF.TODAY.IP',
  34.     'CS.D.EURGBP.TODAY.IP',
  35.     'CS.D.EURJPY.TODAY.IP',
  36.     'CS.D.EURUSD.TODAY.IP',
  37.     'CS.D.GBPEUR.TODAY.IP',
  38.     'CS.D.GBPUSD.TODAY.IP',
  39.     'CS.D.USDCAD.TODAY.IP',
  40.     'CS.D.USDCHF.TODAY.IP',
  41.     'CS.D.USDJPY.TODAY.IP',
  42.     'CS.D.CADCHF.TODAY.IP',
  43.     'CS.D.CADJPY.TODAY.IP',
  44.     'CS.D.CHFJPY.TODAY.IP',
  45.     'CS.D.EURCAD.TODAY.IP',
  46.     'CS.D.EURSGD.TODAY.IP',
  47.     'CS.D.EURZAR.TODAY.IP',
  48.     'CS.D.GBPCAD.TODAY.IP',
  49.     'CS.D.GBPCHF.TODAY.IP',
  50.     'CS.D.GBPJPY.TODAY.IP',
  51.     'CS.D.GBPSGD.TODAY.IP',
  52.     'CS.D.GBPZAR.TODAY.IP',
  53.     'CS.D.MXNJPY.TODAY.IP',
  54.     'CS.D.NOKJPY.TODAY.IP',
  55.     'CS.D.PLNJPY.TODAY.IP',
  56.     'CS.D.SEKJPY.TODAY.IP',
  57.     'CS.D.SGDJPY.TODAY.IP',
  58.     'CS.D.USDSGD.TODAY.IP',
  59.     'CS.D.USDZAR.TODAY.IP',
  60.     'CS.D.AUDCAD.TODAY.IP',
  61.     'CS.D.AUDCHF.TODAY.IP',
  62.     'CS.D.AUDEUR.TODAY.IP',
  63.     'CS.D.AUDGBP.TODAY.IP',
  64.     'CS.D.AUDJPY.TODAY.IP',
  65.     'CS.D.AUDNZD.TODAY.IP',
  66.     'CS.D.AUDSGD.TODAY.IP',
  67.     'CS.D.EURAUD.TODAY.IP',
  68.     'CS.D.EURNZD.TODAY.IP',
  69.     'CS.D.GBPAUD.TODAY.IP',
  70.     'CS.D.GBPNZD.TODAY.IP',
  71.     'CS.D.NZDAUD.TODAY.IP',
  72.     'CS.D.NZDCAD.TODAY.IP',
  73.     'CS.D.NZDCHF.TODAY.IP',
  74.     'CS.D.NZDEUR.TODAY.IP',
  75.     'CS.D.NZDGBP.TODAY.IP',
  76.     'CS.D.NZDJPY.TODAY.IP',
  77.     'CS.D.NZDUSD.TODAY.IP',
  78.     'CS.D.CHFHUF.TODAY.IP',
  79.     'CS.D.EURCZK.TODAY.IP',
  80.     'CS.D.EURHUF.TODAY.IP',
  81.     'CS.D.EURILS.TODAY.IP',
  82.     'CS.D.EURMXN.TODAY.IP',
  83.     'CS.D.EURPLN.TODAY.IP',
  84.     'CS.D.EURTRY.TODAY.IP',
  85.     'CS.D.GBPCZK.TODAY.IP',
  86.     'CS.D.GBPHUF.TODAY.IP',
  87.     'CS.D.GBPILS.TODAY.IP',
  88.     'CS.D.GBPMXN.TODAY.IP',
  89.     'CS.D.GBPPLN.TODAY.IP',
  90.     'CS.D.GBPTRY.TODAY.IP',
  91.     'CS.D.TRYJPY.TODAY.IP',
  92.     'CS.D.USDCZK.TODAY.IP',
  93.     'CS.D.USDHUF.TODAY.IP',
  94.     'CS.D.USDILS.TODAY.IP',
  95.     'CS.D.USDMXN.TODAY.IP',
  96.     'CS.D.USDPLN.TODAY.IP',
  97.     'CS.D.USDTRY.TODAY.IP',
  98.     'CS.D.CADNOK.TODAY.IP',
  99.     'CS.D.CHFNOK.TODAY.IP',
  100.     'CS.D.EURDKK.TODAY.IP',
  101.     'CS.D.EURNOK.TODAY.IP',
  102.     'CS.D.EURSEK.TODAY.IP',
  103.     'CS.D.GBPDKK.TODAY.IP',
  104.     'CS.D.GBPNOK.TODAY.IP',
  105.     'CS.D.GBPSEK.TODAY.IP',
  106.     'CS.D.NOKSEK.TODAY.IP',
  107.     'CS.D.USDDKK.TODAY.IP',
  108.     'CS.D.USDNOK.TODAY.IP',
  109.     'CS.D.USDSEK.TODAY.IP',
  110.     'CS.D.AUDCNH.TODAY.IP',
  111.     'CS.D.CADCNH.TODAY.IP',
  112.     'CS.D.CNHJPY.TODAY.IP',
  113.     'CS.D.BRLJPY.TODAY.IP',
  114.     'CS.D.GBPINR.TODAY.IP',
  115.     'CS.D.USDBRL.TODAY.IP',
  116.     'CS.D.USDIDR.TODAY.IP',
  117.     'CS.D.USDINR.TODAY.IP',
  118.     'CS.D.USDKRW.TODAY.IP',
  119.     'CS.D.USDMYR.TODAY.IP',
  120.     'CS.D.USDPHP.TODAY.IP',
  121.     'CS.D.USDTWD.TODAY.IP',
  122.     'CS.D.EURCNH.TODAY.IP',
  123.     'CS.D.sp_EURRUB.TODAY.IP',
  124.     'CS.D.GBPCNH.TODAY.IP',
  125.     'CS.D.NZDCNH.TODAY.IP',
  126.     'CS.D.USDCNH.TODAY.IP',
  127.     'CS.D.sp_USDRUB.TODAY.IP']
  128. # ALL EPICS
  129.  
  130. b_REAL = True #Change this if you want to use your Live/Demo account
  131.  
  132. if b_REAL:
  133.     REAL_OR_NO_REAL = 'https://api.ig.com/gateway/deal'
  134.     API_ENDPOINT = "https://api.ig.com/gateway/deal/session"
  135.     API_KEY = 'YOUR API KEY HERE'
  136.     data = {"identifier": "YOUR USERNAME HERE", "password": "YOUR PASSWORD HERE"}
  137. else:
  138.     REAL_OR_NO_REAL = 'https://demo-api.ig.com/gateway/deal'
  139.     API_ENDPOINT = "https://demo-api.ig.com/gateway/deal/session"
  140.     API_KEY = 'YOUR API KEY HERE'
  141.     data = {"identifier": "YOUR USERNAME HERE", "password": "YOUR PASSWORD HERE"}
  142.  
  143. headers = {'Content-Type': 'application/json; charset=utf-8',
  144.            'Accept': 'application/json; charset=utf-8',
  145.            'X-IG-API-KEY': API_KEY,
  146.            'Version': '2'
  147.            }
  148.  
  149. r = requests.post(API_ENDPOINT, data=json.dumps(data), headers=headers)
  150.  
  151. headers_json = dict(r.headers)
  152. CST_token = headers_json["CST"]
  153. print(R"CST : " + CST_token)
  154. x_sec_token = headers_json["X-SECURITY-TOKEN"]
  155. print(R"X-SECURITY-TOKEN : " + x_sec_token)
  156.  
  157. # GET ACCOUNTS
  158. base_url = REAL_OR_NO_REAL + '/accounts'
  159. authenticated_headers = {'Content-Type': 'application/json; charset=utf-8',
  160.                          'Accept': 'application/json; charset=utf-8',
  161.                          'X-IG-API-KEY': API_KEY,
  162.                          'CST': CST_token,
  163.                          'X-SECURITY-TOKEN': x_sec_token}
  164.  
  165. auth_r = requests.get(base_url, headers=authenticated_headers)
  166. d = json.loads(auth_r.text)
  167.  
  168. # print ("-----------------DEBUG-----------------")
  169. # print ("#################DEBUG#################")
  170. # print(auth_r.status_code)
  171. # print(auth_r.reason)
  172. # print (auth_r.text)
  173. # print ("-----------------DEBUG-----------------")
  174. # print ("#################DEBUG#################")
  175.  
  176. for i in d['accounts']:
  177.     if str(i['accountType']) == "SPREADBET":
  178.         print("Spreadbet Account ID is : " + str(i['accountId']))
  179.         spreadbet_acc_id = str(i['accountId'])
  180.  
  181. # SET SPREAD BET ACCOUNT AS DEFAULT
  182. base_url = REAL_OR_NO_REAL + '/session'
  183. data = {"accountId": spreadbet_acc_id, "defaultAccount": "True"}
  184. auth_r = requests.put(
  185.     base_url,
  186.     data=json.dumps(data),
  187.     headers=authenticated_headers)
  188.  
  189. ##########################################################################
  190. ##########################END OF LOGIN CODE###############################
  191. ##########################END OF LOGIN CODE###############################
  192. ##########################END OF LOGIN CODE###############################
  193. ##########################END OF LOGIN CODE###############################
  194. ##########################################################################
  195. # PROGRAMMABLE VALUES
  196. orderType_value = "MARKET"
  197. size_value = "5"
  198. expiry_value = "DFB"
  199. guaranteedStop_value = True
  200. currencyCode_value = "GBP"
  201. forceOpen_value = True
  202. stopDistance_value = "15"  # Make this a global variable for ease!
  203.  
  204. SL_MULTIPLIER = 4
  205. LOW_SL_WATERMARK = 10
  206. HIGH_SL_WATERMARK = 90
  207. STR_CHECK = ""
  208.  
  209.  
  210. def is_between(time, time_range):
  211.     if time_range[1] < time_range[0]:
  212.         return time >= time_range[0] or time <= time_range[1]
  213.     return time_range[0] <= time <= time_range[1]
  214.  
  215.  
  216. def midpoint(p1, p2):
  217.     return (p1 + p2) / 2
  218.  
  219.  
  220. def distance(a, b):
  221.     if (a == b):
  222.         return 0
  223.     elif (a < 0) and (b < 0) or (a > 0) and (b > 0):
  224.         if (a < b):
  225.             return (abs(abs(a) - abs(b)))
  226.         else:
  227.             return -(abs(abs(a) - abs(b)))
  228.     else:
  229.         return math.copysign((abs(a) + abs(b)), b)
  230.  
  231.  
  232. def percentage(part, whole):
  233.     return 100 * float(part) / float(whole)
  234.  
  235.  
  236. def humanize_time(secs):
  237.     mins, secs = divmod(secs, 60)
  238.     hours, mins = divmod(mins, 60)
  239.     return '%02d:%02d:%02d' % (hours, mins, secs)
  240.  
  241.  
  242. def find_good_epics():
  243.     spreads_and_epics = []
  244.     i_count = 0
  245.     pick_from_epics = []
  246.     full_hol_list = []
  247.     ###################################################################
  248.     tz = pytz.timezone('Europe/Berlin')
  249.     todays_date = str(datetime.datetime.now(tz=tz).strftime('%Y-%m-%d'))
  250.     ger_today = str(str("GER_" + str(todays_date)))
  251.     print("Europe/Berlin :- Today's Date is ..." + str(todays_date))
  252.     ###################################################################
  253.     tz = pytz.timezone('Europe/London')
  254.     todays_date = str(datetime.datetime.now(tz=tz).strftime('%Y-%m-%d'))
  255.     gb_today = str(str("GB_" + str(todays_date)))
  256.     print("Europe/London :- Today's Date is ..." + str(todays_date))
  257.     ###################################################################
  258.     tz = pytz.timezone('America/New_York')
  259.     todays_date = str(datetime.datetime.now(tz=tz).strftime('%Y-%m-%d'))
  260.     us_today = str(str("US_" + str(todays_date)))
  261.     print("America/New_York :- Today's Date is ..." + str(todays_date))
  262.     ###################################################################
  263.     tz = pytz.timezone('Australia/Sydney')
  264.     todays_date = str(datetime.datetime.now(tz=tz).strftime('%Y-%m-%d'))
  265.     aus_today = str(str("AUS_" + str(todays_date)))
  266.     print("Australia/Sydney :- Today's Date is ..." + str(todays_date))
  267.     ###################################################################
  268.     tz = pytz.timezone('Asia/Tokyo')
  269.     todays_date = str(datetime.datetime.now(tz=tz).strftime('%Y-%m-%d'))
  270.     jp_today = str(str("JP_" + str(todays_date)))
  271.     print("Asia/Tokyo :- Today's Date is ..." + str(todays_date))
  272.     ###################################################################
  273.     b_ger_hol = False
  274.     b_uk_hol = False
  275.     b_us_hol = False
  276.     b_aus_hol = False
  277.     b_jp_hol = False
  278.  
  279.     for date, name in sorted(holidays.DE(years=YEAR_var).items()):
  280.         full_hol_list.append(str("GER_" + str(date)))
  281.     for date, name in sorted(holidays.UK(years=YEAR_var).items()):
  282.         full_hol_list.append(str("GB_" + str(date)))
  283.     for date, name in sorted(holidays.US(years=YEAR_var).items()):
  284.         full_hol_list.append(str("US_" + str(date)))
  285.     for date, name in sorted(holidays.AU(years=YEAR_var).items()):
  286.         full_hol_list.append(str("AUS_" + str(date)))
  287.     for date, name in sorted(holidays.JP(years=YEAR_var).items()):
  288.         full_hol_list.append(str("JP_" + str(date)))
  289.  
  290.     full_hol_list = sorted(full_hol_list)
  291.  
  292.     for d in full_hol_list:
  293.         #print (d)
  294.         if str(d) == ger_today:
  295.             b_ger_hol = True
  296.         if str(d) == gb_today:
  297.             b_uk_hol = True
  298.         if str(d) == us_today:
  299.             b_us_hol = True
  300.         if str(d) == aus_today:
  301.             b_aus_hol = True
  302.         if str(d) == jp_today:
  303.             b_jp_hol = True
  304.  
  305.     for epic_id in main_epic_ids:
  306.         tmp_lst = []
  307.         base_url = REAL_OR_NO_REAL + '/markets/' + epic_id
  308.         auth_r = requests.get(base_url, headers=authenticated_headers)
  309.         d = json.loads(auth_r.text)
  310.  
  311.         try:
  312.             i_count = i_count + 1
  313.             if epic_id.find('MXN') != -1:
  314.                 #print("!!DEBUG!!...skipping, FOUND MXN in..." + str(epic_id))
  315.                 time.sleep(1)
  316.             elif epic_id.find('SEK') != -1:
  317.                 #print("!!DEBUG!!...skipping, FOUND SEK in..." + str(epic_id))
  318.                 time.sleep(1)
  319.             elif epic_id.find('NOK') != -1:
  320.                 #print("!!DEBUG!!...skipping, FOUND NOK in..." + str(epic_id))
  321.                 time.sleep(1)
  322.             elif epic_id.find('CNH') != -1:
  323.                 #print("!!DEBUG!!...skipping, FOUND CNH in..." + str(epic_id))
  324.                 time.sleep(1)
  325.             else:
  326.                 b_TRADE_OK = False
  327.                 while True:
  328.  
  329.                     ###################EUROPE############################
  330.                     ###################EUROPE############################
  331.                     ###################EUROPE############################
  332.                     tz = pytz.timezone('Europe/Berlin')
  333.                     now_time = datetime.datetime.now(tz=tz).strftime('%H:%M')
  334.                     #print ("!!DEBUG!! Europe/Berlin:" + str(now_time))
  335.                     if is_between(str(now_time), ("08:00", "16:00")):
  336.                         #print("!!DEBUG!!...FRANKFURT MARKET OPEN!!")
  337.                         time.sleep(1)
  338.                         STR_CHECK = "EUR"
  339.                         if STR_CHECK in epic_id and b_ger_hol == False:
  340.                             b_TRADE_OK = True
  341.                             break
  342.                     ###################LONDON############################
  343.                     ###################LONDON############################
  344.                     ###################LONDON############################
  345.                     tz = pytz.timezone('Europe/London')
  346.                     now_time = datetime.datetime.now(tz=tz).strftime('%H:%M')
  347.                     while True:
  348.                         if is_between(str(now_time), ("22:00", "22:59")):
  349.                             time.sleep(1)  # Sleeping for the tally up hour
  350.                             print("!!DEBUG!! Tally Up hour:" + str(now_time))
  351.                             now_time = datetime.datetime.now(
  352.                                 tz=tz).strftime('%H:%M')
  353.                         else:
  354.                             break
  355.                     #print ("!!DEBUG!! Europe/London:" + str(now_time))
  356.                     if is_between(str(now_time), ("08:00", "16:00")):
  357.                         #print("!!DEBUG!!...LONDON MARKET OPEN!!")
  358.                         time.sleep(1)
  359.                         STR_CHECK = "GBP"
  360.                         if STR_CHECK in epic_id and b_uk_hol == False:
  361.                             b_TRADE_OK = True
  362.                             break
  363.                     ###################NY############################
  364.                     ###################NY############################
  365.                     ###################NY############################
  366.                     tz = pytz.timezone('America/New_York')
  367.                     now_time = datetime.datetime.now(tz=tz).strftime('%H:%M')
  368.                     #print ("!!DEBUG!! America/New_York:" + str(now_time))
  369.                     if is_between(str(now_time), ("08:00", "16:00")):
  370.                         #print("!!DEBUG!!...NEW YORK MARKET OPEN!!")
  371.                         time.sleep(1)
  372.                         STR_CHECK = "USD"
  373.                         if STR_CHECK in epic_id and b_us_hol == False:
  374.                             b_TRADE_OK = True
  375.                             break
  376.                     ###################AUS############################
  377.                     ###################AUS############################
  378.                     ###################AUS############################
  379.                     tz = pytz.timezone('Australia/Sydney')
  380.                     now_time = datetime.datetime.now(tz=tz).strftime('%H:%M')
  381.                     #print ("!!DEBUG!! Australia/Sydney:" + str(now_time))
  382.                     if is_between(str(now_time), ("08:00", "16:00")):
  383.                         #print("!!DEBUG!!...SYDNEY MARKET OPEN!!")
  384.                         time.sleep(1)
  385.                         STR_CHECK = "AUD"
  386.                         if STR_CHECK in epic_id and b_aus_hol == False:
  387.                             b_TRADE_OK = True
  388.                             break
  389.                     ###################TOKYO############################
  390.                     ###################TOKYO############################
  391.                     ###################TOKYO############################
  392.                     tz = pytz.timezone('Asia/Tokyo')
  393.                     now_time = datetime.datetime.now(tz=tz).strftime('%H:%M')
  394.                     #print ("!!DEBUG!! Asia/Tokyo:" + str(now_time))
  395.                     if is_between(str(now_time), ("08:00", "16:00")):
  396.                         #print("!!DEBUG!!...TOKYO MARKET OPEN!!")
  397.                         time.sleep(1)
  398.                         STR_CHECK = "JPY"
  399.                         if STR_CHECK in epic_id and b_jp_hol == False:
  400.                             b_TRADE_OK = True
  401.                             break
  402.                     break
  403.  
  404.                 if b_TRADE_OK:
  405.  
  406.                     current_bid = d['snapshot']['bid']
  407.                     ask_price = d['snapshot']['offer']
  408.                     spread = float(current_bid) - float(ask_price)
  409.                     if float(spread) >= -1:
  410.                         # tmp_lst.append(epic_id)
  411.                         # spreads_and_epics.append(tmp_lst)
  412.                         pick_from_epics.append(epic_id)
  413.                         # print ("bid : " + str(current_bid))
  414.                         # print ("ask : " + str(ask_price))
  415.                         # print ("-------------------------")
  416.                         # print ("spread : " + str(spread))
  417.                         # print ("-------------------------")
  418.                         print("!!DEBUG!!...FOUND GOOD EPIC..." +
  419.                               str(i_count) + "/" + str(len(main_epic_ids)))
  420.                         time.sleep(1)
  421.                     else:
  422.                         print(
  423.                             "!!DEBUG!!...skipping, NO GOOD EPIC....Checking next epic spreads..." +
  424.                             str(i_count) +
  425.                             "/" +
  426.                             str(
  427.                                 len(main_epic_ids)))
  428.                         time.sleep(1)
  429.                         continue
  430.  
  431.         except Exception as e:
  432.             print(e)
  433.             pass
  434.  
  435.     return (pick_from_epics)
  436.  
  437.  
  438. def are_we_going_to_trade(epic_id, TRADE_DIRECTION, limit):
  439.  
  440.     if TRADE_DIRECTION == "NONE":
  441.         return None
  442.  
  443.     limitDistance_value = str(limit)
  444.  
  445.     ##########################################################################
  446.     print(
  447.         "Order will be a " +
  448.         str(TRADE_DIRECTION) +
  449.         " Order, With a limit of: " +
  450.         str(limitDistance_value))
  451.     print(
  452.         "stopDistance_value for " +
  453.         str(epic_id) +
  454.         " will bet set at " +
  455.         str(stopDistance_value))
  456.     ##########################################################################
  457.  
  458.     # MAKE AN ORDER
  459.     base_url = REAL_OR_NO_REAL + '/positions/otc'
  460.     data = {
  461.         "direction": TRADE_DIRECTION,
  462.         "epic": epic_id,
  463.         "limitDistance": limitDistance_value,
  464.         "orderType": orderType_value,
  465.         "size": size_value,
  466.         "expiry": expiry_value,
  467.         "guaranteedStop": guaranteedStop_value,
  468.         "currencyCode": currencyCode_value,
  469.         "forceOpen": forceOpen_value,
  470.         "stopDistance": stopDistance_value}
  471.     r = requests.post(
  472.         base_url,
  473.         data=json.dumps(data),
  474.         headers=authenticated_headers)
  475.  
  476.     print("-----------------DEBUG-----------------")
  477.     print("#################DEBUG#################")
  478.     print(r.status_code)
  479.     print(r.reason)
  480.     print(r.text)
  481.     print("-----------------DEBUG-----------------")
  482.     print("#################DEBUG#################")
  483.  
  484.     d = json.loads(r.text)
  485.     deal_ref = d['dealReference']
  486.     time.sleep(1)
  487.     # CONFIRM MARKET ORDER
  488.     base_url = REAL_OR_NO_REAL + '/confirms/' + deal_ref
  489.     auth_r = requests.get(base_url, headers=authenticated_headers)
  490.     d = json.loads(auth_r.text)
  491.     DEAL_ID = d['dealId']
  492.     print("DEAL ID : " + str(d['dealId']))
  493.     print(d['dealStatus'])
  494.     print(d['reason'])
  495.  
  496.     if str(d['reason']) != "SUCCESS":
  497.         print("!!DEBUG!!...!!some thing occurred ERROR!!")
  498.         time.sleep(10)
  499.         print("-----------------DEBUG-----------------")
  500.         print("#################DEBUG#################")
  501.         print("!!DEBUG!! Resuming...")
  502.         print("-----------------DEBUG-----------------")
  503.         print("#################DEBUG#################")
  504.     else:
  505.         print("-----------------DEBUG-----------------")
  506.         print("#################DEBUG#################")
  507.         print("!!DEBUG!!...Yay, ORDER OPEN")
  508.         time.sleep(10)
  509.         print("-----------------DEBUG-----------------")
  510.         print("#################DEBUG#################")
  511.  
  512.  
  513. def Chandelier_Exit_formula(TRADE_DIR, ATR, Price):
  514.  
  515.     if TRADE_DIR == "BUY":
  516.  
  517.         return float(Price) - float(ATR) * 3
  518.  
  519.     elif TRADE_DIR == "SELL":
  520.  
  521.         return float(Price) + float(ATR) * 3
  522.  
  523.  
  524. def calculate_stop_loss(d):
  525.  
  526.     price_ranges = []
  527.     closing_prices = []
  528.     first_time_round_loop = True
  529.     TR_prices = []
  530.     price_compare = "bid"
  531.  
  532.     for i in d['prices']:
  533.         if first_time_round_loop:
  534.             # First time round loop cannot get previous
  535.             closePrice = i['closePrice'][price_compare]
  536.             closing_prices.append(closePrice)
  537.             high_price = i['highPrice'][price_compare]
  538.             low_price = i['lowPrice'][price_compare]
  539.             price_range = float(high_price - closePrice)
  540.             price_ranges.append(price_range)
  541.             first_time_round_loop = False
  542.         else:
  543.             prev_close = closing_prices[-1]
  544.             ###############################
  545.             closePrice = i['closePrice'][price_compare]
  546.             closing_prices.append(closePrice)
  547.             high_price = i['highPrice'][price_compare]
  548.             low_price = i['lowPrice'][price_compare]
  549.             price_range = float(high_price - closePrice)
  550.             price_ranges.append(price_range)
  551.             TR = max(high_price - low_price,
  552.                      abs(high_price - prev_close),
  553.                      abs(low_price - prev_close))
  554.             TR_prices.append(TR)
  555.  
  556.     return str(int(float(max(TR_prices))))
  557.  
  558.  
  559. if __name__ == '__main__':
  560.  
  561.     while True:
  562.  
  563.         try:
  564.  
  565.             base_url = REAL_OR_NO_REAL + "/accounts"
  566.             auth_r = requests.get(base_url, headers=authenticated_headers)
  567.             d = json.loads(auth_r.text)
  568.  
  569.             print("-----------------DEBUG-----------------")
  570.             print("#################DEBUG#################")
  571.             print(auth_r.status_code)
  572.             print(auth_r.reason)
  573.             print(auth_r.text)
  574.             print("-----------------DEBUG-----------------")
  575.             print("#################DEBUG#################")
  576.  
  577.             for i in d['accounts']:
  578.                 if str(i['accountType']) == "SPREADBET":
  579.                     balance = i['balance']['balance']
  580.                     deposit = i['balance']['deposit']
  581.  
  582.             percent_used = percentage(deposit, balance)
  583.  
  584.             print("-----------------DEBUG-----------------")
  585.             print("#################DEBUG#################")
  586.             print(
  587.                 "!!DEBUG!!...Percent of account used ..." +
  588.                 str(percent_used))
  589.             print("-----------------DEBUG-----------------")
  590.             print("#################DEBUG#################")
  591.  
  592.             if float(percent_used) > 70:
  593.                 print("!!DEBUG!!...Don't trade, Too much margin used up already")
  594.                 time.sleep(60)
  595.                 continue
  596.             else:
  597.                 print("!!DEBUG!!...OK to trade, Account balance OK!!")
  598.  
  599.             tradeable_epic_ids = find_good_epics()
  600.             shuffle(tradeable_epic_ids)
  601.  
  602.         except Exception as e:
  603.             print(e)
  604.             print("!!DEBUG!!...No Suitable Epics...Yet!!, Try again!!")
  605.             continue
  606.  
  607.         for epic_id in tradeable_epic_ids:
  608.  
  609.             base_url = REAL_OR_NO_REAL + "/prices/" + epic_id + "/MINUTE_15/16"
  610.             auth_r = requests.get(base_url, headers=authenticated_headers)
  611.             d = json.loads(auth_r.text)
  612.  
  613.             high_prices = []
  614.             low_prices = []
  615.             mid_prices = []
  616.             close_prices = []
  617.             ATR = calculate_stop_loss(d)
  618.  
  619.             remaining_allowance = d['allowance']['remainingAllowance']
  620.             reset_time = humanize_time(int(d['allowance']['allowanceExpiry']))
  621.             print("-----------------DEBUG-----------------")
  622.             print("#################DEBUG#################")
  623.             print("Remaining API Calls left: " + str(remaining_allowance))
  624.             print("Time to API Key reset: " + str(reset_time))
  625.             print("-----------------DEBUG-----------------")
  626.             print("#################DEBUG#################")
  627.  
  628.             for i in d['prices']:
  629.  
  630.                 if i['highPrice']['bid'] is not None:
  631.                     highPrice = i['highPrice']['bid']
  632.                     high_prices.append(highPrice)
  633.                 ########################################
  634.                 if i['lowPrice']['bid'] is not None:
  635.                     lowPrice = i['lowPrice']['bid']
  636.                     low_prices.append(lowPrice)
  637.                 ########################################
  638.                 if i['closePrice']['bid'] is not None:
  639.                     closePrice = i['lowPrice']['bid']
  640.                     close_prices.append(closePrice)
  641.                 ########################################
  642.                 mid_prices.append(float(midpoint(highPrice, lowPrice)))
  643.  
  644.             close_prices = numpy.asarray(close_prices)
  645.             low_prices = numpy.asarray(low_prices)
  646.             high_prices = numpy.asarray(high_prices)
  647.             mid_prices = numpy.asarray(mid_prices)
  648.  
  649.             xi = numpy.arange(0, len(low_prices))
  650.  
  651.             close_prices_slope, close_prices_intercept, close_prices_r_value, close_prices_p_value, close_prices_std_err = stats.linregress(
  652.                 xi, close_prices)
  653.             low_prices_slope, low_prices_intercept, low_prices_r_value, low_prices_p_value, low_prices_std_err = stats.linregress(
  654.                 xi, low_prices)
  655.             high_prices_slope, high_prices_intercept, high_prices_r_value, high_prices_p_value, high_prices_std_err = stats.linregress(
  656.                 xi, high_prices)
  657.             mid_prices_slope, mid_prices_intercept, mid_prices_r_value, mid_prices_p_value, mid_prices_std_err = stats.linregress(
  658.                 xi, mid_prices)
  659.  
  660.             base_url = REAL_OR_NO_REAL + '/markets/' + epic_id
  661.             auth_r = requests.get(
  662.                 base_url, headers=authenticated_headers)
  663.             d = json.loads(auth_r.text)
  664.  
  665.             current_bid = d['snapshot']['bid']
  666.  
  667.             if distance(current_bid, mid_prices_intercept) > 1:
  668.                 TRADE_DIRECTION = "SELL"
  669.                 pip_limit = int(abs(float(max(high_prices)) -
  670.                                     float(current_bid)) / SL_MULTIPLIER)
  671.                 print("-----------------DEBUG-----------------")
  672.                 print("#################DEBUG#################")
  673.                 print("!!DEBUG!!...BUY!!")
  674.                 print(str(epic_id))
  675.                 print(
  676.                     "!!DEBUG!!...Take Profit@...." +
  677.                     str(pip_limit) +
  678.                     " pips")
  679.                 print("-----------------DEBUG-----------------")
  680.                 print("#################DEBUG#################")
  681.                 ce_stop = Chandelier_Exit_formula(
  682.                     TRADE_DIRECTION, ATR, min(low_prices))
  683.                 tmp_stop = int(abs(float(current_bid) - (ce_stop)))
  684.             elif distance(current_bid, mid_prices_intercept) < -1:
  685.                 TRADE_DIRECTION = "BUY"
  686.                 pip_limit = int(abs(float(min(low_prices)) -
  687.                                     float(current_bid)) / SL_MULTIPLIER)
  688.                 print("-----------------DEBUG-----------------")
  689.                 print("#################DEBUG#################")
  690.                 print("!!DEBUG!!...SELL!!")
  691.                 print(str(epic_id))
  692.                 print(
  693.                     "!!DEBUG!!...Take Profit@...." +
  694.                     str(pip_limit) +
  695.                     " pips")
  696.                 print("-----------------DEBUG-----------------")
  697.                 print("#################DEBUG#################")
  698.                 ce_stop = Chandelier_Exit_formula(
  699.                     TRADE_DIRECTION, ATR, max(high_prices))
  700.                 tmp_stop = int(abs(float(current_bid) - (ce_stop)))
  701.  
  702.             else:
  703.                 pip_limit = 9999999
  704.                 tmp_stop = "999999"
  705.                 TRADE_DIRECTION = "NONE"
  706.                 print("!!DEBUG!!...Within trading range...Leave!!")
  707.  
  708.             if int(pip_limit) <= 1:
  709.                 print("!!DEBUG!!...No Trade!!, Pip Limit Under 1")
  710.                 TRADE_DIRECTION = "NONE"
  711.  
  712.             stopDistance_value = str(tmp_stop)
  713.  
  714.             if int(stopDistance_value) <= LOW_SL_WATERMARK or int(
  715.                     stopDistance_value) >= HIGH_SL_WATERMARK:
  716.                 TRADE_DIRECTION = "NONE"
  717.  
  718.             try:
  719.                 are_we_going_to_trade(epic_id, TRADE_DIRECTION, pip_limit)
  720.             except Exception as e:
  721.                 print(e)
  722.                 print("Something fucked up!!, Try again!!")
  723.                 continue
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement