Guest User

FULLY AUTOMATED TRADING CODE v2

a guest
May 15th, 2018
5,480
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 35.17 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. ####################################################
  7. # Scikit's LinearRegression model
  8. # from sklearn.linear_model import LinearRegression
  9. ####################################################
  10. import numpy
  11. import pandas
  12. import matplotlib.pyplot as plt
  13. import matplotlib.dates as mdates
  14. from scipy import stats
  15. import math
  16. import requests
  17. import json
  18. import time
  19. import random
  20. from time import localtime, strftime
  21. import datetime
  22. import calendar
  23. from random import shuffle
  24. import holidays
  25. import pytz
  26.  
  27. # Frankfurt
  28. # Germany
  29. # EUR
  30. # print("Frankfurt Market Status:...." + str(is_between(str(now_time), ("06:00", "14:00"))))
  31. # London
  32. # Great Britain
  33. # GBP
  34. # print("London Market Status:...." + str(is_between(str(now_time), ("07:00", "15:00"))))
  35. # New York
  36. # United States
  37. # USD
  38. # print("New York Market Status:...." + str(is_between(str(now_time), ("12:00", "20:30"))))
  39. # Sydney
  40. # Austrailia
  41. # AUD
  42. # print("Sydney Market Status:...." + str(is_between(str(now_time), ("22:00", "06:30"))))
  43. # Tokyo
  44. # Japan
  45. # JPY
  46. # print("Tokyo Market Status:...." + str(is_between(str(now_time),
  47. # ("23:00", "07:30"))))
  48.  
  49. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  50. # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  51. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
  52. # NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE
  53. # DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY,
  54. # WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  55. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  56. # SOFTWARE.
  57.  
  58. print("########################################################################################")
  59. print("########################################################################################")
  60. print("########################################################################################")
  61. print("THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.")
  62. print("########################################################################################")
  63. print("########################################################################################")
  64. print("########################################################################################")
  65.  
  66. # ALL EPICS
  67. main_epic_ids = [
  68.     'CS.D.AUDUSD.TODAY.IP',
  69.     'CS.D.EURCHF.TODAY.IP',
  70.     'CS.D.EURGBP.TODAY.IP',
  71.     'CS.D.EURJPY.TODAY.IP',
  72.     'CS.D.EURUSD.TODAY.IP',
  73.     'CS.D.GBPEUR.TODAY.IP',
  74.     'CS.D.GBPUSD.TODAY.IP',
  75.     'CS.D.USDCAD.TODAY.IP',
  76.     'CS.D.USDCHF.TODAY.IP',
  77.     'CS.D.USDJPY.TODAY.IP',
  78.     'CS.D.CADCHF.TODAY.IP',
  79.     'CS.D.CADJPY.TODAY.IP',
  80.     'CS.D.CHFJPY.TODAY.IP',
  81.     'CS.D.EURCAD.TODAY.IP',
  82.     'CS.D.EURSGD.TODAY.IP',
  83.     'CS.D.EURZAR.TODAY.IP',
  84.     'CS.D.GBPCAD.TODAY.IP',
  85.     'CS.D.GBPCHF.TODAY.IP',
  86.     'CS.D.GBPJPY.TODAY.IP',
  87.     'CS.D.GBPSGD.TODAY.IP',
  88.     'CS.D.GBPZAR.TODAY.IP',
  89.     'CS.D.MXNJPY.TODAY.IP',
  90.     'CS.D.NOKJPY.TODAY.IP',
  91.     'CS.D.PLNJPY.TODAY.IP',
  92.     'CS.D.SEKJPY.TODAY.IP',
  93.     'CS.D.SGDJPY.TODAY.IP',
  94.     'CS.D.USDSGD.TODAY.IP',
  95.     'CS.D.USDZAR.TODAY.IP',
  96.     'CS.D.AUDCAD.TODAY.IP',
  97.     'CS.D.AUDCHF.TODAY.IP',
  98.     'CS.D.AUDEUR.TODAY.IP',
  99.     'CS.D.AUDGBP.TODAY.IP',
  100.     'CS.D.AUDJPY.TODAY.IP',
  101.     'CS.D.AUDNZD.TODAY.IP',
  102.     'CS.D.AUDSGD.TODAY.IP',
  103.     'CS.D.EURAUD.TODAY.IP',
  104.     'CS.D.EURNZD.TODAY.IP',
  105.     'CS.D.GBPAUD.TODAY.IP',
  106.     'CS.D.GBPNZD.TODAY.IP',
  107.     'CS.D.NZDAUD.TODAY.IP',
  108.     'CS.D.NZDCAD.TODAY.IP',
  109.     'CS.D.NZDCHF.TODAY.IP',
  110.     'CS.D.NZDEUR.TODAY.IP',
  111.     'CS.D.NZDGBP.TODAY.IP',
  112.     'CS.D.NZDJPY.TODAY.IP',
  113.     'CS.D.NZDUSD.TODAY.IP',
  114.     'CS.D.CHFHUF.TODAY.IP',
  115.     'CS.D.EURCZK.TODAY.IP',
  116.     'CS.D.EURHUF.TODAY.IP',
  117.     'CS.D.EURILS.TODAY.IP',
  118.     'CS.D.EURMXN.TODAY.IP',
  119.     'CS.D.EURPLN.TODAY.IP',
  120.     'CS.D.EURTRY.TODAY.IP',
  121.     'CS.D.GBPCZK.TODAY.IP',
  122.     'CS.D.GBPHUF.TODAY.IP',
  123.     'CS.D.GBPILS.TODAY.IP',
  124.     'CS.D.GBPMXN.TODAY.IP',
  125.     'CS.D.GBPPLN.TODAY.IP',
  126.     'CS.D.GBPTRY.TODAY.IP',
  127.     'CS.D.TRYJPY.TODAY.IP',
  128.     'CS.D.USDCZK.TODAY.IP',
  129.     'CS.D.USDHUF.TODAY.IP',
  130.     'CS.D.USDILS.TODAY.IP',
  131.     'CS.D.USDMXN.TODAY.IP',
  132.     'CS.D.USDPLN.TODAY.IP',
  133.     'CS.D.USDTRY.TODAY.IP',
  134.     'CS.D.CADNOK.TODAY.IP',
  135.     'CS.D.CHFNOK.TODAY.IP',
  136.     'CS.D.EURDKK.TODAY.IP',
  137.     'CS.D.EURNOK.TODAY.IP',
  138.     'CS.D.EURSEK.TODAY.IP',
  139.     'CS.D.GBPDKK.TODAY.IP',
  140.     'CS.D.GBPNOK.TODAY.IP',
  141.     'CS.D.GBPSEK.TODAY.IP',
  142.     'CS.D.NOKSEK.TODAY.IP',
  143.     'CS.D.USDDKK.TODAY.IP',
  144.     'CS.D.USDNOK.TODAY.IP',
  145.     'CS.D.USDSEK.TODAY.IP',
  146.     'CS.D.AUDCNH.TODAY.IP',
  147.     'CS.D.CADCNH.TODAY.IP',
  148.     'CS.D.CNHJPY.TODAY.IP',
  149.     'CS.D.BRLJPY.TODAY.IP',
  150.     'CS.D.GBPINR.TODAY.IP',
  151.     'CS.D.USDBRL.TODAY.IP',
  152.     'CS.D.USDIDR.TODAY.IP',
  153.     'CS.D.USDINR.TODAY.IP',
  154.     'CS.D.USDKRW.TODAY.IP',
  155.     'CS.D.USDMYR.TODAY.IP',
  156.     'CS.D.USDPHP.TODAY.IP',
  157.     'CS.D.USDTWD.TODAY.IP',
  158.     'CS.D.EURCNH.TODAY.IP',
  159.     'CS.D.sp_EURRUB.TODAY.IP',
  160.     'CS.D.GBPCNH.TODAY.IP',
  161.     'CS.D.NZDCNH.TODAY.IP',
  162.     'CS.D.USDCNH.TODAY.IP',
  163.     'CS.D.sp_USDRUB.TODAY.IP']
  164. # ALL EPICS
  165.  
  166. # TESTINGs
  167. # main_epic_ids = [
  168.     # 'CS.D.AUDUSD.TODAY.IP',
  169.     # 'CS.D.EURGBP.TODAY.IP',
  170.     # 'CS.D.EURJPY.TODAY.IP',
  171.     # 'CS.D.EURUSD.TODAY.IP',
  172.     # 'CS.D.GBPUSD.TODAY.IP',
  173.     # 'CS.D.USDCAD.TODAY.IP',
  174.     # 'CS.D.USDCHF.TODAY.IP',
  175.     # 'CS.D.USDJPY.TODAY.IP',
  176.     # 'CS.D.AUDEUR.TODAY.IP',
  177.     # 'CS.D.AUDGBP.TODAY.IP',
  178.     # 'CS.D.AUDJPY.TODAY.IP',
  179.     # 'CS.D.EURAUD.TODAY.IP',
  180.     # 'CS.D.GBPAUD.TODAY.IP']
  181. # TESTING
  182.  
  183.  
  184. # TIME_FRAMES = ["MINUTE/1", "MINUTE_2/1", "MINUTE_3/1", "MINUTE_5/1", "MINUTE_10/1",
  185. # "MINUTE_15/1", "MINUTE_30/1", "HOUR/1", "HOUR_2/1", "HOUR_3/1", "HOUR_4/1",
  186. # "DAY/1", "WEEK/1", "MONTH/1"]
  187.  
  188. b_REAL = True
  189.  
  190. if b_REAL:
  191.     REAL_OR_NO_REAL = 'https://api.ig.com/gateway/deal'
  192.     API_ENDPOINT = "https://api.ig.com/gateway/deal/session"
  193.     API_KEY = 'API KEY'
  194.     data = {"identifier": "USERNAME", "password": "PASSWORD"}
  195. else:
  196.     REAL_OR_NO_REAL = 'https://demo-api.ig.com/gateway/deal'
  197.     API_ENDPOINT = "https://demo-api.ig.com/gateway/deal/session"
  198.     API_KEY = 'API KEY'
  199.     data = {"identifier": "USERNAME", "password": "PASSWORD"}
  200.  
  201. headers = {'Content-Type': 'application/json; charset=utf-8',
  202.            'Accept': 'application/json; charset=utf-8',
  203.            'X-IG-API-KEY': API_KEY,
  204.            'Version': '2'
  205.            }
  206.  
  207. r = requests.post(API_ENDPOINT, data=json.dumps(data), headers=headers)
  208.  
  209. headers_json = dict(r.headers)
  210. CST_token = headers_json["CST"]
  211. print(R"CST : " + CST_token)
  212. x_sec_token = headers_json["X-SECURITY-TOKEN"]
  213. print(R"X-SECURITY-TOKEN : " + x_sec_token)
  214.  
  215. # GET ACCOUNTS
  216. base_url = REAL_OR_NO_REAL + '/accounts'
  217. authenticated_headers = {'Content-Type': 'application/json; charset=utf-8',
  218.                          'Accept': 'application/json; charset=utf-8',
  219.                          'X-IG-API-KEY': API_KEY,
  220.                          'CST': CST_token,
  221.                          'X-SECURITY-TOKEN': x_sec_token}
  222.  
  223. auth_r = requests.get(base_url, headers=authenticated_headers)
  224. d = json.loads(auth_r.text)
  225.  
  226. # print ("-----------------DEBUG-----------------")
  227. # print ("#################DEBUG#################")
  228. # print(auth_r.status_code)
  229. # print(auth_r.reason)
  230. # print (auth_r.text)
  231. # print ("-----------------DEBUG-----------------")
  232. # print ("#################DEBUG#################")
  233.  
  234. for i in d['accounts']:
  235.     if str(i['accountType']) == "SPREADBET":
  236.         print("Spreadbet Account ID is : " + str(i['accountId']))
  237.         spreadbet_acc_id = str(i['accountId'])
  238.  
  239. # SET SPREAD BET ACCOUNT AS DEFAULT
  240. base_url = REAL_OR_NO_REAL + '/session'
  241. data = {"accountId": spreadbet_acc_id, "defaultAccount": "True"}
  242. auth_r = requests.put(
  243.     base_url,
  244.     data=json.dumps(data),
  245.     headers=authenticated_headers)
  246.  
  247. # print ("-----------------DEBUG-----------------")
  248. # print ("#################DEBUG#################")
  249. # print(auth_r.status_code)
  250. # print(auth_r.reason)
  251. # print (auth_r.text)
  252. # print ("-----------------DEBUG-----------------")
  253. # print ("#################DEBUG#################")
  254. # ERROR about account ID been the same, Ignore!
  255.  
  256. ##########################################################################
  257. ##########################END OF LOGIN CODE###############################
  258. ##########################END OF LOGIN CODE###############################
  259. ##########################END OF LOGIN CODE###############################
  260. ##########################END OF LOGIN CODE###############################
  261. ##########################################################################
  262. # PROGRAMMABLE VALUES
  263. # SET INITIAL VARIABLES, Hacky for now!
  264. orderType_value = "MARKET"
  265. size_value = "1"
  266. expiry_value = "DFB"
  267. guaranteedStop_value = True
  268. currencyCode_value = "GBP"
  269. forceOpen_value = True
  270. stopDistance_value = "15"  # Make this a global variable for ease!
  271.  
  272. SL_MULTIPLIER = 3.24
  273. LOW_SL_WATERMARK = 20
  274. HIGH_SL_WATERMARK = 70
  275. STR_CHECK = ""
  276.  
  277. set(pytz.all_timezones_set)
  278. YEAR_var = 2018
  279.  
  280.  
  281. def is_between(time, time_range):
  282.     if time_range[1] < time_range[0]:
  283.         return time >= time_range[0] or time <= time_range[1]
  284.     return time_range[0] <= time <= time_range[1]
  285.  
  286.  
  287. def midpoint(p1, p2):
  288.     return (p1 + p2) / 2
  289.  
  290.  
  291. def distance(a, b):
  292.     if (a == b):
  293.         return 0
  294.     elif (a < 0) and (b < 0) or (a > 0) and (b > 0):
  295.         if (a < b):
  296.             return (abs(abs(a) - abs(b)))
  297.         else:
  298.             return -(abs(abs(a) - abs(b)))
  299.     else:
  300.         return math.copysign((abs(a) + abs(b)), b)
  301.  
  302.  
  303. def percentage(part, whole):
  304.     return 100 * float(part) / float(whole)
  305.  
  306.  
  307. def humanize_time(secs):
  308.     mins, secs = divmod(secs, 60)
  309.     hours, mins = divmod(mins, 60)
  310.     return '%02d:%02d:%02d' % (hours, mins, secs)
  311.  
  312.  
  313. def find_good_epics():
  314.     spreads_and_epics = []
  315.     i_count = 0
  316.     pick_from_epics = []
  317.     full_hol_list = []
  318.     ###################################################################
  319.     tz = pytz.timezone('Europe/Berlin')
  320.     todays_date = str(datetime.datetime.now(tz=tz).strftime('%Y-%m-%d'))
  321.     ger_today = str(str("GER_" + str(todays_date)))
  322.     print("Europe/Berlin :- Today's Date is ..." + str(todays_date))
  323.     ###################################################################
  324.     tz = pytz.timezone('Europe/London')
  325.     todays_date = str(datetime.datetime.now(tz=tz).strftime('%Y-%m-%d'))
  326.     gb_today = str(str("GB_" + str(todays_date)))
  327.     print("Europe/London :- Today's Date is ..." + str(todays_date))
  328.     ###################################################################
  329.     tz = pytz.timezone('America/New_York')
  330.     todays_date = str(datetime.datetime.now(tz=tz).strftime('%Y-%m-%d'))
  331.     us_today = str(str("US_" + str(todays_date)))
  332.     print("America/New_York :- Today's Date is ..." + str(todays_date))
  333.     ###################################################################
  334.     tz = pytz.timezone('Australia/Sydney')
  335.     todays_date = str(datetime.datetime.now(tz=tz).strftime('%Y-%m-%d'))
  336.     aus_today = str(str("AUS_" + str(todays_date)))
  337.     print("Australia/Sydney :- Today's Date is ..." + str(todays_date))
  338.     ###################################################################
  339.     tz = pytz.timezone('Asia/Tokyo')
  340.     todays_date = str(datetime.datetime.now(tz=tz).strftime('%Y-%m-%d'))
  341.     jp_today = str(str("JP_" + str(todays_date)))
  342.     print("Asia/Tokyo :- Today's Date is ..." + str(todays_date))
  343.     ###################################################################
  344.     b_ger_hol = False
  345.     b_uk_hol = False
  346.     b_us_hol = False
  347.     b_aus_hol = False
  348.     b_jp_hol = False
  349.  
  350.     for date, name in sorted(holidays.DE(years=YEAR_var).items()):
  351.         full_hol_list.append(str("GER_" + str(date)))
  352.     # print("###########################")
  353.     for date, name in sorted(holidays.UK(years=YEAR_var).items()):
  354.         full_hol_list.append(str("GB_" + str(date)))
  355.     # print("###########################")
  356.     for date, name in sorted(holidays.US(years=YEAR_var).items()):
  357.         full_hol_list.append(str("US_" + str(date)))
  358.     # print("###########################")
  359.     for date, name in sorted(holidays.AU(years=YEAR_var).items()):
  360.         full_hol_list.append(str("AUS_" + str(date)))
  361.     # print("###########################")
  362.     for date, name in sorted(holidays.JP(years=YEAR_var).items()):
  363.         full_hol_list.append(str("JP_" + str(date)))
  364.     # print("###########################")
  365.  
  366.     full_hol_list = sorted(full_hol_list)
  367.  
  368.     for d in full_hol_list:
  369.         # print (d)
  370.         if str(d) == ger_today:
  371.             b_ger_hol = True
  372.         if str(d) == gb_today:
  373.             b_uk_hol = True
  374.         if str(d) == us_today:
  375.             b_us_hol = True
  376.         if str(d) == aus_today:
  377.             b_aus_hol = True
  378.         if str(d) == jp_today:
  379.             b_jp_hol = True
  380.  
  381.     for epic_id in main_epic_ids:
  382.         tmp_lst = []
  383.         base_url = REAL_OR_NO_REAL + '/markets/' + epic_id
  384.         auth_r = requests.get(base_url, headers=authenticated_headers)
  385.         d = json.loads(auth_r.text)
  386.  
  387.         try:
  388.             i_count = i_count + 1
  389.             if epic_id.find('MXN') != -1:
  390.                 # print("!!DEBUG!!...skipping, FOUND MXN in..." + str(epic_id))
  391.                 time.sleep(1)
  392.             elif epic_id.find('SEK') != -1:
  393.                 # print("!!DEBUG!!...skipping, FOUND SEK in..." + str(epic_id))
  394.                 time.sleep(1)
  395.             elif epic_id.find('NOK') != -1:
  396.                 # print("!!DEBUG!!...skipping, FOUND NOK in..." + str(epic_id))
  397.                 time.sleep(1)
  398.             elif epic_id.find('CNH') != -1:
  399.                 # print("!!DEBUG!!...skipping, FOUND CNH in..." + str(epic_id))
  400.                 time.sleep(1)
  401.             else:
  402.                 b_TRADE_OK = False
  403.                 while True:
  404.  
  405.                     ###################EUROPE############################
  406.                     ###################EUROPE############################
  407.                     ###################EUROPE############################
  408.                     tz = pytz.timezone('Europe/Berlin')
  409.                     now_time = datetime.datetime.now(tz=tz).strftime('%H:%M')
  410.                     # print ("!!DEBUG!! Europe/Berlin:" + str(now_time))
  411.                     if is_between(str(now_time), ("08:00", "16:00")):
  412.                         # print("!!DEBUG!!...FRANKFURT MARKET OPEN!!")
  413.                         STR_CHECK = "EUR"
  414.                         if STR_CHECK in epic_id and b_ger_hol == False:
  415.                             time.sleep(2)
  416.                             b_TRADE_OK = True
  417.                             break
  418.                     ###################LONDON############################
  419.                     ###################LONDON############################
  420.                     ###################LONDON############################
  421.                     tz = pytz.timezone('Europe/London')
  422.                     now_time = datetime.datetime.now(tz=tz).strftime('%H:%M')
  423.                     while True:
  424.                         if is_between(str(now_time), ("22:00", "22:59")):
  425.                             time.sleep(1)  # Sleeping for the tally up hour
  426.                             print("!!DEBUG!! Tally Up hour:" + str(now_time))
  427.                             now_time = datetime.datetime.now(
  428.                                 tz=tz).strftime('%H:%M')
  429.                         else:
  430.                             break
  431.                     # print ("!!DEBUG!! Europe/London:" + str(now_time))
  432.                     if is_between(str(now_time), ("08:00", "16:00")):
  433.                         # print("!!DEBUG!!...LONDON MARKET OPEN!!")
  434.                         STR_CHECK = "GBP"
  435.                         if STR_CHECK in epic_id and b_uk_hol == False:
  436.                             time.sleep(2)
  437.                             b_TRADE_OK = True
  438.                             break
  439.                     ###################NY############################
  440.                     ###################NY############################
  441.                     ###################NY############################
  442.                     tz = pytz.timezone('America/New_York')
  443.                     now_time = datetime.datetime.now(tz=tz).strftime('%H:%M')
  444.                     # print ("!!DEBUG!! America/New_York:" + str(now_time))
  445.                     if is_between(str(now_time), ("08:00", "16:00")):
  446.                         # print("!!DEBUG!!...NEW YORK MARKET OPEN!!")
  447.                         STR_CHECK = "USD"
  448.                         if STR_CHECK in epic_id and b_us_hol == False:
  449.                             time.sleep(2)
  450.                             b_TRADE_OK = True
  451.                             break
  452.                     ###################AUS############################
  453.                     ###################AUS############################
  454.                     ###################AUS############################
  455.                     tz = pytz.timezone('Australia/Sydney')
  456.                     now_time = datetime.datetime.now(tz=tz).strftime('%H:%M')
  457.                     # print ("!!DEBUG!! Australia/Sydney:" + str(now_time))
  458.                     if is_between(str(now_time), ("08:00", "16:00")):
  459.                         # print("!!DEBUG!!...SYDNEY MARKET OPEN!!")
  460.                         STR_CHECK = "AUD"
  461.                         if STR_CHECK in epic_id and b_aus_hol == False:
  462.                             time.sleep(2)
  463.                             b_TRADE_OK = True
  464.                             break
  465.                     ###################TOKYO############################
  466.                     ###################TOKYO############################
  467.                     ###################TOKYO############################
  468.                     tz = pytz.timezone('Asia/Tokyo')
  469.                     now_time = datetime.datetime.now(tz=tz).strftime('%H:%M')
  470.                     # print ("!!DEBUG!! Asia/Tokyo:" + str(now_time))
  471.                     if is_between(str(now_time), ("08:00", "16:00")):
  472.                         # print("!!DEBUG!!...TOKYO MARKET OPEN!!")
  473.                         STR_CHECK = "JPY"
  474.                         if STR_CHECK in epic_id and b_jp_hol == False:
  475.                             time.sleep(2)
  476.                             b_TRADE_OK = True
  477.                             break
  478.                     break
  479.  
  480.                 if b_TRADE_OK:
  481.  
  482.                     current_bid = d['snapshot']['bid']
  483.                     ask_price = d['snapshot']['offer']
  484.                     spread = float(current_bid) - float(ask_price)
  485.                     if float(spread) >= -2:
  486.                         pick_from_epics.append(epic_id)
  487.                         print("!!DEBUG!!...FOUND GOOD EPIC..." +
  488.                               str(i_count) + "/" + str(len(main_epic_ids)))
  489.                         time.sleep(1)
  490.                     else:
  491.                         print(
  492.                             "!!DEBUG!!...skipping, NO GOOD EPIC....Checking next epic spreads..." +
  493.                             str(i_count) +
  494.                             "/" +
  495.                             str(
  496.                                 len(main_epic_ids)))
  497.                         time.sleep(1)
  498.                         continue
  499.  
  500.         except Exception as e:
  501.             print(e)
  502.             pass
  503.  
  504.     # sorted_list = sorted(spreads_and_epics, key=operator.itemgetter(1))
  505.     # for i in range(len(sorted_list)):
  506.         # print(sorted_list[i])
  507.     # print (max(sorted_list, key=lambda x: x[1]))
  508.  
  509.     # lowest_epic = max(sorted_list, key=lambda x: x[1])
  510.  
  511.     # return (str(lowest_epic[0]))
  512.     return (pick_from_epics)
  513.  
  514.  
  515. def are_we_going_to_trade(epic_id, TRADE_DIRECTION, limit):
  516.  
  517.     if TRADE_DIRECTION == "NONE":
  518.         return None
  519.  
  520.     limitDistance_value = str(limit)
  521.  
  522.     ##########################################################################
  523.     print(
  524.         "Order will be a " +
  525.         str(TRADE_DIRECTION) +
  526.         " Order, With a limit of: " +
  527.         str(limitDistance_value))
  528.     print(
  529.         "stopDistance_value for " +
  530.         str(epic_id) +
  531.         " will bet set at " +
  532.         str(stopDistance_value))
  533.     ##########################################################################
  534.  
  535.     # MAKE AN ORDER
  536.     base_url = REAL_OR_NO_REAL + '/positions/otc'
  537.     data = {
  538.         "direction": TRADE_DIRECTION,
  539.         "epic": epic_id,
  540.         "limitDistance": limitDistance_value,
  541.         "orderType": orderType_value,
  542.         "size": size_value,
  543.         "expiry": expiry_value,
  544.         "guaranteedStop": guaranteedStop_value,
  545.         "currencyCode": currencyCode_value,
  546.         "forceOpen": forceOpen_value,
  547.         "stopDistance": stopDistance_value}
  548.     r = requests.post(
  549.         base_url,
  550.         data=json.dumps(data),
  551.         headers=authenticated_headers)
  552.  
  553.     print("-----------------DEBUG-----------------")
  554.     print("#################DEBUG#################")
  555.     print(r.status_code)
  556.     print(r.reason)
  557.     print(r.text)
  558.     print("-----------------DEBUG-----------------")
  559.     print("#################DEBUG#################")
  560.  
  561.     d = json.loads(r.text)
  562.     deal_ref = d['dealReference']
  563.     time.sleep(1)
  564.     # CONFIRM MARKET ORDER
  565.     base_url = REAL_OR_NO_REAL + '/confirms/' + deal_ref
  566.     auth_r = requests.get(base_url, headers=authenticated_headers)
  567.     d = json.loads(auth_r.text)
  568.     DEAL_ID = d['dealId']
  569.     print("DEAL ID : " + str(d['dealId']))
  570.     print(d['dealStatus'])
  571.     print(d['reason'])
  572.  
  573.     if str(d['reason']) != "SUCCESS":
  574.         print("!!DEBUG!!...!!some thing occurred ERROR!!")
  575.         time.sleep(10)
  576.         print("-----------------DEBUG-----------------")
  577.         print("#################DEBUG#################")
  578.         print("!!DEBUG!! Resuming...")
  579.         print("-----------------DEBUG-----------------")
  580.         print("#################DEBUG#################")
  581.     else:
  582.         print("-----------------DEBUG-----------------")
  583.         print("#################DEBUG#################")
  584.         print("!!DEBUG!!...Yay, ORDER OPEN")
  585.         time.sleep(10)
  586.         print("-----------------DEBUG-----------------")
  587.         print("#################DEBUG#################")
  588.  
  589.  
  590. def Chandelier_Exit_formula(TRADE_DIR, ATR, Price):
  591.     # Chandelier Exit (long) = 22-day High - ATR(22) x 3
  592.     # Chandelier Exit (short) = 22-day Low + ATR(22) x 3
  593.  
  594.     if TRADE_DIR == "BUY":
  595.  
  596.         return float(Price) - float(ATR) * 3
  597.  
  598.     elif TRADE_DIR == "SELL":
  599.  
  600.         return float(Price) + float(ATR) * 3
  601.  
  602.  
  603. def calculate_stop_loss(d):
  604.  
  605.     price_ranges = []
  606.     closing_prices = []
  607.     first_time_round_loop = True
  608.     TR_prices = []
  609.     price_compare = "bid"
  610.  
  611.     for i in d['prices']:
  612.         if first_time_round_loop:
  613.             ###########################################
  614.             # First time round loop cannot get previous
  615.             ###########################################
  616.             closePrice = i['closePrice'][price_compare]
  617.             closing_prices.append(closePrice)
  618.             high_price = i['highPrice'][price_compare]
  619.             low_price = i['lowPrice'][price_compare]
  620.             price_range = float(high_price - closePrice)
  621.             price_ranges.append(price_range)
  622.             first_time_round_loop = False
  623.         else:
  624.             prev_close = closing_prices[-1]
  625.             ###########################################
  626.             closePrice = i['closePrice'][price_compare]
  627.             closing_prices.append(closePrice)
  628.             high_price = i['highPrice'][price_compare]
  629.             low_price = i['lowPrice'][price_compare]
  630.             price_range = float(high_price - closePrice)
  631.             price_ranges.append(price_range)
  632.             TR = max(high_price - low_price,
  633.                      abs(high_price - prev_close),
  634.                      abs(low_price - prev_close))
  635.             TR_prices.append(TR)
  636.  
  637.     return str(int(float(max(TR_prices))))
  638.  
  639.  
  640. if __name__ == '__main__':
  641.  
  642.     while True:
  643.  
  644.         try:
  645.  
  646.             base_url = REAL_OR_NO_REAL + "/accounts"
  647.             auth_r = requests.get(base_url, headers=authenticated_headers)
  648.             d = json.loads(auth_r.text)
  649.  
  650.             print("-----------------DEBUG-----------------")
  651.             print("#################DEBUG#################")
  652.             print(auth_r.status_code)
  653.             print(auth_r.reason)
  654.             print(auth_r.text)
  655.             print("-----------------DEBUG-----------------")
  656.             print("#################DEBUG#################")
  657.  
  658.             for i in d['accounts']:
  659.                 if str(i['accountType']) == "SPREADBET":
  660.                     balance = i['balance']['balance']
  661.                     deposit = i['balance']['deposit']
  662.  
  663.             percent_used = percentage(deposit, balance)
  664.  
  665.             print("-----------------DEBUG-----------------")
  666.             print("#################DEBUG#################")
  667.             print(
  668.                 "!!DEBUG!!...Percent of account used ..." +
  669.                 str(percent_used))
  670.             print("-----------------DEBUG-----------------")
  671.             print("#################DEBUG#################")
  672.  
  673.             if float(percent_used) > 70:
  674.                 print("!!DEBUG!!...Don't trade, Too much margin used up already")
  675.                 time.sleep(60)
  676.                 continue
  677.             else:
  678.                 print("!!DEBUG!!...OK to trade, Account balance OK!!")
  679.  
  680.             tradeable_epic_ids = find_good_epics()
  681.             shuffle(tradeable_epic_ids)
  682.  
  683.         except Exception as e:
  684.             print(e)
  685.             print("!!DEBUG!!...No Suitable Epics...Yet!!, Try again!!")
  686.             continue
  687.  
  688.         for epic_id in tradeable_epic_ids:
  689.  
  690.             base_url = REAL_OR_NO_REAL + "/prices/" + epic_id + "/MINUTE_15/16"
  691.             # Price resolution (MINUTE, MINUTE_2, MINUTE_3, MINUTE_5,
  692.             # MINUTE_10, MINUTE_15, MINUTE_30, HOUR, HOUR_2, HOUR_3,
  693.             # HOUR_4, DAY, WEEK, MONTH)
  694.             auth_r = requests.get(base_url, headers=authenticated_headers)
  695.             d = json.loads(auth_r.text)
  696.  
  697.             # print("-----------------DEBUG-----------------")
  698.             # print("#################DEBUG#################")
  699.             # print(auth_r.status_code)
  700.             # print(auth_r.reason)
  701.             # print(auth_r.text)
  702.             # print("-----------------DEBUG-----------------")
  703.             # print("#################DEBUG#################")
  704.  
  705.             high_prices = []
  706.             low_prices = []
  707.             mid_prices = []
  708.             close_prices = []
  709.             ATR = calculate_stop_loss(d)
  710.  
  711.             remaining_allowance = d['allowance']['remainingAllowance']
  712.             reset_time = humanize_time(int(d['allowance']['allowanceExpiry']))
  713.             print("-----------------DEBUG-----------------")
  714.             print("#################DEBUG#################")
  715.             print("Remaining API Calls left: " + str(remaining_allowance))
  716.             print("Time to API Key reset: " + str(reset_time))
  717.             print("-----------------DEBUG-----------------")
  718.             print("#################DEBUG#################")
  719.  
  720.             for i in d['prices']:
  721.  
  722.                 if i['highPrice']['bid'] is not None:
  723.                     highPrice = i['highPrice']['bid']
  724.                     high_prices.append(highPrice)
  725.                 ########################################
  726.                 if i['lowPrice']['bid'] is not None:
  727.                     lowPrice = i['lowPrice']['bid']
  728.                     low_prices.append(lowPrice)
  729.                 ########################################
  730.                 if i['closePrice']['bid'] is not None:
  731.                     closePrice = i['lowPrice']['bid']
  732.                     close_prices.append(closePrice)
  733.                 ########################################
  734.                 mid_prices.append(float(midpoint(highPrice, lowPrice)))
  735.  
  736.             close_prices = numpy.asarray(close_prices)
  737.             low_prices = numpy.asarray(low_prices)
  738.             high_prices = numpy.asarray(high_prices)
  739.             mid_prices = numpy.asarray(mid_prices)
  740.  
  741.             xi = numpy.arange(0, len(low_prices))
  742.  
  743.             # close_prices_slope, close_prices_intercept, close_prices_r_value, close_prices_p_value, close_prices_std_err = stats.linregress(
  744.             # xi, close_prices)
  745.             # low_prices_slope, low_prices_intercept, low_prices_r_value, low_prices_p_value, low_prices_std_err = stats.linregress(
  746.             # xi, low_prices)
  747.             # high_prices_slope, high_prices_intercept, high_prices_r_value, high_prices_p_value, high_prices_std_err = stats.linregress(
  748.             # xi, high_prices)
  749.             # mid_prices_slope, mid_prices_intercept, mid_prices_r_value, mid_prices_p_value, mid_prices_std_err = stats.linregress(
  750.             # xi, mid_prices)
  751.  
  752.             close_prices_slope, close_prices_intercept, close_prices_lo_slope, close_prices_hi_slope = stats.theilslopes(
  753.                 close_prices, xi)
  754.             low_prices_slope, low_prices_intercept, low_prices_lo_slope, low_prices_hi_slope = stats.theilslopes(
  755.                 low_prices, xi)
  756.             high_prices_slope, high_prices_intercept, high_prices_lo_slope, high_prices_hi_slope = stats.theilslopes(
  757.                 high_prices, xi)
  758.             mid_prices_slope, mid_prices_intercept, mid_prices_lo_slope, mid_prices_hi_slope = stats.theilslopes(
  759.                 mid_prices, xi)
  760.  
  761.             # print ("#####################################################")
  762.             # print ("#####################################################")
  763.             # print ("#####################################################")
  764.  
  765.             # print ("Please uncomment this to enable graphs for debugging")
  766.  
  767.             # print ("#####################################################")
  768.             # print ("#####################################################")
  769.             # print ("#####################################################")
  770.  
  771.             # close_prices_line = close_prices_slope * xi + close_prices_intercept
  772.             # low_prices_line = low_prices_slope * xi + low_prices_intercept
  773.             # high_prices_line = high_prices_slope * xi + high_prices_intercept
  774.             # mid_prices_line = mid_prices_slope * xi + mid_prices_intercept
  775.  
  776.             # plt.plot(
  777.             # xi,
  778.             # low_prices_line,
  779.             # xi,
  780.             # high_prices_line,
  781.             # xi,
  782.             # close_prices,
  783.             # 'g--',
  784.             # xi,
  785.             # mid_prices_line)
  786.             # plt.fill_between(
  787.             # xi,
  788.             # low_prices_line,
  789.             # high_prices_line,
  790.             # facecolor='green',
  791.             # alpha=0.5)
  792.             # plt.xlabel('X Axis')
  793.             # plt.ylabel('Y Axis')
  794.             # plt.show()
  795.             # plt.clf()
  796.  
  797.             # print ("#####################################################")
  798.             # print ("#####################################################")
  799.             # print ("#####################################################")
  800.  
  801.             # print ("Please uncomment this to enable graphs for debugging")
  802.  
  803.             # print ("#####################################################")
  804.             # print ("#####################################################")
  805.             # print ("#####################################################")
  806.  
  807.             base_url = REAL_OR_NO_REAL + '/markets/' + epic_id
  808.             auth_r = requests.get(
  809.                 base_url, headers=authenticated_headers)
  810.             d = json.loads(auth_r.text)
  811.  
  812.             # print("-----------------DEBUG-----------------")
  813.             # print("#################DEBUG#################")
  814.             # print(auth_r.status_code)
  815.             # print(auth_r.reason)
  816.             # print(auth_r.text)
  817.             # print("-----------------DEBUG-----------------")
  818.             # print("#################DEBUG#################")
  819.  
  820.             current_bid = d['snapshot']['bid']
  821.  
  822.             # 2 Standard Deviation
  823.             std_dev_BUY = float(mid_prices_intercept +
  824.                                 (numpy.std(mid_prices) * 2))
  825.             # 2 Standard Deviation
  826.             std_dev_SELL = float(mid_prices_intercept -
  827.                                  (numpy.std(mid_prices) * 2))
  828.  
  829.             if float(current_bid) > float(mid_prices_intercept) and float(
  830.                     current_bid) > float(std_dev_BUY):
  831.                 TRADE_DIRECTION = "BUY"
  832.                 pip_limit = int(abs(float(max(high_prices)) -
  833.                                     float(current_bid)) / SL_MULTIPLIER)
  834.                 print("-----------------DEBUG-----------------")
  835.                 print("#################DEBUG#################")
  836.                 print("!!DEBUG!!...BUY!!")
  837.                 print(str(epic_id))
  838.                 print(
  839.                     "!!DEBUG!!...Take Profit@...." +
  840.                     str(pip_limit) +
  841.                     " pips")
  842.                 print("-----------------DEBUG-----------------")
  843.                 print("#################DEBUG#################")
  844.                 ce_stop = Chandelier_Exit_formula(
  845.                     TRADE_DIRECTION, ATR, min(low_prices))
  846.                 tmp_stop = int(abs(float(current_bid) - (ce_stop)))
  847.             elif float(current_bid) < float(mid_prices_intercept) and float(current_bid) < float(std_dev_SELL):
  848.                 TRADE_DIRECTION = "SELL"
  849.                 pip_limit = int(abs(float(min(low_prices)) -
  850.                                     float(current_bid)) / SL_MULTIPLIER)
  851.                 print("-----------------DEBUG-----------------")
  852.                 print("#################DEBUG#################")
  853.                 print("!!DEBUG!!...SELL!!")
  854.                 print(str(epic_id))
  855.                 print(
  856.                     "!!DEBUG!!...Take Profit@...." +
  857.                     str(pip_limit) +
  858.                     " pips")
  859.                 print("-----------------DEBUG-----------------")
  860.                 print("#################DEBUG#################")
  861.                 ce_stop = Chandelier_Exit_formula(
  862.                     TRADE_DIRECTION, ATR, max(high_prices))
  863.                 tmp_stop = int(abs(float(current_bid) - (ce_stop)))
  864.  
  865.             else:
  866.                 pip_limit = 9999999
  867.                 tmp_stop = "999999"
  868.                 TRADE_DIRECTION = "NONE"
  869.                 print("!!DEBUG!!...Within trading range...Leave!!")
  870.  
  871.             if int(pip_limit) <= 1:
  872.                 print("!!DEBUG!!...No Trade!!, Pip Limit Under 1")
  873.                 TRADE_DIRECTION = "NONE"
  874.  
  875.             stopDistance_value = str(tmp_stop)
  876.  
  877.             if int(stopDistance_value) <= LOW_SL_WATERMARK or int(
  878.                     stopDistance_value) >= HIGH_SL_WATERMARK:
  879.                 TRADE_DIRECTION = "NONE"
  880.  
  881.             try:
  882.                 are_we_going_to_trade(epic_id, TRADE_DIRECTION, pip_limit)
  883.             except Exception as e:
  884.                 print(e)
  885.                 print("Something fucked up!!, Try again!!")
  886.                 continue
Advertisement
Add Comment
Please, Sign In to add comment