Advertisement
Guest User

Fully automated trading python

a guest
Apr 30th, 2018
1,109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 27.15 KB | None | 0 0
  1. # IF YOU FOUND THIS USEFUL, Please Donate some Bitcoin ....
  2. # 1FWt366i5PdrxCC6ydyhD8iywUHQ2C7BWC
  3.  
  4. #!/usr/bin/env python
  5. # -*- coding: utf-8 -*-
  6. import numpy
  7. import pandas
  8. import matplotlib.pyplot as plt
  9. import matplotlib.dates as mdates
  10. # Scikit's LinearRegression model
  11. from sklearn.linear_model import LinearRegression
  12. from scipy import stats
  13. import math
  14. import os
  15. import requests
  16. import json
  17. import time
  18. import random
  19. import uuid
  20. from time import localtime, strftime
  21. import datetime as dt
  22. from datetime import date
  23. import calendar
  24. import sys
  25. import itertools
  26. import operator
  27. import sched
  28. from random import shuffle
  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. # TESTINGs
  131. # main_epic_ids = [
  132. # 'CS.D.AUDUSD.TODAY.IP',
  133. # 'CS.D.EURGBP.TODAY.IP',
  134. # 'CS.D.EURJPY.TODAY.IP',
  135. # 'CS.D.EURUSD.TODAY.IP',
  136. # 'CS.D.GBPUSD.TODAY.IP',
  137. # 'CS.D.USDCAD.TODAY.IP',
  138. # 'CS.D.USDCHF.TODAY.IP',
  139. # 'CS.D.USDJPY.TODAY.IP',
  140. # 'CS.D.AUDEUR.TODAY.IP',
  141. # 'CS.D.AUDGBP.TODAY.IP',
  142. # 'CS.D.AUDJPY.TODAY.IP',
  143. # 'CS.D.EURAUD.TODAY.IP',
  144. # 'CS.D.GBPAUD.TODAY.IP']
  145. # # TESTING
  146.  
  147.  
  148. # TIME_FRAMES = ["MINUTE/1", "MINUTE_2/1", "MINUTE_3/1", "MINUTE_5/1", "MINUTE_10/1",
  149. # "MINUTE_15/1", "MINUTE_30/1", "HOUR/1", "HOUR_2/1", "HOUR_3/1", "HOUR_4/1",
  150. # "DAY/1", "WEEK/1", "MONTH/1"]
  151.  
  152. REAL_OR_NO_REAL = 'https://api.ig.com/gateway/deal'
  153. API_ENDPOINT = "https://api.ig.com/gateway/deal/session"
  154. API_KEY = '<<<YOUR API KEY HERE>>>'
  155.                                                      
  156. data = {"identifier": "<<<YOUR USERNAME HERE>>>", "password": "<<<YOUR PASSWORD HERE>>>"}
  157.  
  158.  
  159. headers = {'Content-Type': 'application/json; charset=utf-8',
  160.            'Accept': 'application/json; charset=utf-8',
  161.            'X-IG-API-KEY': API_KEY,
  162.            'Version': '2'
  163.            }
  164.  
  165. r = requests.post(API_ENDPOINT, data=json.dumps(data), headers=headers)
  166.  
  167. headers_json = dict(r.headers)
  168. CST_token = headers_json["CST"]
  169. print(R"CST : " + CST_token)
  170. x_sec_token = headers_json["X-SECURITY-TOKEN"]
  171. print(R"X-SECURITY-TOKEN : " + x_sec_token)
  172.  
  173. # GET ACCOUNTS
  174. base_url = REAL_OR_NO_REAL + '/accounts'
  175. authenticated_headers = {'Content-Type': 'application/json; charset=utf-8',
  176.                          'Accept': 'application/json; charset=utf-8',
  177.                          'X-IG-API-KEY': API_KEY,
  178.                          'CST': CST_token,
  179.                          'X-SECURITY-TOKEN': x_sec_token}
  180.  
  181. auth_r = requests.get(base_url, headers=authenticated_headers)
  182. d = json.loads(auth_r.text)
  183.  
  184. # print ("-----------------DEBUG-----------------")
  185. # print ("#################DEBUG#################")
  186. # print(auth_r.status_code)
  187. # print(auth_r.reason)
  188. # print (auth_r.text)
  189. # print ("-----------------DEBUG-----------------")
  190. # print ("#################DEBUG#################")
  191.  
  192. for i in d['accounts']:
  193.     if str(i['accountType']) == "SPREADBET":
  194.         print("Spreadbet Account ID is : " + str(i['accountId']))
  195.         spreadbet_acc_id = str(i['accountId'])
  196.  
  197. # SET SPREAD BET ACCOUNT AS DEFAULT
  198. base_url = REAL_OR_NO_REAL + '/session'
  199. data = {"accountId": spreadbet_acc_id, "defaultAccount": "True"}
  200. auth_r = requests.put(
  201.     base_url,
  202.     data=json.dumps(data),
  203.     headers=authenticated_headers)
  204.  
  205. # print ("-----------------DEBUG-----------------")
  206. # print ("#################DEBUG#################")
  207. # print(auth_r.status_code)
  208. # print(auth_r.reason)
  209. # print (auth_r.text)
  210. # print ("-----------------DEBUG-----------------")
  211. # print ("#################DEBUG#################")
  212. # ERROR about account ID been the same, Ignore!
  213.  
  214. ##########################################################################
  215. ##########################END OF LOGIN CODE###############################
  216. ##########################END OF LOGIN CODE###############################
  217. ##########################END OF LOGIN CODE###############################
  218. ##########################END OF LOGIN CODE###############################
  219. ##########################################################################
  220. # PROGRAMMABLE VALUES
  221. # SET INITIAL VARIABLES, Hacky for now!
  222. orderType_value = "MARKET"
  223. size_value = "3"
  224. expiry_value = "DFB"
  225. guaranteedStop_value = True
  226. currencyCode_value = "GBP"
  227. forceOpen_value = True
  228. stopDistance_value = "15"  # Make this a global variable for ease!
  229.  
  230. SL_MULTIPLIER = 2.99
  231. LOW_SL_WATERMARK = 20
  232. HIGH_SL_WATERMARK = 70
  233. STR_CHECK = ""
  234.  
  235.  
  236. def is_between(time, time_range):
  237.     if time_range[1] < time_range[0]:
  238.         return time >= time_range[0] or time <= time_range[1]
  239.     return time_range[0] <= time <= time_range[1]
  240.  
  241.  
  242. def midpoint(p1, p2):
  243.     return (p1 + p2) / 2
  244.  
  245.  
  246. def distance(a, b):
  247.     if (a == b):
  248.         return 0
  249.     elif (a < 0) and (b < 0) or (a > 0) and (b > 0):
  250.         if (a < b):
  251.             return (abs(abs(a) - abs(b)))
  252.         else:
  253.             return -(abs(abs(a) - abs(b)))
  254.     else:
  255.         return math.copysign((abs(a) + abs(b)), b)
  256.  
  257. # Frankfurt
  258. # Germany
  259. # EUR
  260. # print("Frankfurt Market Status:...." + str(is_between(str(now_time), ("06:00", "14:00"))))
  261. # London
  262. # Great Britain
  263. # GBP
  264. # print("London Market Status:...." + str(is_between(str(now_time), ("07:00", "15:00"))))
  265. # New York
  266. # United States
  267. # USD
  268. # print("New York Market Status:...." + str(is_between(str(now_time), ("12:00", "20:30"))))
  269. # Sydney
  270. # Austrailia
  271. # AUD
  272. # print("Sydney Market Status:...." + str(is_between(str(now_time), ("22:00", "06:30"))))
  273. # Tokyo
  274. # Japan
  275. # JPY
  276. # print("Tokyo Market Status:...." + str(is_between(str(now_time),
  277. # ("23:00", "07:30"))))
  278.  
  279.  
  280. def percentage(part, whole):
  281.     return 100 * float(part) / float(whole)
  282.  
  283.  
  284. def humanize_time(secs):
  285.     mins, secs = divmod(secs, 60)
  286.     hours, mins = divmod(mins, 60)
  287.     return '%02d:%02d:%02d' % (hours, mins, secs)
  288.  
  289.  
  290. def lowest_spread_epic():
  291.     spreads_and_epics = []
  292.     i_count = 0
  293.     pick_from_epics = []
  294.  
  295.     for epic_id in main_epic_ids:
  296.         tmp_lst = []
  297.         base_url = REAL_OR_NO_REAL + '/markets/' + epic_id
  298.         auth_r = requests.get(base_url, headers=authenticated_headers)
  299.         d = json.loads(auth_r.text)
  300.  
  301.         try:
  302.             i_count = i_count + 1
  303.             if epic_id.find('MXN') != -1:
  304.                 #print("!!DEBUG!!...skipping, FOUND MXN in..." + str(epic_id))
  305.                 time.sleep(1)
  306.             elif epic_id.find('SEK') != -1:
  307.                 #print("!!DEBUG!!...skipping, FOUND SEK in..." + str(epic_id))
  308.                 time.sleep(1)
  309.             elif epic_id.find('NOK') != -1:
  310.                 #print("!!DEBUG!!...skipping, FOUND NOK in..." + str(epic_id))
  311.                 time.sleep(1)
  312.             elif epic_id.find('CNH') != -1:
  313.                 #print("!!DEBUG!!...skipping, FOUND CNH in..." + str(epic_id))
  314.                 time.sleep(1)
  315.             else:
  316.                 b_TRADE_OK = False
  317.                 while True:
  318.  
  319.                     now_time = strftime("%H:%M", localtime())
  320.                     # A bit about this, If market is not open...Don't trade it's respective pair!
  321.                     ###################EUROPE############################
  322.                     ###################EUROPE############################
  323.                     ###################EUROPE############################
  324.                     if is_between(str(now_time), ("06:00", "14:00")):
  325.                         #print("!!DEBUG!!...FRANKFURT MARKET OPEN!!")
  326.                         time.sleep(1)
  327.                         STR_CHECK = "EUR"
  328.                         if STR_CHECK in epic_id:
  329.                             b_TRADE_OK = True
  330.                             break
  331.                     ###################LONDON############################
  332.                     ###################LONDON############################
  333.                     ###################LONDON############################
  334.                     if is_between(str(now_time), ("07:00", "15:00")):
  335.                         #print("!!DEBUG!!...LONDON MARKET OPEN!!")
  336.                         time.sleep(1)
  337.                         STR_CHECK = "GBP"
  338.                         if STR_CHECK in epic_id:
  339.                             b_TRADE_OK = True
  340.                             break
  341.                     ###################NY############################
  342.                     ###################NY############################
  343.                     ###################NY############################
  344.                     if is_between(str(now_time), ("12:00", "22:00")):
  345.                         #print("!!DEBUG!!...NEW YORK MARKET OPEN!!")
  346.                         time.sleep(1)
  347.                         STR_CHECK = "USD"
  348.                         if STR_CHECK in epic_id:
  349.                             b_TRADE_OK = True
  350.                             break
  351.                     ###################AUS############################
  352.                     ###################AUS############################
  353.                     ###################AUS############################
  354.                     if is_between(str(now_time), ("22:00", "06:00")):
  355.                         #print("!!DEBUG!!...SYDNEY MARKET OPEN!!")
  356.                         time.sleep(1)
  357.                         STR_CHECK = "AUD"
  358.                         if STR_CHECK in epic_id:
  359.                             b_TRADE_OK = True
  360.                             break
  361.                     ###################TOKYO############################
  362.                     ###################TOKYO############################
  363.                     ###################TOKYO############################
  364.                     if is_between(str(now_time), ("23:00", "07:00")):
  365.                         #print("!!DEBUG!!...TOKYO MARKET OPEN!!")
  366.                         time.sleep(1)
  367.                         STR_CHECK = "JPY"
  368.                         if STR_CHECK in epic_id:
  369.                             b_TRADE_OK = True
  370.                             break
  371.                     break
  372.  
  373.                 if b_TRADE_OK:
  374.  
  375.                     current_bid = d['snapshot']['bid']
  376.                     ask_price = d['snapshot']['offer']
  377.                     spread = float(current_bid) - float(ask_price)
  378.                     if float(spread) >= -1:
  379.                         # tmp_lst.append(epic_id)
  380.                         # spreads_and_epics.append(tmp_lst)
  381.                         pick_from_epics.append(epic_id)
  382.                         # print ("bid : " + str(current_bid))
  383.                         # print ("ask : " + str(ask_price))
  384.                         # print ("-------------------------")
  385.                         # print ("spread : " + str(spread))
  386.                         # print ("-------------------------")
  387.                         print("!!DEBUG!!...FOUND GOOD EPIC..." +
  388.                               str(i_count) + "/" + str(len(main_epic_ids)))
  389.                         time.sleep(1)
  390.                     else:
  391.                         print(
  392.                             "!!DEBUG!!...skipping, NO GOOD EPIC....Checking next epic spreads..." +
  393.                             str(i_count) +
  394.                             "/" +
  395.                             str(
  396.                                 len(main_epic_ids)))
  397.                         time.sleep(1)
  398.                         continue
  399.  
  400.         except Exception as e:
  401.             print(e)
  402.             pass
  403.  
  404.     # sorted_list = sorted(spreads_and_epics, key=operator.itemgetter(1))
  405.     # for i in range(len(sorted_list)):
  406.         # print(sorted_list[i])
  407.     # print (max(sorted_list, key=lambda x: x[1]))
  408.  
  409.     # lowest_epic = max(sorted_list, key=lambda x: x[1])
  410.  
  411.     # return (str(lowest_epic[0]))
  412.     return (pick_from_epics)
  413.  
  414.  
  415. def are_we_going_to_trade(epic_id, TRADE_DIRECTION, limit):
  416.  
  417.     if TRADE_DIRECTION == "NONE":
  418.         return None
  419.  
  420.     limitDistance_value = str(limit)
  421.  
  422.     ##########################################################################
  423.     print(
  424.         "Order will be a " +
  425.         str(TRADE_DIRECTION) +
  426.         " Order, With a limit of: " +
  427.         str(limitDistance_value))
  428.     print(
  429.         "stopDistance_value for " +
  430.         str(epic_id) +
  431.         " will bet set at " +
  432.         str(stopDistance_value))
  433.     ##########################################################################
  434.  
  435.     # MAKE AN ORDER
  436.     base_url = REAL_OR_NO_REAL + '/positions/otc'
  437.     data = {
  438.         "direction": TRADE_DIRECTION,
  439.         "epic": epic_id,
  440.         "limitDistance": limitDistance_value,
  441.         "orderType": orderType_value,
  442.         "size": size_value,
  443.         "expiry": expiry_value,
  444.         "guaranteedStop": guaranteedStop_value,
  445.         "currencyCode": currencyCode_value,
  446.         "forceOpen": forceOpen_value,
  447.         "stopDistance": stopDistance_value}
  448.     r = requests.post(
  449.         base_url,
  450.         data=json.dumps(data),
  451.         headers=authenticated_headers)
  452.  
  453.     print("-----------------DEBUG-----------------")
  454.     print("#################DEBUG#################")
  455.     print(r.status_code)
  456.     print(r.reason)
  457.     print(r.text)
  458.     print("-----------------DEBUG-----------------")
  459.     print("#################DEBUG#################")
  460.  
  461.     d = json.loads(r.text)
  462.     deal_ref = d['dealReference']
  463.     time.sleep(1)
  464.     # CONFIRM MARKET ORDER
  465.     base_url = REAL_OR_NO_REAL + '/confirms/' + deal_ref
  466.     auth_r = requests.get(base_url, headers=authenticated_headers)
  467.     d = json.loads(auth_r.text)
  468.     DEAL_ID = d['dealId']
  469.     print("DEAL ID : " + str(d['dealId']))
  470.     print(d['dealStatus'])
  471.     print(d['reason'])
  472.  
  473.     if str(d['reason']) != "SUCCESS":
  474.         print("!!DEBUG!!...!!some thing occurred ERROR!!")
  475.         time.sleep(10)
  476.         print("-----------------DEBUG-----------------")
  477.         print("#################DEBUG#################")
  478.         print("!!DEBUG!! Resuming...")
  479.         print("-----------------DEBUG-----------------")
  480.         print("#################DEBUG#################")
  481.     else:
  482.         print("-----------------DEBUG-----------------")
  483.         print("#################DEBUG#################")
  484.         print("!!DEBUG!!...Yay, ORDER OPEN")
  485.         time.sleep(10)
  486.         print("-----------------DEBUG-----------------")
  487.         print("#################DEBUG#################")
  488.  
  489.  
  490. def Chandelier_Exit_formula(TRADE_DIR, ATR, Price):
  491.     # Chandelier Exit (long) = 22-day High - ATR(22) x 3
  492.     # Chandelier Exit (short) = 22-day Low + ATR(22) x 3
  493.  
  494.     if TRADE_DIR == "BUY":
  495.  
  496.         return float(Price) - float(ATR) * 3
  497.  
  498.     elif TRADE_DIR == "SELL":
  499.  
  500.         return float(Price) + float(ATR) * 3
  501.  
  502.  
  503. def calculate_stop_loss(d):
  504.  
  505.     price_ranges = []
  506.     closing_prices = []
  507.     first_time_round_loop = True
  508.     TR_prices = []
  509.     price_compare = "bid"
  510.  
  511.     for i in d['prices']:
  512.         if first_time_round_loop:
  513.             # First time round loop cannot get previous
  514.             closePrice = i['closePrice'][price_compare]
  515.             closing_prices.append(closePrice)
  516.             high_price = i['highPrice'][price_compare]
  517.             low_price = i['lowPrice'][price_compare]
  518.             price_range = float(high_price - closePrice)
  519.             price_ranges.append(price_range)
  520.             first_time_round_loop = False
  521.         else:
  522.             prev_close = closing_prices[-1]
  523.             ###############################
  524.             closePrice = i['closePrice'][price_compare]
  525.             closing_prices.append(closePrice)
  526.             high_price = i['highPrice'][price_compare]
  527.             low_price = i['lowPrice'][price_compare]
  528.             price_range = float(high_price - closePrice)
  529.             price_ranges.append(price_range)
  530.             TR = max(high_price - low_price,
  531.                      abs(high_price - prev_close),
  532.                      abs(low_price - prev_close))
  533.             TR_prices.append(TR)
  534.  
  535.     return str(int(float(max(TR_prices))))
  536.  
  537.  
  538. if __name__ == '__main__':
  539.  
  540.     while True:
  541.  
  542.         try:
  543.  
  544.             base_url = REAL_OR_NO_REAL + "/accounts"
  545.             auth_r = requests.get(base_url, headers=authenticated_headers)
  546.             d = json.loads(auth_r.text)
  547.  
  548.             print("-----------------DEBUG-----------------")
  549.             print("#################DEBUG#################")
  550.             print(auth_r.status_code)
  551.             print(auth_r.reason)
  552.             print(auth_r.text)
  553.             print("-----------------DEBUG-----------------")
  554.             print("#################DEBUG#################")
  555.  
  556.             for i in d['accounts']:
  557.                 if str(i['accountType']) == "SPREADBET":
  558.                     balance = i['balance']['balance']
  559.                     deposit = i['balance']['deposit']
  560.  
  561.             percent_used = percentage(deposit, balance)
  562.  
  563.             print("-----------------DEBUG-----------------")
  564.             print("#################DEBUG#################")
  565.             print(
  566.                 "!!DEBUG!!...Percent of account used ..." +
  567.                 str(percent_used))
  568.             print("-----------------DEBUG-----------------")
  569.             print("#################DEBUG#################")
  570.  
  571.             if float(percent_used) > 70:
  572.                 print("!!DEBUG!!...Don't trade, Too much margin used up already")
  573.                 time.sleep(60)
  574.                 continue
  575.             else:
  576.                 print("!!DEBUG!!...OK to trade, Account balance OK!!")
  577.  
  578.             tradeable_epic_ids = lowest_spread_epic()
  579.             shuffle(tradeable_epic_ids)
  580.  
  581.         except Exception as e:
  582.             print(e)
  583.             print("!!DEBUG!!...No Suitable Epics...Yet!!, Try again!!")
  584.             continue
  585.  
  586.         for epic_id in tradeable_epic_ids:
  587.  
  588.             base_url = REAL_OR_NO_REAL + "/prices/" + epic_id + "/MINUTE_15/16"
  589.             # Price resolution (MINUTE, MINUTE_2, MINUTE_3, MINUTE_5,
  590.             # MINUTE_10, MINUTE_15, MINUTE_30, HOUR, HOUR_2, HOUR_3,
  591.             # HOUR_4, DAY, WEEK, MONTH)
  592.             auth_r = requests.get(base_url, headers=authenticated_headers)
  593.             d = json.loads(auth_r.text)
  594.  
  595.             # print("-----------------DEBUG-----------------")
  596.             # print("#################DEBUG#################")
  597.             # print(auth_r.status_code)
  598.             # print(auth_r.reason)
  599.             # print(auth_r.text)
  600.             # print("-----------------DEBUG-----------------")
  601.             # print("#################DEBUG#################")
  602.  
  603.             high_prices = []
  604.             low_prices = []
  605.             mid_prices = []
  606.             close_prices = []
  607.             ATR = calculate_stop_loss(d)
  608.  
  609.             remaining_allowance = d['allowance']['remainingAllowance']
  610.             reset_time = humanize_time(int(d['allowance']['allowanceExpiry']))
  611.             print("-----------------DEBUG-----------------")
  612.             print("#################DEBUG#################")
  613.             print("Remaining API Calls left: " + str(remaining_allowance))
  614.             print("Time to API Key reset: " + str(reset_time))
  615.             print("-----------------DEBUG-----------------")
  616.             print("#################DEBUG#################")
  617.  
  618.             for i in d['prices']:
  619.  
  620.                 if i['highPrice']['bid'] is not None:
  621.                     highPrice = i['highPrice']['bid']
  622.                     high_prices.append(highPrice)
  623.                 ########################################
  624.                 if i['lowPrice']['bid'] is not None:
  625.                     lowPrice = i['lowPrice']['bid']
  626.                     low_prices.append(lowPrice)
  627.                 ########################################
  628.                 if i['closePrice']['bid'] is not None:
  629.                     closePrice = i['lowPrice']['bid']
  630.                     close_prices.append(closePrice)
  631.                 ########################################
  632.                 mid_prices.append(float(midpoint(highPrice, lowPrice)))
  633.  
  634.             close_prices = numpy.asarray(close_prices)
  635.             low_prices = numpy.asarray(low_prices)
  636.             high_prices = numpy.asarray(high_prices)
  637.             mid_prices = numpy.asarray(mid_prices)
  638.  
  639.             xi = numpy.arange(0, len(low_prices))
  640.  
  641.             close_prices_slope, close_prices_intercept, close_prices_r_value, close_prices_p_value, close_prices_std_err = stats.linregress(
  642.                 xi, close_prices)
  643.             low_prices_slope, low_prices_intercept, low_prices_r_value, low_prices_p_value, low_prices_std_err = stats.linregress(
  644.                 xi, low_prices)
  645.             high_prices_slope, high_prices_intercept, high_prices_r_value, high_prices_p_value, high_prices_std_err = stats.linregress(
  646.                 xi, high_prices)
  647.             mid_prices_slope, mid_prices_intercept, mid_prices_r_value, mid_prices_p_value, mid_prices_std_err = stats.linregress(
  648.                 xi, mid_prices)
  649.  
  650.             # close_prices_line = close_prices_slope * xi + close_prices_intercept
  651.             # low_prices_line = low_prices_slope * xi + low_prices_intercept
  652.             # high_prices_line = high_prices_slope * xi + high_prices_intercept
  653.             # mid_prices_line = mid_prices_slope * xi + mid_prices_intercept
  654.  
  655.             # plt.plot(
  656.             # xi,
  657.             # low_prices_line,
  658.             # xi,
  659.             # high_prices_line,
  660.             # xi,
  661.             # close_prices,
  662.             # 'g--',
  663.             # xi,
  664.             # mid_prices_line)
  665.             # plt.fill_between(
  666.             # xi,
  667.             # low_prices_line,
  668.             # high_prices_line,
  669.             # facecolor='green',
  670.             # alpha=0.5)
  671.             # plt.xlabel('X Axis')
  672.             # plt.ylabel('Y Axis')
  673.             # plt.show()
  674.             # plt.clf()
  675.  
  676.             base_url = REAL_OR_NO_REAL + '/markets/' + epic_id
  677.             auth_r = requests.get(
  678.                 base_url, headers=authenticated_headers)
  679.             d = json.loads(auth_r.text)
  680.  
  681.            # print("-----------------DEBUG-----------------")
  682.            # print("#################DEBUG#################")
  683.            # print(auth_r.status_code)
  684.            # print(auth_r.reason)
  685.            # print(auth_r.text)
  686.            # print("-----------------DEBUG-----------------")
  687.            # print("#################DEBUG#################")
  688.  
  689.             current_bid = d['snapshot']['bid']
  690.  
  691.             if distance(current_bid, mid_prices_intercept) > 1:  # Upper Line
  692.                 TRADE_DIRECTION = "BUY"
  693.                 pip_limit = int(abs(float(max(high_prices)) -
  694.                                     float(current_bid)) / SL_MULTIPLIER)
  695.                 print("-----------------DEBUG-----------------")
  696.                 print("#################DEBUG#################")
  697.                 print("!!DEBUG!!...BUY!!")
  698.                 print(str(epic_id))
  699.                 print(
  700.                     "!!DEBUG!!...Take Profit@...." +
  701.                     str(pip_limit) +
  702.                     " pips")
  703.                 print("-----------------DEBUG-----------------")
  704.                 print("#################DEBUG#################")
  705.                 ce_stop = Chandelier_Exit_formula(
  706.                     TRADE_DIRECTION, ATR, min(low_prices))
  707.                 tmp_stop = int(abs(float(current_bid) - (ce_stop)))
  708.             elif distance(current_bid, mid_prices_intercept) < -1:  # Lower Line
  709.                 TRADE_DIRECTION = "SELL"
  710.                 pip_limit = int(abs(float(min(low_prices)) -
  711.                                     float(current_bid)) / SL_MULTIPLIER)
  712.                 print("-----------------DEBUG-----------------")
  713.                 print("#################DEBUG#################")
  714.                 print("!!DEBUG!!...SELL!!")
  715.                 print(str(epic_id))
  716.                 print(
  717.                     "!!DEBUG!!...Take Profit@...." +
  718.                     str(pip_limit) +
  719.                     " pips")
  720.                 print("-----------------DEBUG-----------------")
  721.                 print("#################DEBUG#################")
  722.                 ce_stop = Chandelier_Exit_formula(
  723.                     TRADE_DIRECTION, ATR, max(high_prices))
  724.                 tmp_stop = int(abs(float(current_bid) - (ce_stop)))
  725.  
  726.             else:
  727.                 pip_limit = 9999999
  728.                 tmp_stop = "999999"
  729.                 TRADE_DIRECTION = "NONE"
  730.                 print("!!DEBUG!!...Within trading range...Leave!!")
  731.  
  732.             if int(pip_limit) <= 1:
  733.                 print("!!DEBUG!!...No Trade!!, Pip Limit Under 1")
  734.                 TRADE_DIRECTION = "NONE"
  735.  
  736.             stopDistance_value = str(tmp_stop)
  737.  
  738.             if int(stopDistance_value) <= LOW_SL_WATERMARK or int(
  739.                     stopDistance_value) >= HIGH_SL_WATERMARK:
  740.                 TRADE_DIRECTION = "NONE"
  741.  
  742.             try:
  743.                 are_we_going_to_trade(epic_id, TRADE_DIRECTION, pip_limit)
  744.             except Exception as e:
  745.                 print(e)
  746.                 print("Something fucked up!!, Try again!!")
  747.                 continue
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement