Esempio n. 1
0
cJSON *LP_assethbla(char *assetid)
{
    char url[1024],*retstr; int32_t n; cJSON *array,*bid=0,*ask=0,*retjson;
    sprintf(url,"http://%s:7876/nxt?requestType=getBidOrders&asset=%s&firstIndex=0&lastIndex=0",NXTnodes[LP_rand() % (sizeof(NXTnodes)/sizeof(*NXTnodes))],assetid);
    if ( (retstr= issue_curlt(url,LP_HTTP_TIMEOUT)) != 0 )
    {
        bid = cJSON_Parse(retstr);
        free(retstr);
    }
    sprintf(url,"http://%s:7876/nxt?requestType=getAskOrders&asset=%s&firstIndex=0&lastIndex=0",NXTnodes[LP_rand() % (sizeof(NXTnodes)/sizeof(*NXTnodes))],assetid);
    if ( (retstr= issue_curlt(url,LP_HTTP_TIMEOUT)) != 0 )
    {
        ask = cJSON_Parse(retstr);
        free(retstr);
    }
    retjson = cJSON_CreateObject();
    if ( bid != 0 && ask != 0 )
    {
        if ( (array= jarray(&n,bid,"bidOrders")) != 0 )
            jadd(retjson,"bid",jduplicate(jitem(array,0)));
        if ( (array= jarray(&n,ask,"askOrders")) != 0 )
            jadd(retjson,"ask",jduplicate(jitem(array,0)));
    }
    if ( bid != 0 )
        free_json(bid);
    if ( ask != 0 )
        free_json(ask);
    return(retjson);
}
Esempio n. 2
0
void marketmaker_pendingupdate(char *exchange,char *base,char *rel)
{
    char *retstr; cJSON *retjson,*obj; int32_t i; struct mmpending_order *ptr;
    for (i=0; i<Num_Pending; i++)
    {
        ptr = &Pending_orders[i];
        if ( strcmp(exchange,ptr->exchange) != 0 || strcmp(base,ptr->base) != 0 || strcmp(rel,ptr->rel) != 0 )
            continue;
        if ( ptr->completed == 0 && (retstr= DEX_orderstatus(exchange,ptr->orderid)) != 0 )
        {
            //printf("%s status.(%s)\n",ptr->orderid,retstr);
            if ( (retjson= cJSON_Parse(retstr)) != 0 )
            {
                obj = jobj(retjson,"result");
                if ( is_cJSON_Array(obj) != 0 )
                    obj = jitem(retjson,0);
                if ( jdouble(obj,"QuantityRemaining") == 0. || is_cJSON_True(jobj(obj,"IsOpen")) == 0 )
                {
//{"Uuid":null,"OrderUuid":"e7b0789c-0c4e-413b-a768-3d5734d9cbe5","Exchange":"BTC-KMD","OrderType":"LIMIT_SELL","Quantity":877.77700000,"QuantityRemaining":462.50512234,"Limit":0.00011770,"CommissionPaid":0.00012219,"Price":0.04887750,"PricePerUnit":0.00011769,"Opened":"2017-02-20T13:16:22.29","Closed":null,"CancelInitiated":false,"ImmediateOrCancel":false,"IsConditional":false,"Condition":"NONE","ConditionTarget":null}                    printf("uuid.(%s) finished.(%s)\n",ptr->orderid,jprint(retjson,0));
                    ptr->completed = (uint32_t)time(NULL);
                    ptr->pending = 0;
                }
                free_json(retjson);
            }
            free(retstr);
        }
    }
}
Esempio n. 3
0
double basilisk_process_results(struct supernet_info *myinfo,struct basilisk_request *issueR,cJSON *retjson,double hwm)
{
    cJSON *array,*item; int32_t i,n,m; struct basilisk_request tmpR,R,refR,list[BASILISK_MAXRELAYS]; double metric=0.;
    //printf("process_results.(%s)\n",jprint(retjson,0));
    if ( (array= jarray(&n,retjson,"result")) != 0 )
    {
        for (i=m=0; i<n; i++)
        {
            item = jitem(array,i);
            if ( i != 0 )
            {
                basilisk_parsejson(&R,item);
                if ( refR.requestid == R.requestid )
                    list[m++] = R;
                else
                {
                    if ( (metric= basilisk_request_listprocess(myinfo,&tmpR,list,m)) > hwm )
                        *issueR = tmpR, hwm = metric;
                    m = 0;
                }
            }
            if ( m < sizeof(list)/sizeof(*list) )
                basilisk_parsejson(&list[m++],item);
        }
        if ( m > 0 && m < sizeof(list)/sizeof(*list) )
            if ( (metric= basilisk_request_listprocess(myinfo,&tmpR,list,m)) > hwm )
                *issueR = tmpR, hwm = metric;
    }
    return(hwm);
}
Esempio n. 4
0
cJSON *gecko_paymentsobj(struct supernet_info *myinfo,cJSON *txjson,cJSON *valsobj,int32_t reusedaddrs)
{
    cJSON *item,*array; char *coinaddr; uint64_t satoshis; uint8_t addrtype,pubkey33[33],rmd160[20],outputscript[512]; int32_t i,n,scriptlen; uint32_t locktime,txversion; struct iguana_waddress *waddr; struct iguana_waccount *wacct;
    locktime = jint(valsobj,"locktime");
    if ( (txversion= juint(valsobj,"txversion")) == 0 )
        txversion = (locktime == 0) ? IGUANA_NORMAL_TXVERSION : IGUANA_LOCKTIME_TXVERSION;
    if ( txjson == 0 )
        txjson = bitcoin_txcreate(1,locktime,txversion);
    if ( (array= jarray(&n,valsobj,"payments")) != 0 && n > 0 )
    {
        for (i=0; i<n; i++)
        {
            item = jitem(array,i);
            if ( (coinaddr= jfieldname(item)) != 0 && (satoshis= j64bits(item,coinaddr)) > 0 )
            {
                printf("payment.%s <- %.8f\n",coinaddr,dstr(satoshis));
                bitcoin_addr2rmd160(&addrtype,rmd160,coinaddr);
                scriptlen = 0;
                if ( reusedaddrs == 0 )
                {
                    if ( (waddr= iguana_waddresssearch(myinfo,&wacct,coinaddr)) != 0 )
                    {
                        if ( bitcoin_pubkeylen(waddr->pubkey) > 0 )
                            scriptlen = bitcoin_pubkeyspend(outputscript,0,pubkey33);
                    }
                }
                if ( scriptlen == 0 )
                    scriptlen = bitcoin_standardspend(outputscript,0,rmd160);
                bitcoin_txoutput(txjson,outputscript,scriptlen,satoshis);
            }
        }
    }
    return(txjson);
}
Esempio n. 5
0
char *PARSEBALANCE(struct exchange_info *exchange,double *balancep,char *coinstr)
{
    //[[{"type":"deposit","currency":"btc","amount":"0.0","available":"0.0"},{"type":"deposit","currency":"usd","amount":"0.0","available":"0.0"},{"type":"exchange","currency":"btc","amount":"0.01065851","available":"0.01065851"},{"type":"exchange","currency":"usd","amount":"23386.37278962","available":"0.00378962"},{"type":"trading","currency":"btc","amount":"0.0","available":"0.0"},{"type":"trading","currency":"usd","amount":"0.0","available":"0.0"}]]
    int32_t i,n,ind; char field[64],*str,*typestr,*itemstr = 0; cJSON *item,*obj,*array; double amounts[3],avail[3],val0,val1;
    *balancep = 0.;
    strcpy(field,coinstr), tolowercase(field);
    memset(amounts,0,sizeof(amounts));
    memset(avail,0,sizeof(avail));
    if ( exchange->balancejson != 0 && is_cJSON_Array(exchange->balancejson) != 0 && (n= cJSON_GetArraySize(exchange->balancejson)) > 0 )
    {
        for (i=0; i<n; i++)
        {
            if ( (item= jitem(exchange->balancejson,i)) != 0 )
            {
                if ( (str= jstr(item,"currency")) != 0 && strcmp(field,str) == 0 )
                {
                    val0 = jdouble(item,"amount");
                    val1 = jdouble(item,"available");
                    if ( (typestr= jstr(item,"type")) != 0 )
                    {
                        if ( strcmp(typestr,"deposit") == 0 )
                            ind = 0;
                        else if ( strcmp(typestr,"exchange") == 0 )
                            ind = 1;
                        else if ( strcmp(typestr,"trading") == 0 )
                            ind = 2;
                        else ind = -1;
                        if ( ind >= 0 )
                        {
                            amounts[ind] = val0;
                            avail[ind] = val1;
                        }
                    }
                }
            }
        }
        if ( (obj= cJSON_CreateObject()) != 0 )
        {
            touppercase(field);
            *balancep = avail[0] + avail[1] + avail[2];
            jaddstr(obj,"base",field);
            jaddnum(obj,"balance",*balancep);
            jaddnum(obj,"total",amounts[0]+amounts[1]+amounts[2]);
            array = cJSON_CreateArray(), jaddinum(array,avail[0]), jaddinum(array,amounts[0]), jadd(obj,"deposit",array);
            array = cJSON_CreateArray(), jaddinum(array,avail[1]), jaddinum(array,amounts[1]), jadd(obj,"exchange",array);
            array = cJSON_CreateArray(), jaddinum(array,avail[2]), jaddinum(array,amounts[2]), jadd(obj,"trading",array);
            itemstr = jprint(obj,1);
        }
    }
    if ( itemstr == 0 )
        return(clonestr("{\"error\":\"cant find coin balance\"}"));
    return(itemstr);
}
Esempio n. 6
0
void marketmaker_pendinginit(char *exchange,char *base,char *rel)
{
    char *retstr,*orderid; cJSON *retjson,*array,*item; int32_t i,j,n,dir; struct mmpending_order *ptr;
    if ( (retstr= DEX_openorders(exchange)) != 0 )
    {
        if ( (retjson= cJSON_Parse(retstr)) != 0 )
        {
            //printf("%s\n",jprint(retjson,0));
            if ( is_cJSON_True(jobj(retjson,"success")) != 0 && (array= jarray(&n,retjson,"result")) != 0 )
            {
                for (i=0; i<n; i++)
                {
                    item = jitem(array,i);
                    //printf("(%s)\n",jprint(item,0));
                    //{"success":true,"message":"","result":[{"Uuid":null,"OrderUuid":"81ad3e37-65d4-4fee-9c29-03b050f5192b","Exchange":"BTC-KMD","OrderType":"LIMIT_BUY","Quantity":885.19934578,"QuantityRemaining":885.19934578,"Limit":0.00011184,"CommissionPaid":0,"Price":0,"PricePerUnit":null,"Opened":"2017-02-19T19:14:02.94","Closed":null,"CancelInitiated":false,"ImmediateOrCancel":false,"IsConditional":false,"Condition":"NONE","ConditionTarget":null}],"tag":"10056789044100011414"}
                    if ( (orderid= jstr(item,"OrderUuid")) != 0 && is_cJSON_Null(jobj(item,"Closed")) != 0 && is_cJSON_False(jobj(item,"CancelInitiated")) != 0 )
                    {
                        for (j=0; j<Num_Pending; j++)
                        {
                            ptr = &Pending_orders[j];
                            if ( strcmp(exchange,ptr->exchange) != 0 || strcmp(base,ptr->base) != 0 || strcmp(rel,ptr->rel) != 0 )
                                continue;
                            if ( strcmp(ptr->orderid,orderid) == 0 )
                            {
                                ptr->pending = (uint32_t)time(NULL);
                                ptr->completed = 0;
                                printf("%s pending\n",orderid);
                                break;
                            }
                        }
                        if ( j == Num_Pending )
                        {
                            if ( jstr(item,"OrderType") != 0 )
                            {
                                if ( strcmp(jstr(item,"OrderType"),"LIMIT_BUY") == 0 )
                                    dir = 1;
                                else if ( strcmp(jstr(item,"OrderType"),"LIMIT_SELL") == 0 )
                                    dir = -1;
                                else dir = 0;
                                if ( dir != 0 )
                                    marketmaker_queue(exchange,base,rel,dir,jdouble(item,"Limit"),jdouble(item,"QuantityRemaining"),item);
                                else printf("no dir (%s) (%s)\n",jprint(item,0),jstr(item,"OrderType"));
                            }
                        }
                    }
                }
            }
            free_json(retjson);
        }
        free(retstr);
    }
}
Esempio n. 7
0
uint16_t SuperNET_API2num(char *agent,char *method)
{
    int32_t i,n = 0; cJSON *item;
    if ( agent != 0 && method != 0 && API_json != 0 && (n= cJSON_GetArraySize(API_json)) > 0 )
    {
        for (i=0; i<n; i++)
        {
            item = jitem(API_json,i);
            if ( strcmp(agent,jstr(item,"agent")) == 0 && strcmp(method,jstr(item,"method")) == 0 )
                return((i << 5) | (SUPERNET_APIVERSION & 0x1f));
        }
    }
    return(-1);
}
Esempio n. 8
0
uint32_t marketmaker_fiatupdate(cJSON *fiatjson)
{
    int32_t i,n,baseid; cJSON *item,*array; double price; char *name; uint64_t mask = 0;
    fiatjson = jobj(fiatjson,"list");
    if ( fiatjson != 0 && (array= jarray(&n,fiatjson,"resources")) > 0 )
    {
        for (i=0; i<n; i++)
        {
            /*
            "resource" : {
                "classname" : "Quote",
                "fields" : {
                    "name" : "USD/BRX",
                    "price" : "3.063200",
                    "symbol" : "BRX=X",
                    "ts" : "1487866204",
                    "type" : "currency",
                    "utctime" : "2017-02-23T16:10:04+0000",
                    "volume" : "0"
                }
           */
            item = jitem(array,i);
            if ( (item= jobj(item,"resource")) != 0 )
                item = jobj(item,"fields");
            if ( item != 0 )
            {
                price = jdouble(item,"price");
                if ( price > SMALLVAL && (name= jstr(item,"name")) != 0 && strncmp(name,"USD/",4) == 0 )
                {
                    if ( (baseid= komodo_baseid(name+4)) >= 0 && baseid < 32 )
                    {
                        if ( ((1LL << baseid) & mask) == 0 )
                        {
                            _marketmaker_fiatupdate(baseid,price);
                            mask |= (1LL << baseid);
                        } else if ( fabs(price*PAXPRICES[0] - PAXPRICES[baseid]) > SMALLVAL )
                            printf("DUPLICATE PRICE? %s %.8f vs %.8f\n",name+4,price*PAXPRICES[0],PAXPRICES[baseid]);
                    }
                }
            }
        }
    }
    printf("pax mask.%x\n",(uint32_t)mask);
    return((uint32_t)mask);
}
Esempio n. 9
0
int32_t SuperNET_num2API(char *agent,char *method,uint16_t num)
{
    int32_t n,apiversion; cJSON *item;
    if ( (apiversion= (num & 0x1f)) != SUPERNET_APIVERSION )
    {
        printf("need to make sure all released api help returns are indexed here!\n");
        return(-1);
    }
    num >>= 5;
    if ( API_json != 0 && (n= cJSON_GetArraySize(API_json)) > 0 && num < n )
    {
        item = jitem(API_json,num);
        strcpy(agent,jstr(item,"agent"));
        strcpy(method,jstr(item,"method"));
        return(num);
    }
    return(-1);
}
Esempio n. 10
0
int32_t main(int32_t argc,char **argv)
{
    cJSON *argjson,*array,*filejson,*obj,*fobj; char *fname,*filestr,*fstr,*str,*field; int32_t i,n; long filesize;
    printf("argv[2]: %s\n",argv[2]);
    if ( argc > 2 && (argjson= cJSON_Parse(argv[2])) != 0 )
    {
        fname = argv[1];
        printf("got file: %s\n",fname);
        if ( (filestr= OS_filestr(&filesize,fname)) != 0 )
        {
            if ( (filejson= cJSON_Parse(filestr)) != 0 )
            {
                if ( (array= jarray(&n,argjson,"fields")) != 0 )
                {
                    for (i=0; i<n; i++)
                    {
                        obj = jitem(array,i);
                        if ( (field= jfieldname(obj)) != 0 && (obj= obj->child) != 0 )
                        {
                            if ( (fobj= jobj(filejson,field)) != 0 )
                            {
                                fstr = jprint(fobj,0);
                                str = jprint(obj,0);
                                if ( strcmp(fstr,str) != 0 )
                                {
                                    printf("{\"error\":\"field.(%s) in (%s) i.%d of n.%d mismatch (%s) != (%s)\"}\n",field,fname,i,n,fstr,str);
                                    fprintf(stderr,"{\"error\":\"field.(%s) in (%s) i.%d of n.%d mismatch (%s) != (%s)\"}\n",field,fname,i,n,fstr,str);
                                }
                                else printf("{\"result\":\"MATCHED.[%s] (%s).(%s)\"}\n",fname,field,fstr);
                                free(str);
                                free(fstr);
                            } else fprintf(stderr,"cant find field.(%s) in (%s)\n",field,fname);
                        } else fprintf(stderr,"no fieldname array[%d]\n",i);
                    }
                } else fprintf(stderr,"no fields array\n");
                free_json(filejson);
            } else fprintf(stderr,"cant parse.(%s)\n",filestr);
            free(filestr);
        } else fprintf(stderr,"cant load (%s)\n",fname);
    } else fprintf(stderr,"argc.%d fname.(%s) error\n",argc,argv[1]);
}
void init_exchanges(cJSON *json)
{
    cJSON *array; int32_t i,n;
    for (FIRST_EXTERNAL=0; FIRST_EXTERNAL<sizeof(Supported_exchanges)/sizeof(*Supported_exchanges); FIRST_EXTERNAL++)
    {
        find_exchange(0,Supported_exchanges[FIRST_EXTERNAL]);
        if ( strcmp(Supported_exchanges[FIRST_EXTERNAL],"peggy") == 0 )
        {
            FIRST_EXTERNAL++;
            break;
        }
    }
    for (i=FIRST_EXTERNAL; i<sizeof(Supported_exchanges)/sizeof(*Supported_exchanges); i++)
        find_exchange(0,Supported_exchanges[i]);
    prices777_initpair(-1,0,0,0,0,0.,0,0,0,0);
    if ( (array= jarray(&n,json,"baskets")) != 0 )
    {
        for (i=0; i<n; i++)
            prices777_makebasket(0,jitem(array,i),1,"basket",0,0);
    }
    void prices777_basketsloop(void *ptr);
    portable_thread_create((void *)prices777_basketsloop,0);
    //prices777_makebasket("{\"name\":\"NXT/BTC\",\"base\":\"NXT\",\"rel\":\"BTC\",\"basket\":[{\"exchange\":\"bittrex\"},{\"exchange\":\"poloniex\"},{\"exchange\":\"btc38\"}]}",0);
}
Esempio n. 12
0
void NXTventure_liquidation()
{
    /*{"quantityQNT":"607438148","unconfirmedQuantityQNT":"607438148","decimals":4,"name":"ARDR","asset":""},
     {"quantityQNT":"451991779","unconfirmedQuantityQNT":"451991779","decimals":4,"name":"SuperNET","asset":"12071612744977229797"},
     {"quantityQNT":"146960000","unconfirmedQuantityQNT":"146960000","decimals":4,"name":"Privatebet","asset":"17083334802666450484"},
     {"quantityQNT":"79500188","unconfirmedQuantityQNT":"79500188","decimals":3,"name":"crypto777","asset":"13476425053110940554"},
     {"quantityQNT":"1495473","unconfirmedQuantityQNT":"1495473","decimals":0,"name":"jl777hodl","asset":"6932037131189568014"},
     {"quantityQNT":"7250","unconfirmedQuantityQNT":"7250","decimals":0,"name":"InstantDEX","asset":"15344649963748848799"},*/
    char *assetids[][4] =
    {
        { "12422608354438203866", "607438148", "ARDR", "10000" },
        { "12071612744977229797", "451991779", "SuperNET", "10000" },
        { "17083334802666450484", "146960000", "Privatebet", "10000" },
        { "13476425053110940554", "79500188", "crypto777", "1000" },
        { "6932037131189568014", "1495473", "jl777hodl", "1" },
        { "15344649963748848799", "7250", "InstantDEX", "1" },
    };
    void *cHandle=0; char *retstr,*retstr2,url[1024],*account; uint64_t txid,qty,qtyA,assetid,sum; double ratio; cJSON *array,*retjson2,*item,*retjson; int32_t i,j,decimals,numassetids=(int32_t)(sizeof(assetids)/sizeof(*assetids)),n=0;
    char *passphrase = "";
    sprintf(url,"http://127.0.0.1:7876/nxt?requestType=getAssetAccounts&asset=16212446818542881180");
    if ( (retstr= issue_curlt(url,LP_HTTP_TIMEOUT)) != 0 )
    {
        if ( (retjson= cJSON_Parse(retstr)) != 0 )
        {
            if ( (array= jarray(&n,retjson,"accountAssets")) != 0 )
            {
                for (j=0; j<numassetids; j++)
                {
                    assetid = calc_nxt64bits(assetids[j][0]);
                    qtyA = calc_nxt64bits(assetids[j][1]);
                    decimals = (int32_t)calc_nxt64bits(assetids[j][3]);
                    printf("distribute %llu QNT of %s assetid %llu %.8f\n",(long long)qtyA,assetids[j][2],(long long)assetid,(double)qtyA / decimals);
                    sum = 0;
                    for (i=0; i<n; i++)
                    {
                        item = jitem(array,i);
                        qty = j64bits(item,"quantityQNT");
                        ratio = (double)qty / (1000000. - 13000.);
                        if ( (account= jstr(item,"accountRS")) != 0 && qtyA*ratio >= 1 )
                        {
                            if ( strcmp(account,"NXT-XRK4-5HYK-5965-9FH4Z") != 0 )
                            {
                                sum += (long long)(qtyA * ratio);
                                sprintf(url,"requestType=transferAsset&secretPhrase=%s&recipient=%s&asset=%llu&quantityQNT=%llu&feeNQT=100000000&deadline=60",passphrase,account,(long long)assetid,(long long)(qtyA * ratio));
                                if ( (retstr2= curl_post(&cHandle,"http://127.0.0.1:7876/nxt","",url,"","","","")) != 0 )
                                {
                                    if ( (retjson2= cJSON_Parse(retstr2)) != 0 )
                                    {
                                        txid = j64bits(retjson2,"transaction");
                                        printf("%s %.6f %8llu QNT %s -> %llu %.8f txid %llu\n",account,ratio,(long long)qtyA,assetids[j][2],(long long)(qtyA * ratio),((double)(long long)(qtyA * ratio))/decimals,(long long)txid);
                                        free_json(retjson2);
                                    }
                                    free(retstr2);
                                }
                                usleep(250000);
                            }
                        }
                    }
                    printf("%s distribution total %llu QNT %.8f\n",assetids[j][2],(long long)sum,(double)sum/decimals);
                }
            }
            free_json(retjson);
        }
        printf("NXTventure assethodlers.%d\n",n);
        free(retstr);
    }
}
Esempio n. 13
0
void dpow_statemachinestart(void *ptr)
{
    void **ptrs = ptr;
    struct supernet_info *myinfo; struct dpow_info *dp; struct dpow_checkpoint checkpoint;
    int32_t i,j,ht,extralen,destprevvout0,srcprevvout0,numratified=0,kmdheight,myind = -1; uint8_t extras[10000],pubkeys[64][33]; cJSON *ratified=0,*item; struct iguana_info *src,*dest; char *jsonstr,*handle,*hexstr,str[65],str2[65],srcaddr[64],destaddr[64]; bits256 zero,srchash,destprevtxid0,srcprevtxid0; struct dpow_block *bp; struct dpow_entry *ep = 0; uint32_t duration,minsigs,starttime,srctime;
    memset(&zero,0,sizeof(zero));
    srcprevtxid0 = destprevtxid0 = zero;
    srcprevvout0 = destprevvout0 = -1;
    myinfo = ptrs[0];
    dp = ptrs[1];
    minsigs = (uint32_t)(long)ptrs[2];
    duration = (uint32_t)(long)ptrs[3];
    jsonstr = ptrs[4];
    kmdheight = -1;
    memcpy(&checkpoint,&ptrs[5],sizeof(checkpoint));
    src = iguana_coinfind(dp->symbol);
    dest = iguana_coinfind(dp->dest);
    dpow_getchaintip(myinfo,&srchash,&srctime,dp->srctx,&dp->numsrctx,src);
    dpow_getchaintip(myinfo,&srchash,&srctime,dp->desttx,&dp->numdesttx,dest);
    if ( src == 0 || dest == 0 )
    {
        printf("null coin ptr? (%s %p or %s %p)\n",dp->symbol,src,dp->dest,dest);
        return;
    }
    if ( strcmp(src->symbol,"KMD") == 0 )
        kmdheight = checkpoint.blockhash.height;
    else if ( strcmp(dest->symbol,"KMD") == 0 )
        kmdheight = dest->longestchain;
    if ( (bp= dp->blocks[checkpoint.blockhash.height]) == 0 )
    {
        bp = calloc(1,sizeof(*bp));
        bp->minsigs = minsigs;
        bp->duration = duration;
        bp->srccoin = src;
        bp->destcoin = dest;
        bp->myind = -1;
        bp->opret_symbol = dp->symbol;
        if ( jsonstr != 0 && (ratified= cJSON_Parse(jsonstr)) != 0 )
        {
            bp->isratify = 1;
            if ( (numratified= cJSON_GetArraySize(ratified)) > 0 )
            {
                if ( numratified > 64 )
                {
                    fprintf(stderr,"cant ratify more than 64 notaries ratified has %d\n",numratified);
                    return;
                }
                for (i=0; i<numratified; i++)
                {
                    item = jitem(ratified,i);
                    hexstr = handle = 0;
                    if ( (hexstr= jstr(item,"pubkey")) != 0 && is_hexstr(hexstr,0) == 66 )
                    {
                        decode_hex(bp->ratified_pubkeys[i],33,hexstr);
                        for (j=0; j<i; j++)
                            if ( memcmp(bp->ratified_pubkeys[j],bp->ratified_pubkeys[i],33) == 0 )
                            {
                                printf("ratification.%d is the same as %d, reject this donkey\n",j,i);
                                exit(-1);
                            }
                        if ( (handle= jstr(item,"handle")) != 0 )
                            safecopy(bp->handles[i],handle,sizeof(bp->handles[i]));
                        if ( i == 0 )
                        {
                            destprevtxid0 = jbits256(item,"destprevtxid0");
                            destprevvout0 = jint(item,"destprevvout0");
                            srcprevtxid0 = jbits256(item,"srcprevtxid0");
                            srcprevvout0 = jint(item,"srcprevvout0");
                            if ( bits256_nonz(destprevtxid0) != 0 && bits256_nonz(srcprevtxid0) != 0 )
                                bp->require0 = 1;
                        }
                    }
                    else
                    {
                        printf("break loop hexstr.%p handle.%p\n",hexstr,handle);
                        break;
                    }
                }
                if ( i == numratified )
                {
                    bp->numratified = numratified;
                    bp->ratified = ratified;
                    printf("numratified.%d %s\n",numratified,jprint(ratified,0));
                }
                else
                {
                    printf("i.%d numratified.%d\n",i,numratified);
                    free_json(ratified);
                }
            }
        }
        bp->bestk = -1;
        dp->blocks[checkpoint.blockhash.height] = bp;
        bp->beacon = rand256(0);
        vcalc_sha256(0,bp->commit.bytes,bp->beacon.bytes,sizeof(bp->beacon));
        /*if ( checkpoint.blockhash.height >= DPOW_FIRSTRATIFY && dp->blocks[checkpoint.blockhash.height - DPOW_FIRSTRATIFY] != 0 )
        {
            printf("purge %s.%d\n",dp->dest,checkpoint.blockhash.height - DPOW_FIRSTRATIFY);
            free(dp->blocks[checkpoint.blockhash.height - DPOW_FIRSTRATIFY]);
            dp->blocks[checkpoint.blockhash.height - DPOW_FIRSTRATIFY] = 0;
        }*/
    }
    if ( bp->isratify != 0 && dp->ratifying != 0 )
    {
        printf("new ratification starting dp->ratifying.%d\n",dp->ratifying);
        dp->ratifying++;
        while ( dp->ratifying > 1 )
            sleep(3);
        printf("other ratifications stopped\n");
    }
    if ( dp->ratifying != 0 && bp->isratify == 0 )
    {
        printf("skip notarization ht.%d when ratifying\n",bp->height);
        free(ptr);
        return;
    }
    dp->ratifying += bp->isratify;
    bitcoin_address(srcaddr,src->chain->pubtype,dp->minerkey33,33);
    bitcoin_address(destaddr,dest->chain->pubtype,dp->minerkey33,33);
    if ( kmdheight >= 0 )
    {
        ht = kmdheight;///strcmp("KMD",src->symbol) == 0 ? kmdheight : bp->height;
        if ( strcmp("KMD",dest->symbol) == 0 )
        {
            bp->numnotaries = komodo_notaries(dest->symbol,pubkeys,ht);
        }
        else
        {
            if ( ht == 0 )
                ht = strcmp("KMD",src->symbol) == 0 ? src->longestchain : dest->longestchain;
            bp->numnotaries = komodo_notaries(src->symbol,pubkeys,ht);
        }
        for (i=0; i<bp->numnotaries; i++)
        {
            //int32_t j; for (j=0; j<33; j++)
            //    printf("%02x",pubkeys[i][j]);
            //printf(" <= pubkey[%d]\n",i);
            memcpy(bp->notaries[i].pubkey,pubkeys[i],33);
            if ( strcmp("KMD",src->symbol) == 0 )
                memcpy(myinfo->notaries[i],pubkeys[i],33);
            if ( memcmp(bp->notaries[i].pubkey,dp->minerkey33,33) == 0 )
            {
                myind = i;
                ep = &bp->notaries[myind];
                for (j=0; j<33; j++)
                    printf("%02x",dp->minerkey33[j]);
                printf(" MYIND.%d <<<<<<<<<<<<<<<<<<<<<<\n",myind);
            }
        }
        if ( strcmp("KMD",src->symbol) == 0 )
            myinfo->numnotaries = bp->numnotaries;
        if ( myind < 0 || ep == 0 )
        {
            printf("minerkey33-> ");
            for (i=0; i<33; i++)
                printf("%02x",dp->minerkey33[i]);
            printf(" statemachinestart this node %s %s is not official notary numnotaries.%d kmdht.%d bpht.%d\n",srcaddr,destaddr,bp->numnotaries,kmdheight,bp->height);
            free(ptr);
            dp->ratifying -= bp->isratify;
            return;
        }
        printf("myind.%d\n",myind);
    }
    else
    {
        printf("statemachinestart no kmdheight.%d\n",kmdheight);
        free(ptr);
        dp->ratifying -= bp->isratify;
        return;
    }
    bp->myind = myind;
    printf("[%d] notarize %s->%s %s ht.%d minsigs.%d duration.%d start.%u\n",bp->myind,dp->symbol,dp->dest,bits256_str(str,checkpoint.blockhash.hash),checkpoint.blockhash.height,minsigs,duration,checkpoint.timestamp);
    if ( bp->isratify != 0 && memcmp(bp->notaries[0].pubkey,bp->ratified_pubkeys[0],33) != 0 )
    {
        for (i=0; i<33; i++)
            printf("%02x",bp->notaries[0].pubkey[i]);
        printf(" current vs ");
        for (i=0; i<33; i++)
            printf("%02x",bp->ratified_pubkeys[0][i]);
        printf(" new, cant change notary0\n");
        dp->ratifying -= bp->isratify;
        return;
    }
    //printf(" myind.%d myaddr.(%s %s)\n",myind,srcaddr,destaddr);
    if ( myind == 0 && bits256_nonz(destprevtxid0) != 0 && bits256_nonz(srcprevtxid0) != 0 && destprevvout0 >= 0 && srcprevvout0 >= 0 )
    {
        ep->dest.prev_hash = destprevtxid0;
        ep->dest.prev_vout = destprevvout0;
        ep->src.prev_hash = srcprevtxid0;
        ep->src.prev_vout = srcprevvout0;
        bp->notaries[myind].ratifysrcutxo = srcprevtxid0;
        bp->notaries[myind].ratifysrcvout = srcprevvout0;
        bp->notaries[myind].ratifydestutxo = destprevtxid0;
        bp->notaries[myind].ratifydestvout = destprevvout0;
        printf("Use override utxo %s/v%d %s/v%d\n",bits256_str(str,destprevtxid0),destprevvout0,bits256_str(str2,srcprevtxid0),srcprevvout0);
    }
    else
    {
        if ( dpow_checkutxo(myinfo,dp,bp,bp->destcoin,&ep->dest.prev_hash,&ep->dest.prev_vout,destaddr) < 0 )
        {
            printf("dont have %s %s utxo, please send funds\n",dp->dest,destaddr);
            free(ptr);
            dp->ratifying -= bp->isratify;
            return;
        }
        if ( dpow_checkutxo(myinfo,dp,bp,bp->srccoin,&ep->src.prev_hash,&ep->src.prev_vout,srcaddr) < 0 )
        {
            printf("dont have %s %s utxo, please send funds\n",dp->symbol,srcaddr);
            free(ptr);
            dp->ratifying -= bp->isratify;
            return;
        }
        if ( bp->isratify != 0 )
        {
            bp->notaries[myind].ratifysrcutxo = ep->src.prev_hash;
            bp->notaries[myind].ratifysrcvout = ep->src.prev_vout;
            bp->notaries[myind].ratifydestutxo = ep->dest.prev_hash;
            bp->notaries[myind].ratifydestvout = ep->dest.prev_vout;
        }
    }
    bp->recvmask |= (1LL << myind);
    bp->notaries[myind].othermask |= (1LL << myind);
    dp->checkpoint = checkpoint;
    bp->height = checkpoint.blockhash.height;
    bp->timestamp = checkpoint.timestamp;
    bp->hashmsg = checkpoint.blockhash.hash;
    bp->myind = myind;
    while ( bp->isratify == 0 && dp->destupdated == 0 )
    {
        if ( dp->checkpoint.blockhash.height > checkpoint.blockhash.height )
        {
            printf("abort %s ht.%d due to new checkpoint.%d\n",dp->symbol,checkpoint.blockhash.height,dp->checkpoint.blockhash.height);
            dp->ratifying -= bp->isratify;
            return;
        }
        sleep(1);
    }
    starttime = (uint32_t)time(NULL);
    if ( bp->isratify == 0 )
    {
        //if ( (starttime= checkpoint.timestamp) == 0 )
            bp->starttime = starttime;
        extralen = dpow_paxpending(extras,&bp->paxwdcrc);
        bp->notaries[bp->myind].paxwdcrc = bp->paxwdcrc;
    }
    printf("PAXWDCRC.%x myind.%d isratify.%d DPOW.%s statemachine checkpoint.%d %s start.%u+dur.%d vs %ld\n",bp->paxwdcrc,bp->myind,bp->isratify,src->symbol,checkpoint.blockhash.height,bits256_str(str,checkpoint.blockhash.hash),starttime,bp->duration,time(NULL));
    for (i=0; i<sizeof(srchash); i++)
        srchash.bytes[i] = dp->minerkey33[i+1];
    //printf("start utxosync start.%u %u\n",starttime,(uint32_t)time(NULL));
    //dpow_utxosync(myinfo,dp,bp,0,myind,srchash);
    //printf("done utxosync start.%u %u\n",starttime,(uint32_t)time(NULL));
    while ( time(NULL) < starttime+bp->duration && src != 0 && dest != 0 && bp->state != 0xffffffff )
    {
        if ( bp->isratify == 0 )
        {
            if ( myinfo->DPOWS[0].ratifying != 0 )
            {
                printf("break due to already ratifying\n");
                break;
            }
            extralen = dpow_paxpending(extras,&bp->paxwdcrc);
            bp->notaries[bp->myind].paxwdcrc = bp->paxwdcrc;
        }
        sleep(13);
        if ( dp->checkpoint.blockhash.height > checkpoint.blockhash.height )
        {
            if ( bp->isratify == 0 )
            {
                printf("abort %s ht.%d due to new checkpoint.%d\n",dp->symbol,checkpoint.blockhash.height,dp->checkpoint.blockhash.height);
                break;
            }
        }
        if ( dp->ratifying > 1 )
        {
            printf("new ratification started. abort ht.%d\n",bp->height);
            break;
        }
        if ( bp->isratify == 0 )
        {
            bits256 checkhash;
            checkhash = dpow_getblockhash(myinfo,bp->srccoin,bp->height);
            if ( bits256_cmp(checkhash,bp->hashmsg) != 0 )
            {
                printf("%s ht.%d %s got reorged to %s, abort notarization\n",bp->srccoin->symbol,bp->height,bits256_str(str,bp->hashmsg),bits256_str(str2,checkhash));
                bp->state = 0xffffffff;
            }
        }
        if ( bp->state != 0xffffffff )
        {
            dpow_send(myinfo,dp,bp,srchash,bp->hashmsg,0,bp->height,(void *)"ping",0);
            dpow_nanomsg_update(myinfo);
        }
        else
        {
            dp->lastnotarized = checkpoint.blockhash.hash;
            printf("notarized %s %s\n",dp->symbol,bits256_str(str,checkpoint.blockhash.hash));
        }
        if ( 0 && dp->cancelratify != 0 && bp->isratify != 0 )
        {
            printf("abort pending ratify\n");
            break;
        }
    }
    printf("END isratify.%d:%d bestk.%d %llx sigs.%llx state.%x machine ht.%d completed state.%x %s.%s %s.%s recvmask.%llx paxwdcrc.%x %p %p\n",bp->isratify,dp->ratifying,bp->bestk,(long long)bp->bestmask,(long long)(bp->bestk>=0?bp->destsigsmasks[bp->bestk]:0),bp->state,bp->height,bp->state,dp->dest,bits256_str(str,bp->desttxid),dp->symbol,bits256_str(str2,bp->srctxid),(long long)bp->recvmask,bp->paxwdcrc,src,dest);
    bp->state = 0xffffffff;
    dp->lastrecvmask = bp->recvmask;
    dp->ratifying -= bp->isratify;
    dp->blocks[bp->height] = 0;
    free(ptr);
}
Esempio n. 14
0
cJSON *LP_NXT_redeems()
{
    char url[1024],*retstr,*recv,*method,*msgstr,assetname[128]; uint64_t totals[2][sizeof(assetids)/sizeof(*assetids)],mult,txnum,assetid,qty; int32_t i,ind,numtx=0,past_marker=0; cJSON *item,*attach,*decjson,*array,*msgjson,*encjson,*retjson=0;
    //sleep 1; fiat/supernet sendtoaddress RNZZuQYu8xJLZHuekhd96hYfoQuiCMz99T 1001.44150000 # txnum.8537615468620726612
    //sleep 1; fiat/pangea sendtoaddress RWMdRaUmMZqKkEibwEhY6XS3RLCXJDWHTi 22.10910000 # txnum.2649622877615958504
    uint64_t txnum_marker = calc_nxt64bits("8537615468620726612"); // 2649622877615958504"); // set to most recent processed
    uint64_t txnum_marker2 = calc_nxt64bits("7256847492742571143"); // dont change, end marker
    char *passphrase = "";
    char *account = "NXT-MRBN-8DFH-PFMK-A4DBM";
    memset(totals,0,sizeof(totals));
    sprintf(url,"http://127.0.0.1:7876/nxt?requestType=getBlockchainTransactions&account=%s",account);
    //printf("calling (%s)\n",url);
    if ( (retstr= issue_curlt(url,LP_HTTP_TIMEOUT)) != 0 )
    {
        //printf("got.(%s)\n",retstr);
        if ( (retjson= cJSON_Parse(retstr)) != 0 )
        {
            if ( (array= jarray(&numtx,retjson,"transactions")) != 0 )
            {
                for (i=0; i<numtx; i++)
                {
                    msgjson = encjson = decjson = 0;
                    txnum = assetid = qty = 0;
                    item = jitem(array,i);
                    msgstr = jstr(item,"message");
                    txnum = j64bits(item,"transaction");
                    if ( txnum == txnum_marker )
                        past_marker = 1;
                    //printf("%d: %s\n",i,jprint(item,0));
                    if ( (recv= jstr(item,"recipientRS")) != 0 && strcmp(recv,"NXT-MRBN-8DFH-PFMK-A4DBM") == 0 )
                    {
                        if ( (attach= jobj(item,"attachment")) != 0 && jint(attach,"version.AssetTransfer") == 1 )
                        {
                            assetid = j64bits(attach,"asset");
                            qty = j64bits(attach,"quantityQNT");
                            //printf("txnum.%llu (%s)\n",(long long)txnum,jprint(attach,0));
                            if ( (msgstr == 0 || msgstr[0] == 0) && jint(attach,"version.PrunablePlainMessage") == 1 )
                            {
                                method = "getPrunableMessage";
                                if ( (msgjson= LP_NXT_message(method,txnum,"test")) != 0 )
                                {
                                    msgstr = jstr(msgjson,"message");
                                    //printf("%d method.(%s) (%s)\n",i,method,msgstr);
                                }
                            }
                            if ( msgstr == 0 || msgstr[0] == 0 )
                                msgstr = jstr(attach,"message");
                            if ( msgstr == 0 || msgstr[0] == 0 )
                            {
                                
                                if ( (encjson= jobj(attach,"encryptedMessage")) != 0 )
                                {
                                    msgstr = "encryptedMessage";//jstr(encjson,"data");
                                    if ( (decjson= LP_NXT_decrypt(txnum,account,jstr(encjson,"data"),jstr(encjson,"nonce"),passphrase)) != 0 )
                                    {
                                        //printf("%s\n",jprint(decjson,0));
                                        if ( jstr(decjson,"decryptedMessage") != 0 )
                                            msgstr = jstr(decjson,"decryptedMessage");
                                    }
                                }
                            }
                        }
                        mult = LP_assetid_mult(&ind,assetname,assetid);
                        if ( ind >= 0 )
                            totals[past_marker][ind] += qty * mult;
                        if ( msgstr != 0 && assetname[0] != 0 && qty != 0 )
                        {
                            char validaddress[64]; int32_t z,n;
                            n = (int32_t)strlen(msgstr);
                            for (z=0; z<n; z++)
                            {
                                if ( msgstr[z] == 'R' )
                                    break;
                            }
                            memset(validaddress,0,sizeof(validaddress));
                            if ( n-z >= 34 )
                                strncpy(validaddress,&msgstr[z],34);
                            if ( txnum == calc_nxt64bits("4545341872872347590") )
                                strcpy(validaddress,"RKuwq4oi4mqQ2V4r54mPEthn3TBrEwu2Ni");
                            if ( past_marker == 0 )
                            {
                                if ( strlen(validaddress) == 34 || strlen(validaddress) == 33 )
                                {
                                    //printf("%-4d: (%34s) <- %13.5f %10s tx.%llu past_marker.%d\n",i,validaddress,dstr(qty * mult),assetname,(long long)txnum,past_marker);
                                    LP_sendtoaddress_line(validaddress,assetname,(qty * mult),txnum);
                                } else printf("%-4d: (%34s) <- %13.5f %10s tx.%llu\n",i,msgstr!=0?msgstr:jprint(item,0),dstr(qty * mult),assetname,(long long)txnum);
                            }
                        }
                        if ( msgjson != 0 )
                            free_json(msgjson);
                        if ( decjson != 0 )
                            free_json(decjson);
                    }
                    if ( txnum == txnum_marker2 )
                        break;
                }
            }
            //free_json(retjson);
        }
        free(retstr);
    } else printf("null return from NXT api call\n");
    printf("\nTotal redeemed.%d\n",numtx);
    for (past_marker=0; past_marker<2; past_marker++)
    {
        for (i=0; i<sizeof(totals[0])/sizeof(*totals[0]); i++)
        {
            if ( totals[past_marker][i] != 0 )
                printf("%-10s %13.5f past_marker.%d\n",assetids[i][1],dstr(totals[past_marker][i]),past_marker);
        }
        printf("\n>>>>>>>>>> already processed:\n");
    }
    return(retjson);
}
Esempio n. 15
0
void PAX_update(struct peggy_info *PEGS,double *btcusdp,double *btcdbtcp)
{
    int32_t i,n,seconds,datenum; uint32_t timestamp; char url[1024],*dstr,*str;
    double btcddaily=0.,btcusd=0.,ask,high,low,bid,close,vol,quotevol,open,price = 0.;
    //cJSON *btcdtrades,*btcdtrades2,*,*bitcoincharts,;
    cJSON *quandl,*btcdhist,*array,*item,*bitcoinave,*blockchaininfo,*coindesk=0;
    //btcdtrades = url_json("https://poloniex.com/public?command=returnTradeHistory&currencyPair=BTC_BTCD");
    //btcdtrades2 = url_json("https://bittrex.com/api/v1.1/public/getmarkethistory?market=BTC-BTCD&count=50");
    bitcoinave = url_json("https://api.bitcoinaverage.com/ticker/USD/");
    //bitcoincharts = url_json("http://api.bitcoincharts.com/v1/weighted_prices.json");
    blockchaininfo = url_json("https://blockchain.info/ticker");
    coindesk = url_json("http://api.coindesk.com/v1/bpi/historical/close.json");
    sprintf(url,"https://poloniex.com/public?command=returnChartData&currencyPair=BTC_BTCD&start=%ld&end=9999999999&period=86400",(long)(time(NULL)-2*3600*24));
    quandl = url_json("https://www.quandl.com/api/v1/datasets/BAVERAGE/USD.json?rows=1");
    if ( quandl != 0 && (str= jstr(quandl,"updated_at")) != 0 && (datenum= conv_date(&seconds,str)) > 0 && (array= jarray(&n,quandl,"data")) != 0 )
    {
        //printf("datenum.%d data.%d %d\n",datenum,n,cJSON_GetArraySize(array));
        for (i=0; i<1; i++)
        {
            // ["Date","24h Average","Ask","Bid","Last","Total Volume"]
            // ["2015-07-25",289.27,288.84,288.68,288.87,44978.61]
            item = jitem(array,i);
            if ( (dstr= jstr(jitem(item,0),0)) != 0 && (datenum= conv_date(&seconds,dstr)) > 0 )
            {
                btcusd = price = jdouble(jitem(item,1),0), ask = jdouble(jitem(item,2),0), bid = jdouble(jitem(item,3),0);
                close = jdouble(jitem(item,4),0), vol = jdouble(jitem(item,5),0);
                //fprintf(stderr,"%d.[%d %f %f %f %f %f].%d ",i,datenum,price,ask,bid,close,vol,n);
            }
        }
    }
    {
        double avebid,aveask,bidvol,askvol; struct exchange_quote sortbuf[512];
        struct supernet_info *myinfo = SuperNET_MYINFO(0); cJSON *argjson = cJSON_Parse("{}");
        aveask = instantdex_aveprice(myinfo,sortbuf,(int32_t)(sizeof(sortbuf)/sizeof(*sortbuf)),&askvol,"BTCD","BTC",1,argjson);
        avebid = instantdex_aveprice(myinfo,sortbuf,(int32_t)(sizeof(sortbuf)/sizeof(*sortbuf)),&bidvol,"BTCD","BTC",-1,argjson);
        if ( avebid > SMALLVAL && aveask > SMALLVAL )
        {
            price = (avebid*bidvol + aveask*askvol) / (bidvol + askvol);
            *btcdbtcp = price;
            printf("set BTCD price %f\n",price);
            PEGS->btcdbtc = price;
        }
        else
        {
            btcdhist = url_json(url);
            //{"date":1406160000,"high":0.01,"low":0.00125,"open":0.01,"close":0.001375,"volume":1.50179994,"quoteVolume":903.58818412,"weightedAverage":0.00166204},
            if ( btcdhist != 0 && (array= jarray(&n,btcdhist,0)) != 0 )
            {
                //printf("GOT.(%s)\n",cJSON_Print(array));
                for (i=0; i<1; i++)
                {
                    item = jitem(array,i);
                    timestamp = juint(item,"date"), high = jdouble(item,"high"), low = jdouble(item,"low"), open = jdouble(item,"open");
                    close = jdouble(item,"close"), vol = jdouble(item,"volume"), quotevol = jdouble(item,"quoteVolume"), price = jdouble(item,"weightedAverage");
                    //printf("[%u %f %f %f %f %f %f %f]",timestamp,high,low,open,close,vol,quotevol,price);
                    //printf("[%u %d %f]",timestamp,OS_conv_unixtime(&seconds,timestamp),price);
                    btcddaily = price;
                    if ( btcddaily != 0 )
                        PEGS->btcdbtc = *btcdbtcp = btcddaily;
                }
                //printf("poloniex.%d\n",n);
            }
            if ( btcdhist != 0 )
                free_json(btcdhist);
        }
    }
    if ( bitcoinave != 0 )
    {
        if ( (price= jdouble(bitcoinave,"24h_avg")) > SMALLVAL )
        {
            //printf("bitcoinave %f %f\n",btcusd,price);
            dxblend(&btcusd,price,0.5);
        }
        free_json(bitcoinave);
    }
    if ( quandl != 0 )
        free_json(quandl);
    if ( coindesk != 0 )
        free_json(coindesk);
    if ( blockchaininfo != 0 )
    {
        if ( (item= jobj(blockchaininfo,"USD")) != 0 && item != 0 && (price= jdouble(item,"15m")) > SMALLVAL )
        {
            //printf("blockchaininfo %f %f\n",btcusd,price);
            dxblend(&btcusd,price,0.5);
        }
        free_json(blockchaininfo);
    }
    if ( btcusd != 0 )
        PEGS->btcusd = *btcusdp = btcusd;
}
Esempio n. 16
0
void PAX_btcprices(struct peggy_info *PEGS,int32_t enddatenum,int32_t numdates)
{
    int32_t i,n,year,month,day,seconds,datenum; char url[1024],date[64],*dstr,*str;
    uint32_t timestamp,utc32[MAX_SPLINES]; struct tai t;
    cJSON *coindesk,*quandl,*btcdhist,*bpi,*array,*item;
    double btcddaily[MAX_SPLINES],cdaily[MAX_SPLINES],qdaily[MAX_SPLINES],ask,high,low,bid,close,vol,quotevol,open,price = 0.;
    coindesk = url_json("http://api.coindesk.com/v1/bpi/historical/close.json");
    sprintf(url,"https://poloniex.com/public?command=returnChartData&currencyPair=BTC_BTCD&start=%ld&end=9999999999&period=86400",(long)(time(NULL)-numdates*3600*24));
    if ( (bpi= jobj(coindesk,"bpi")) != 0 )
    {
        datenum = enddatenum;
        memset(utc32,0,sizeof(utc32));
        memset(cdaily,0,sizeof(cdaily));
        if ( datenum == 0 )
        {
            datenum = OS_conv_unixtime(&t,&seconds,(uint32_t)time(NULL));
            printf("got datenum.%d %d %d %d\n",datenum,seconds/3600,(seconds/60)%24,seconds%60);
        }
        for (i=0; i<numdates; i++)
        {
            expand_datenum(date,datenum);
            if ( (price= jdouble(bpi,date)) != 0 )
            {
                utc32[numdates - 1 - i] = OS_conv_datenum(datenum,12,0,0);
                cdaily[numdates - 1 - i] = price * .001;
                //printf("(%s %u %f) ",date,utc32[numdates - 1 - i],price);
            }
            datenum = ecb_decrdate(&year,&month,&day,date,datenum);
        }
        PAX_genspline(&PEGS->splines[MAX_CURRENCIES],MAX_CURRENCIES,"coindesk",utc32,cdaily,numdates,cdaily);
        
    } else printf("no bpi\n");
    quandl = url_json("https://www.quandl.com/api/v1/datasets/BAVERAGE/USD.json?rows=64");
    if ( (str= jstr(quandl,"updated_at")) != 0 && (datenum= conv_date(&seconds,str)) > 0 && (array= jarray(&n,quandl,"data")) != 0 )
    {
        printf("datenum.%d data.%d %d\n",datenum,n,cJSON_GetArraySize(array));
        memset(utc32,0,sizeof(utc32)), memset(qdaily,0,sizeof(qdaily));
        for (i=0; i<n&&i<MAX_SPLINES; i++)
        {
            // ["Date","24h Average","Ask","Bid","Last","Total Volume"]
            // ["2015-07-25",289.27,288.84,288.68,288.87,44978.61]
            item = jitem(array,i);
            if ( Debuglevel > 2 )
                printf("(%s) ",cJSON_Print(item));
            if ( (dstr= jstr(jitem(item,0),0)) != 0 && (datenum= conv_date(&seconds,dstr)) > 0 )
            {
                price = jdouble(jitem(item,1),0), ask = jdouble(jitem(item,2),0), bid = jdouble(jitem(item,3),0);
                close = jdouble(jitem(item,4),0), vol = jdouble(jitem(item,5),0);
                if ( Debuglevel > 2 )
                    fprintf(stderr,"%d.[%d %f %f %f %f %f].%d ",i,datenum,price,ask,bid,close,vol,n);
                utc32[numdates - 1 - i] = OS_conv_datenum(datenum,12,0,0), qdaily[numdates - 1 - i] = price * .001;
            }
        }
        PAX_genspline(&PEGS->splines[MAX_CURRENCIES+1],MAX_CURRENCIES+1,"quandl",utc32,qdaily,n<MAX_SPLINES?n:MAX_SPLINES,qdaily);
    }
    btcdhist = url_json(url);
    //{"date":1406160000,"high":0.01,"low":0.00125,"open":0.01,"close":0.001375,"volume":1.50179994,"quoteVolume":903.58818412,"weightedAverage":0.00166204},
    if ( (array= jarray(&n,btcdhist,0)) != 0 )
    {
        memset(utc32,0,sizeof(utc32)), memset(btcddaily,0,sizeof(btcddaily));
        //printf("GOT.(%s)\n",cJSON_Print(array));
        for (i=0; i<n; i++)
        {
            item = jitem(array,i);
            timestamp = juint(item,"date"), high = jdouble(item,"high"), low = jdouble(item,"low"), open = jdouble(item,"open");
            close = jdouble(item,"close"), vol = jdouble(item,"volume"), quotevol = jdouble(item,"quoteVolume"), price = jdouble(item,"weightedAverage");
            //printf("[%u %f %f %f %f %f %f %f]",timestamp,high,low,open,close,vol,quotevol,price);
            if ( Debuglevel > 2 )
                printf("[%u %d %f]",timestamp,OS_conv_unixtime(&t,&seconds,timestamp),price);
            utc32[i] = timestamp - 12*3600, btcddaily[i] = price * 100.;
        }
        if ( Debuglevel > 2 )
            printf("poloniex.%d\n",n);
        PAX_genspline(&PEGS->splines[MAX_CURRENCIES+2],MAX_CURRENCIES+2,"btcdhist",utc32,btcddaily,n<MAX_SPLINES?n:MAX_SPLINES,btcddaily);
    }
    // https://poloniex.com/public?command=returnChartData&currencyPair=BTC_BTCD&start=1405699200&end=9999999999&period=86400
}
Esempio n. 17
0
double PAX_yahoo(char *metal)
{
    // http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json
    // http://finance.yahoo.com/webservice/v1/symbols/XAU=X/quote?format=json
    // http://finance.yahoo.com/webservice/v1/symbols/XAG=X/quote?format=json
    // http://finance.yahoo.com/webservice/v1/symbols/XPT=X/quote?format=json
    // http://finance.yahoo.com/webservice/v1/symbols/XPD=X/quote?format=json
    char url[1024],*jsonstr; cJSON *json,*obj,*robj,*item,*field; double price = 0.;
    sprintf(url,"http://finance.yahoo.com/webservice/v1/symbols/%s=X/quote?format=json",metal);
    if ( (jsonstr= issue_curl(url)) != 0 )
    {
        //printf("(%s)\n",jsonstr);
        if ( (json= cJSON_Parse(jsonstr)) != 0 )
        {
            if ( (obj= jobj(json,"list")) != 0 && (robj= jobj(obj,"resources")) != 0 && (item= jitem(robj,0)) != 0 )
            {
                if ( (robj= jobj(item,"resource")) != 0 && (field= jobj(robj,"fields")) != 0 && (price= jdouble(field,"price")) != 0 )
                    price = 1. / price;
            }
            free_json(json);
        }
        free(jsonstr);
    }
    if ( Debuglevel > 2 )
        printf("(%s %f) ",metal,price);
    return(price);
}