Thursday, June 4, 2020

iqoption robot code sample 1 sma5 trade

โคด ตั้วอย่าง
https://colab.research.google.com/drive/1DXkTXZ-eiQ1Jio_tzyuTsHjdy0R5IQLT#scrollTo=2yu0huE3czMh&line=216&uniqifier=1


import os
from iqoptionapi.stable_api import IQ_Option
import logging
import time
import secrets
from datetime import datetime as dt
import numpy as np
import matplotlib.pyplot as plt
# from mpl_finance import candlestick_ohlc
import pandas as pd
import matplotlib.dates as mpl_dates
import talib

import plotly.graph_objs as go
from plotly.offline import plot

from pyti.smoothed_moving_average import smoothed_moving_average as sma
from pyti.exponential_moving_average import exponential_moving_average as ema
global short_time
global b
global result
global x
short_time=0
cnt=0
result=0
x=0
# logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(message)s')
print("login...")
I_want_money=IQ_Option("xxxx@hotmail.com","12345678aabbccddeeff")
check, reason=I_want_money.connect()#connect to iqoption
print(check)#, reason)
#I_want_money.connect()#connect to iqoption
print(I_want_money.reset_practice_balance())
#goal="USDCHF-OTC"
class TradingModel:
  def __init__(selfsymbol,size,maxdict,Money,x,expirations_mode):
    self.symbol = symbol[x]
    self.size = size
    self.maxdict = maxdict
    self.Money=Money
    self.expirations_mode= expirations_mode
    self.df = self.getData()

  # Returns true if stream1 crossed under stream2 in most recent candle, stream2 can be integer/float or data arra



  def getData(self):

        # print("start stream...")
    I_want_money.start_candles_stream(self.symbol,self.size,self.maxdict)
        #DO something
    # print("Please wait now collecting candlestick data...",self.symbol)

    candles=I_want_money.get_realtime_candles(self.symbol,self.size)
    inputs = {
                        'time': np.array([]).astype(int),
                        'open': np.array([]).astype(float),
                        'high': np.array([]).astype(float),
                        'low': np.array([]).astype(float),
                        'close': np.array([]).astype(float),
                        'volume': np.array([]).astype(float)
                }
    for timestamp in candles:
        #    ((datetime.utcfromtimestamp(int(data_ohlc['from'])).strftime('%Y-%m-%d %H:%M:%S'))
                # inputs["time"]=np.append(inputs["time"],candles[((datetime.utcfromtimestamp(int(candles['from'])).strftime('%Y-%m-%d %H:%M:%S'))] )
        inputs["time"]=np.append(inputs["time"],candles[timestamp]['from'] )
        inputs["open"]=np.append(inputs["open"],candles[timestamp]["open"] )
        inputs["high"]=np.append(inputs["high"],candles[timestamp]["max"] )
        inputs["low"]=np.append(inputs["low"],candles[timestamp]["min"] )
        inputs["close"]=np.append(inputs["close"],candles[timestamp]["close"] )
        inputs["volume"]=np.append(inputs["volume"],candles[timestamp]["volume"] )
    df = pd.DataFrame(inputs)#,columns=['time', 'open', 'high', 'low', 'close', 'volume'])#,index=0, parse_dates=True)

    df=df.sort_index()
  
    df['H-L'] = df['high'] - df['low']
    df['O-C'] = df['open']-df['close'
    df['SMA5'] = df['close'].shift(1).rolling(window = 5).mean()
    df['newATR'] = talib.ATR(df['high'], df['low'], df['close'], timeperiod=14)

    # os.system('cls')  # on windows
    # print(df.loc[35:])
    return df

  def strategy(self):

    df = self.df


    print(df['high'].iloc[self.maxdict-3],round(df['SMA5'].iloc[self.maxdict-3],6),df['low'].iloc[self.maxdict-3])
    print(df['high'].iloc[self.maxdict-3]-round(df['SMA5'].iloc[self.maxdict-3],6),df['low'].iloc[self.maxdict-3]-round(df['SMA5'].iloc[self.maxdict-3],6)," atr ",df['newATR'].max())
    print("high to SMA5\t",round(df['high'].iloc[self.maxdict-3]-df['SMA5'].iloc[self.maxdict-3]-(1.1*df['newATR'].max()),6))
    print("SMA5 to low \t",round(df['SMA5'].iloc[self.maxdict-3]-df['low'].iloc[self.maxdict-3]-(1.1*df['newATR'].max()),6))
    distantce_high_to_sma=round(df['high'].iloc[self.maxdict-3]-df['SMA5'].iloc[self.maxdict-3]-(1.1*df['newATR'].max()),6)
    distantce_sma_to_low=round(df['SMA5'].iloc[self.maxdict-3]-df['low'].iloc[self.maxdict-3]-(1.1*df['newATR'].max()),6)
    sma_in_candle=df['high'].iloc[self.maxdict-3] > df['SMA5'].iloc[self.maxdict-3] > df['low'].iloc[self.maxdict-3]
    bearish_candle=df['O-C'].iloc[self.maxdict-2]>0  and distantce_sma_to_low>0
    bullish_candle=df['O-C'].iloc[self.maxdict-2]<0 and distantce_high_to_sma>0
    lower_wick_bull=(df['open']-df['low']).iloc[self.maxdict-3]
    upper_wick_bull=(df['high']-df['close']).iloc[self.maxdict-3]
    lower_wick_bear=(df['close']-df['low']).iloc[self.maxdict-3]
    upper_wick_bear=(df['high']-df['open']).iloc[self.maxdict-3]
    print(lower_wick_bull,upper_wick_bull)
    print(lower_wick_bear,upper_wick_bear)
    

    for i in range(1len(df['close'])):
      if distantce_high_to_sma>df['newATR'].max():
        print("candle far above SMA5",distantce_high_to_sma)
        self.sell()
        break

      if distantce_sma_to_low>df['newATR'].max():
        print("candle far below SMA5",distantce_sma_to_low)
        self.buy()
        break


  

  def buy(self):
    Money=self.Money
    ACTIVES=self.symbol
    ACTION="call"#or "put"


    check,id=I_want_money.buy(Money,ACTIVES,ACTION,self.expirations_mode)

    if check:
       print(ACTIVES," !buy!",self.Money)
    else:
       print(ACTIVES," buy fail")
       pass#time.sleep(5)

    result=(I_want_money.check_win_v3(id))
    print(result)
##    return result



  def sell(self):
    Money=self.Money
    ACTIVES=self.symbol
    ACTION="put"#or "put"


    check,id=I_want_money.buy(Money,ACTIVES,ACTION,self.expirations_mode)

    if check:
       print(ACTIVES," !sell!",self.Money)
    else:
       print(ACTIVES," sell fail")
       pass#time.sleep(5)

    result=(I_want_money.check_win_v3(id))
    print(result)
##    return result

  # def unloadcandle(self):
  #   print("stop candle")
  #   I_want_money.stop_candles_stream(self.symbol,self.size)


def Main():

    b=0
    s=0
    martinggale=1
    balance=I_want_money.get_balance()
    print("balance = ",balance)



##    symbol = ["AUDJPY","EURUSD","EURJPY","GBPUSD","AUDUSD","USDJPY"]
    symbol = ["EURUSD","NZDUSD","AUDCAD","EURNZD","AUDJPY","GBPAUD","GBPCAD"]
    cnt=len(symbol)
    # print(cnt," SYMBOL IN LIST")

    size=30#"all"#size=[1,5,10,15,30,60,120,300,600,900,1800,3600,7200,14400,28800,43200,86400,604800,2592000,"all"]

    maxdict=40
    trigger_level=0
    Money=1000
    randoms=[1,2.5,3]
    martinggale=secrets.choice(randoms)
    Money=Money*martinggale
    print("Invest money = ",Money)


    expirations_mode=2



    remaning_time=I_want_money.get_remaning(expirations_mode)

    model = TradingModel(symbol,
                         size,
                         maxdict,
                         Money,
                         x,
                         expirations_mode)

    model.strategy()




if __name__ == '__main__':
  while check:
    x=x
    Main()
    


No comments:

Post a Comment