How to change Binance server time using Python? - time

Question
How can I change the server time of Binance, one of the biggest cryptocurrency exchange, using the programming language Python?
Details
I am using the python library `python-binance' to interact with Binance.
When I typed the code below, you get the local time based on your location.
from binance.client import Client
from datetime import datetime
# client = Client('api_key' , 'api_secret') # Binance API key
raw_server_time = client.get_server_time()
server_time = datetime.fromtimestamp(raw_server_time['serverTime']/1000.0)
server_time
Since I am in France, the result is as follows:
>>> datetime.datetime(2020, 5, 23, 12, 49, 10, 13000)
Even though I am in France, I would like to make Binance think that I am in the Eastern part of the USA (e.g. New York). So I have tried the requests library, supported in the python-binance library as below.
proxies = {
'http': 'http://168.169.146.12:8080'
}
# in the Client instantiation
client = Client(api_key, api_secret, {'proxies': proxies})
# or on an individual call
client.get_all_orders(symbol='BTCUSDT', requests_params={'proxies': proxies})
But I get the following error message.
>>> BinanceAPIException: APIError(code=-1021): Timestamp for this request was 1000ms ahead of the server's time.
You can find more detailed information about the code above in the documentation page of the python-binance library. The http server was found in the website free-proxy.cz. A screenshot of the list of New-York based proxies are also provided below.

If you are running Windows 10, or Windows 11, do the following:
Start -> search date and time
Make sure you have set Set time automatically to On
In the opened window you have an option Synchronize your clock, and press Sync now.
I observed this problem sometimes after my PC goes to sleep.

I got this error too, while writing python code in Microsoft Visual Code(MVC).
When i kept my Bot running, this also happens over time while bot was active. So i needed the Bot to alter my computer time. I found the following sollution:
How to adjust my computer time:
important to run program as 'Administrator', and have WindowsTime active.
Search in 'services' for WindowsTime and make sure this is running/active. Auto-run on startup if needed
At this line of code on startup of the Bot:
import os
os.system('w32tm/resync')
Keeping Bot active over time
After i synced the time at the start, i am monitoring error responses from binance for the TimeStamp error. When the timestamp message is found it will resync my computer time again.
try:
###put for example buy code here###
except Exception as e:
print(e)
substring = 'Timestamp for this request was 1000ms ahead of the server'
if substring in e.message:
os.system('w32tm/resync')
Hopes this helps you all.

import time
import win32api
client = Client(api_key, api_secret)
server_time = client.get_server_time()
gmtime=time.gmtime(int((server_time["serverTime"])/1000))
win32api.SetSystemTime(gmtime[0],gmtime[1],0,gmtime[2],gmtime[3],gmtime[4],gmtime[5],0) // Needed Administrator Permission

For Windows, try this: https://steemit.com/crypto/#biyi/how-to-resolve-binance-s-timestamp-ahead-of-server-s-time-challenge
net stop w32time
w32tm /unregister
w32tm /register
net start w32time
w32tm /resync

Related

Uncaught Error: Returned values aren't valid, did it run Out of Gas?

I'm listening to events of my deployed contract. Whenever a transaction gets completed and event is fired receiving the response causes following error:
Uncaught Error: Returned values aren't valid, did it run Out of Gas?
at ABICoder.push../node_modules/web3-eth-abi/src/index.js.ABICoder.decodeParameters
(index.js:227)
at ABICoder.push../node_modules/web3-eth-abi/src/index.js.ABICoder.decodeLog
(index.js:277)
Web3 version: 1.0.0-beta36
Metamask version: 4.16.0
How to fix it?
Try the command truffle migrate --reset so that all the previous values are reset to their original value
Throws the same error when inside a transaction it generates different events with the same name and the same arguments. In my case, this was the Transfer event from ERC721 and ERC20. Renaming one of them solves this problem, but of course this isn't the right way.
This is a bug in web3js, discussed here.
And the following change fixes it (source):
patch-package
--- a/node_modules/web3-eth-abi/src/index.js
+++ b/node_modules/web3-eth-abi/src/index.js
## -280,7 +280,7 ## ABICoder.prototype.decodeLog = function (inputs, data, topics) {
var nonIndexedData = data;
- var notIndexedParams = (nonIndexedData) ? this.decodeParameters(notIndexedInputs, nonIndexedData) : [];
+ var notIndexedParams = (nonIndexedData && nonIndexedData !== '0x') ? this.decodeParameters(notIndexedInputs, nonIndexedData) : [];
var returnValue = new Result();
returnValue.__length__ = 0;
Edit: Also downgrading to web3-1.0.0.beta33 also fixes this issue too.
Before even checking your ABI or redeploying, check to make sure Metamask is connected to whichever network your contract is actually deployed too. I stepped away and while i was afk Metamask logged out, I guess I wasn't watching closely and I was connected to Ropsten when I working on localhost. Simple mistake, wasted an hour or so trying to figure it out. Hope this helps someone else out!
This happened to me on my react app.
I deployed to contract to Ropsten network, but metamask was using the Rinkeby aaccount. So make sure whichever network you deployed, metamask should be using account from that network.
The solution for me was changing of provider. With Infura the error is gone, but with Alchemy is still happening.
Please check your Metamask Login, This issue is generally populated when you are either log out of the Metamask or worse case you have 0 ether left at your account.
This can also happen when the MNEMONIC value from Ganache is different from the one you have in your truffle.js or truffle-config.js file.

Wifi WPS client start in Windows 10 in script or code

I can not find how to start WPS client in Windows 10 from command prompt or powershell. When I used Linux, everything was really ease with wla_supplicant (wpa_cli wps_pbc). Is there something similar in Windows?
Does anyone know how to set up Wi-Fi network (over WPS) key without human input in Windows?
I also tried WCN (Windows Connect Now) from Microsoft as it implements WPS features. I got also samples from Windows SDK on WCN, but they could not get key by WPS (it faild). But if I use Windows user interface to connect wiothout PIN, everyting seems to be pretty fine.
I am sure that there is possibility to do that, it is very important to perform Wifi Protected Setup by button start from the command prompt or app (C++/C#) without human intrusion or input (once WPS is on air, Windows should automatically get the network key and connect then).
I don't know if it's too late to answer, just put what I know in here and hope it can help.
First, if your system has updated to 16299(Fall Creator Update), you can just simply use new wifi api from UWP.
Install newest Windows SDK, create a C# console project, target C# version to at least 7.1, then add two reference to the project.
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.16299.0\Windows.winmd
After all of that , code in below should work.
using System;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Devices.WiFi;
class Program
{
static async Task Main(string[] args)
{
var dic = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());
if (dic.Count > 0)
{
var adapter = await WiFiAdapter.FromIdAsync(dic[0].Id);
foreach (var an in adapter.NetworkReport.AvailableNetworks)
{
if (an.Ssid == "Ssid which you want to connect to.")
{
// Fouth parameter which is ssid can not be set to null even if we provided
// first one, or an exception will be thrown.
await adapter.ConnectAsync(an, WiFiReconnectionKind.Manual, null, "",
WiFiConnectionMethod.WpsPushButton);
}
}
}
}
}
Build and run the exe, then push your router's button, your pc will be connect to the router.
But if you can not update to 16299, WCN will be your only choice. You may already notice that if call IWCNDevic::Connect frist with push-button method, the WSC(Wifi Simple Configuration) session will fail. That's because WNC would not start a push-button session as a enrollee, but only as a registrar. That means you have to ensure that router's button has been pushed before you call IWCNDevic::Connect. The way to do that is using Native Wifi api to scan your router repeatedly, analyse the newest WSC information element from the scan result, confirm that Selected Registrar attribute has been set to true and Device Password Id attribute has been set to 4. After that, query the IWCNDevice and call Connect function will succeed. Then you can call IWCNDevice::GetNetworkProfile to get a profile that can use to connect to the router. Because it's too much of code, I will only list the main wifi api that will be used.
WlanEnuminterfaces: Use to get a available wifi interface.
WlanRegisterNotification: Use to register a callback to handle scan an connect results.
WlanScan: Use to scan a specified wifi BSS.
WlanGetNetworkBsslist: Use to get newest BSS information after scan.
WlanSetProfile: Use to save profile for a BSS.
WlanConnect: Use to connect to a BSS.
And about the WSC information element and it's attributes, you can find all the information from Wi-Fi Simple Configuration Technical Specification v2.0.5.
For Krisz. About timeout.
You can't cast IAsyncOperation to Task directly. The right way to do that is using AsTask method. And also, you should cancel ConnectAsync after timeout.
Sample code:
var t = adapter.ConnectAsync(an, WiFiReconnectionKind.Manual, null, "",
WiFiConnectionMethod.WpsPushButton).AsTask();
if (!t.Wait(10000))
t.AsAsyncOperation().Cancel();

Microsoft Edge does not allow localhost loopback for websockets

I have web-site and desktop application, and I want to connect them by websockets. So my web-site tries to connect to wss://localhost:8080, for example.
It works in IE11, but in "MS Edge" I have an error:
Cross zone request is not allowed
I have this problem on Win10 10240, so the flag "Allow localhost loopback" is enabled by default, and it did not help.
When I use CheckNetIsolation LoopbackExempt -a -n="Microsoft.MicrosoftEdge_8wekyb3d8bbwe" or this utility, all works as expected.
So, is this a case, that in new builds of "MS Edge" loopbacks are allowed for http, but not allowed for websockets?
And if so, is it possible to make some workaround, and not to force my users to run some shell comand or to download externall utility?
Related question: Can't open localhost in Microsoft Edge (Project Spartan) in Windows 10 preview
In the Microsoft Edge browser type "About:flags" in the title bar (search bar). No quotes, Tick/Un-tick the "allow Localhost Loopback" feature.
Edge on Win Build 10240. (still works upto New Edge (chrome based))
After some research I found the source of error. Here is my repo, to reproduce error: https://github.com/AZaviruha/ms-edge-ws-strange
In short, when you call new WebSocket in MS Edge, it does not generate exception, when you call it with wrong "local"-host argument:
var socket, path;
var hosts = ['localhost', '127.0.0.1'];
for (var i in hosts) {
path = 'ws://'+hosts[i]+':9446';
console.log( '===> Tested path :: ', path );
try {
socket = new WebSocket( path );
break;
}
catch ( e ) {
// !!! Never shown !!!
console.error( '===> WebSocket creation error :: ', e );
}
}
Because of this, you can't "retry" to connect with different hosts.
By the way, if you try non-local non-existent host, it will generate exception!
This recently happened to me again after doing the Windows 10 Creator's Update (1703).
But the fix was easy. I had to
Check the "allow Localhost Loopback" feature mentioned by #Narcarsiss (not sure if that got disabled in the update, or I just never checked it myself previously).
Specify the protocol in the address bar (http://localhost:5000/ instead of just localhost:5000/).
After doing both I was able to access my localhost sites again in MS Edge.

Actionscript 4: NetConnection.connect(...) does not fire a NetStatusEvent event

I downloaded the red5-recorder (http://www.red5-recorder.com/) , which fails to allow me to start recording. After debugging I found that the netconnection, needed to record to a media server, created does not fire a NetStatusEvent event, so essentially it fails silently. I have implemented the connection with the following minimal working example:
trace("make net connection");
nc = new NetConnection();
nc.client = { onBWDone: function():void{ trace("bandwidth check done.") } };
trace("add event listener");
nc.addEventListener(NetStatusEvent.NET_STATUS, function(event:NetStatusEvent) {
trace("handle");
});
trace("connect!");
nc.connect("rtmp://localshost/oflaDemo/test/");
trace("connect done");
The output of this piece of code is:
make net connection
add event listener
connect!
connect done
The actionscript api states that the connect-call always fires such an event:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetConnection.html#includeExamplesSummary
Moreover, the netconnection is not 'connected' (a state of the NetConnection object) 10 seconds after the call. I also took a look at this: NetConnect fails silently in Flash when called from SilverLight But the fix suggested by the author, swapping rtmp and http in the connection uri, do not work. Also, I tested the uri and in fact the exact same code sniplet in a personal project, where it did work. I just can not seem to find why connecting to a media server fails silently in the red5-recorder project.
The awkward part is that if I pass some random string as a conenction uri, still nothing happens (no event, no exception, no crash). Also not setting nc.client becore nc.connect(), which caused exceptions in my experience, did not cause exceptions.
Any suggestions are welcome.
You are setting the address to localshost instead localhost.
nc.connect("rtmp://localshost/oflaDemo/test/");
Correct address:
nc.connect("rtmp://localhost/oflaDemo/test/");

Implementing Timeout on BackgroundTransferService transfer request - Windows Phone

I am using BackgroundTransferService to download a file from the internet.
pseudo code goes something like this:
BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);
transferRequest.Method = "GET";
transferRequest.Tag = "myTag";
transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
BackgroundTransferService.Add(transferRequest);
after this, i add an event handler to handle the transfer when it is completed.
I am only using TransferStatusChanged event handler, not TransferProgressChanged
transferRequests = BackgroundTransferService.Requests;
transferRequests.Last().TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferStatusChanged);
under transfer_TransferStatusChanged() i do whatever i want to do with my downloaded file, or handle the failed situations (404 etc).
The problem is that my downloads go on for indefinite time if there is no 404 response from the server (for example when there is no such server, eg. www.googlea.com/myfilename). I want to implement a timeout for such scenario .. how can i do that ?
There is no built in support for such a scenario. You'll have to build in the timeout support yourself.
Be careful of transfering large files though as the transfer could be done in parts and over a very large period of time, depending on connectivity and battery charge level.
Of course, you may want to add a check that a file exists before making the transfer request and if you have any control over the server you should make sure that the correct responses are being sent too.

Resources